load-oxfmt-config 0.12.1 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,7 +10,7 @@
10
10
  ## Features
11
11
 
12
12
  - 🔍 **Auto-discovery** - Automatically searches for config files in current and parent directories
13
- - 📦 **Multiple formats** - Auto-discovers `.oxfmtrc.json`, `.oxfmtrc.jsonc`, and `oxfmt.config.ts`, and also supports explicit `.js` / `.mjs` / `.cjs` / `.mts` / `.cts` config paths
13
+ - 📦 **Multiple formats** - Auto-discovers `.oxfmtrc.json`, `.oxfmtrc.jsonc`, and `oxfmt.config.ts`, and also supports explicit `.json` / `.jsonc` / `.js` / `.mjs` / `.cjs` / `.ts` / `.mts` / `.cts` config paths
14
14
  - 🧩 **EditorConfig fallback** - Merges supported `.editorconfig` fields into the returned oxfmt config result
15
15
  - 🚫 **Ignore resolution** - Resolves ignore status with oxfmt CLI-like global + config-scoped semantics
16
16
  - ⚡ **Built-in caching** - Caches both file resolution and parsed configs for optimal performance
@@ -247,10 +247,10 @@ Control how `.editorconfig` files are read and merged:
247
247
  - **`false`** — Disable `.editorconfig` reading entirely.
248
248
  - **`EditorconfigOption`** — Enable with additional settings:
249
249
 
250
- | Property | Type | Default | Description |
251
- | --------- | --------- | ----------- | --------------------------------------------------------------------------------------------------------------------- |
252
- | `onlyCwd` | `boolean` | `false` | When `true`, only look for `.editorconfig` in `cwd` itself — no upward traversal. |
253
- | `cwd` | `string` | `undefined` | Override the directory from which `.editorconfig` resolution starts, instead of the config file's directory or `cwd`. |
250
+ | Property | Type | Default | Description |
251
+ | --------- | --------- | ----------- | ------------------------------------------------------------------------------------------------------------- |
252
+ | `onlyCwd` | `boolean` | `false` | When `true`, only look for `.editorconfig` in `cwd` itself — no upward traversal. |
253
+ | `cwd` | `string` | `undefined` | Override the directory from which `.editorconfig` resolution starts, instead of the default lookup directory. |
254
254
 
255
255
  **Returns:** `Promise<LoadOxfmtConfigResult>`
256
256
 
@@ -309,8 +309,9 @@ When provided, nested config lookup is disabled (same as oxfmt CLI `-c`).
309
309
  - **Type:** `string | string[]`
310
310
  - **Default:** `undefined`
311
311
 
312
- Ignore files to use instead of default `.gitignore` hierarchy + cwd `.prettierignore`.
312
+ Ignore files to use instead of the default cwd `.prettierignore`.
313
313
  Can be passed multiple times in CLI style.
314
+ Explicit ignore paths do not replace `.gitignore` or `.git/info/exclude` handling.
314
315
 
315
316
  #### `withNodeModules`
316
317
 
@@ -417,6 +418,7 @@ export default {
417
418
 
418
419
  > JavaScript and TypeScript config files are executed while loading config. Only load them from repositories you trust.
419
420
 
421
+ JavaScript and TypeScript config files must provide a default export whose value is an object.
420
422
  When `configPath` is passed explicitly, extensions `.json`, `.jsonc`, `.ts`, `.mts`, `.cts`, `.js`, `.mjs`, and `.cjs` are supported. Extensionless paths are also accepted and parsed as JSON.
421
423
 
422
424
  ## `.editorconfig` Support
@@ -445,21 +447,20 @@ Set `loadConfigForIgnorePatterns: false` to skip config loading entirely and kee
445
447
 
446
448
  Global ignore includes:
447
449
 
448
- - Default ignored directories: `.git`, `.svn`, `.jj`, `node_modules`
449
- - Default lockfiles: `package-lock.json`, `npm-shrinkwrap.json`, `pnpm-lock.yaml`, `yarn.lock`, `bun.lock`, `bun.lockb`
450
+ - Default ignored directories: `.git`, `.jj`, `.sl`, `.svn`, `.hg`, `node_modules`
451
+ - Default lockfiles: `package-lock.json`, `pnpm-lock.yaml`, `yarn.lock`, `MODULE.bazel.lock`, `bun.lock`, `deno.lock`, `composer.lock`, `Package.resolved`, `Pipfile.lock`, `flake.lock`, `Cargo.lock`, `Gopkg.lock`, `pdm.lock`, `poetry.lock`, `uv.lock`, `npm-shrinkwrap.json`, `bun.lockb`
450
452
  - Ignore files:
451
- - If `ignorePath` is provided: use those files only (multiple supported)
452
- - If `ignorePath` is not provided:
453
- - Read `.gitignore` from the file's directory upward until the git repo boundary
454
- - Read `<repo>/.git/info/exclude` when inside a git repo
455
- - Read `.prettierignore` from `cwd`
453
+ - Always read `.gitignore` from the file's directory upward until the git repo boundary
454
+ - Always read `<repo>/.git/info/exclude` when inside a git repo
455
+ - If `ignorePath` is provided: read those files instead of `cwd/.prettierignore`
456
+ - If `ignorePath` is not provided: read `.prettierignore` from `cwd`
456
457
 
457
458
  Notes:
458
459
 
459
460
  - `node_modules` can be included by passing `withNodeModules: true`.
460
461
 
461
462
  - The default lockfile list mirrors oxfmt documentation intent (`package-lock.json`, `pnpm-lock.yaml`, etc.) and common ecosystem lockfiles. It is not guaranteed to be a complete internal oxfmt list.
462
- - `ignorePatterns` are always interpreted relative to the resolved oxfmt config directory.
463
+ - `ignorePatterns` use gitignore semantics and are interpreted relative to the resolved oxfmt config directory.
463
464
  - `includeConfigIgnorePatterns` defaults to `true` to preserve current behavior.
464
465
  - `loadConfigForIgnorePatterns` defaults to `true` to preserve current behavior.
465
466
  - Nested config behavior follows oxfmt semantics:
@@ -477,7 +478,7 @@ The merged result follows this order:
477
478
  3. Overrides generated from `.editorconfig` sections
478
479
  4. Overrides declared directly in the oxfmt config file
479
480
 
480
- This means explicit oxfmt config values always win over `.editorconfig` fallback values.
481
+ This means explicit root-level oxfmt config values win over root-level `.editorconfig` fallback values. Section-specific `.editorconfig` entries are represented as generated `overrides` in the static result, and explicit oxfmt `overrides` are appended after them.
481
482
 
482
483
  ## Limitations
483
484
 
@@ -514,6 +515,7 @@ The caching system maintains two separate caches:
514
515
 
515
516
  - Failed operations automatically clear their cache entries
516
517
  - Use `useCache: false` to bypass cache for specific calls
518
+ - For native ESM config files (`.mjs` or `.js` under `"type": "module"`), `useCache: false` cache-busts the entry config file. Imported ESM helper modules still follow Node.js module cache behavior for the current process.
517
519
  - Cache persists for the lifetime of the Node.js process
518
520
 
519
521
  ## Related
package/dist/index.d.mts CHANGED
@@ -2,7 +2,7 @@ import { FormatConfig } from "oxfmt";
2
2
 
3
3
  //#region src/types.d.ts
4
4
  /**
5
- * Object-form editorconfig option, enabling fine-grained control.
5
+ * Object-form `.editorconfig` option for fine-grained lookup control.
6
6
  */
7
7
  interface EditorconfigOption {
8
8
  /**
@@ -14,38 +14,41 @@ interface EditorconfigOption {
14
14
  onlyCwd?: boolean;
15
15
  /**
16
16
  * Override the directory from which `.editorconfig` resolution starts.
17
- * When set, editorconfig is searched from this directory instead of from
18
- * the config file's directory (or the top-level `cwd`).
19
17
  *
20
- * This is useful when the oxfmt config path is pre-resolved and you still
21
- * want editorconfig to be resolved relative to each file's directory.
18
+ * When set, `.editorconfig` is searched from this directory instead of from
19
+ * the config lookup directory. This is useful when the oxfmt config path is
20
+ * pre-resolved and EditorConfig should still be resolved from another
21
+ * directory, such as each file's directory.
22
22
  */
23
23
  cwd?: string;
24
24
  }
25
25
  /**
26
- * Format option override for a single matching rule
26
+ * Format option override for a single matching rule.
27
27
  */
28
28
  interface OxfmtConfigOverride {
29
29
  /**
30
- * Glob patterns to match files
30
+ * Glob patterns to match files.
31
31
  */
32
32
  files: string[];
33
33
  /**
34
- * Glob patterns to exclude files
34
+ * Glob patterns to exclude files.
35
35
  */
36
36
  excludeFiles?: string[];
37
37
  /**
38
- * Format options to apply
38
+ * Format options to apply.
39
39
  */
40
40
  options?: FormatConfig;
41
41
  }
42
+ /**
43
+ * Options for loading and merging oxfmt configuration.
44
+ */
42
45
  interface LoadOxfmtConfigOptions {
43
46
  /**
44
- * Path to the configuration file
47
+ * Path to the configuration file.
45
48
  */
46
49
  configPath?: string;
47
50
  /**
48
- * Current working directory
51
+ * Current working directory.
49
52
  */
50
53
  cwd?: string;
51
54
  /**
@@ -62,7 +65,9 @@ interface LoadOxfmtConfigOptions {
62
65
  */
63
66
  disableNestedConfig?: boolean;
64
67
  /**
65
- * Whether to use cache
68
+ * Whether to use in-memory caches for path resolution and parsed config contents.
69
+ *
70
+ * @default true
66
71
  */
67
72
  useCache?: boolean;
68
73
  /**
@@ -77,16 +82,17 @@ interface LoadOxfmtConfigOptions {
77
82
  editorconfig?: boolean | EditorconfigOption;
78
83
  }
79
84
  /**
80
- * Final oxfmt options (including overrides)
85
+ * Final oxfmt options, including config `ignorePatterns` and `overrides`.
81
86
  */
82
87
  interface OxfmtOptions extends FormatConfig {
83
88
  /**
84
- * Ignore files matching these glob patterns
85
- * Patterns are based on the location of the Oxfmt configuration file
89
+ * Ignore files matching these glob patterns.
90
+ *
91
+ * Patterns are based on the location of the oxfmt configuration file.
86
92
  */
87
93
  ignorePatterns?: string[];
88
94
  /**
89
- * Array of format option overrides
95
+ * Array of format option overrides.
90
96
  */
91
97
  overrides?: OxfmtConfigOverride[];
92
98
  }
@@ -95,15 +101,15 @@ interface OxfmtOptions extends FormatConfig {
95
101
  */
96
102
  interface LoadOxfmtConfigResult {
97
103
  /**
98
- * Final merged config (oxfmt + optional editorconfig mapping)
104
+ * Final merged config from oxfmt and optional `.editorconfig` mapping.
99
105
  */
100
106
  config: OxfmtOptions;
101
107
  /**
102
- * Absolute path of resolved config file
108
+ * Absolute path of resolved config file.
103
109
  */
104
110
  filepath?: string;
105
111
  /**
106
- * Directory of resolved config file
112
+ * Directory of resolved config file.
107
113
  */
108
114
  dirname?: string;
109
115
  }
@@ -113,6 +119,7 @@ interface LoadOxfmtConfigResult {
113
119
  interface IsOxfmtIgnoredOptions {
114
120
  /**
115
121
  * Current working directory.
122
+ *
116
123
  * Also the base directory for default `.prettierignore` lookup.
117
124
  */
118
125
  cwd?: string;
@@ -122,37 +129,46 @@ interface IsOxfmtIgnoredOptions {
122
129
  filepath: string;
123
130
  /**
124
131
  * Explicit oxfmt config path.
132
+ *
125
133
  * When provided, nested config lookup is disabled (same as oxfmt CLI -c).
126
134
  */
127
135
  configPath?: string;
128
136
  /**
129
- * Ignore files to use instead of default `.gitignore` hierarchy + cwd `.prettierignore`.
130
- * Can be passed multiple times in CLI style.
137
+ * Ignore files to use instead of the default cwd `.prettierignore`.
138
+ *
139
+ * Explicit ignore paths do not replace `.gitignore` or `.git/info/exclude`
140
+ * handling. They can be passed multiple times in CLI style.
131
141
  */
132
142
  ignorePath?: string | string[];
133
143
  /**
134
144
  * Whether node_modules should be included.
145
+ *
135
146
  * @default false
136
147
  */
137
148
  withNodeModules?: boolean;
138
149
  /**
139
150
  * Disable nested config lookup.
151
+ *
140
152
  * @default false
141
153
  */
142
154
  disableNestedConfig?: boolean;
143
155
  /**
144
156
  * Whether to use in-memory cache.
157
+ *
145
158
  * @default true
146
159
  */
147
160
  useCache?: boolean;
148
161
  /**
149
162
  * Whether to include ignore patterns defined in the config file.
163
+ *
150
164
  * @default true
151
165
  */
152
166
  includeConfigIgnorePatterns?: boolean;
153
167
  /**
154
168
  * Whether to load resolved oxfmt config when evaluating config ignore patterns.
169
+ *
155
170
  * When false, only global ignore is applied and config loading is skipped.
171
+ *
156
172
  * @default true
157
173
  */
158
174
  loadConfigForIgnorePatterns?: boolean;
@@ -166,32 +182,11 @@ interface IsOxfmtIgnoredResult {
166
182
  */
167
183
  ignored: boolean;
168
184
  /**
169
- * Matched ignore source.
185
+ * Matched ignore source when `ignored` is true.
170
186
  */
171
187
  reason?: 'default-dir' | 'lockfile' | 'gitignore' | 'git-info-exclude' | 'prettierignore' | 'ignore-path' | 'config-ignore-patterns';
172
188
  }
173
189
  //#endregion
174
- //#region src/config-file.d.ts
175
- /**
176
- * Resolve the oxfmt config file path.
177
- *
178
- * - If `configPath` is provided, absolute paths are returned as-is;
179
- * relative paths are joined to `cwd`.
180
- * - Otherwise, walk upward from `cwd` to find known filenames.
181
- *
182
- * @param cwd - Starting directory for resolution.
183
- * @param configPath - Optional explicit path.
184
- * @returns Absolute path to config file, or undefined when not found.
185
- *
186
- * @example
187
- * ```ts
188
- * import { resolveOxfmtrcPath } from 'load-oxfmt-config'
189
- *
190
- * const path = await resolveOxfmtrcPath(process.cwd())
191
- * ```
192
- */
193
- declare function resolveOxfmtrcPath(cwd: string, configPath?: string): Promise<string | undefined>;
194
- //#endregion
195
190
  //#region src/core.d.ts
196
191
  /**
197
192
  * Resolve config + editorconfig and return merged config with metadata.
@@ -228,4 +223,52 @@ declare function loadOxfmtConfig(options?: LoadOxfmtConfigOptions): Promise<Load
228
223
  */
229
224
  declare function isOxfmtIgnored(options: IsOxfmtIgnoredOptions): Promise<IsOxfmtIgnoredResult>;
230
225
  //#endregion
231
- export { EditorconfigOption, IsOxfmtIgnoredOptions, IsOxfmtIgnoredResult, LoadOxfmtConfigOptions, LoadOxfmtConfigResult, OxfmtConfigOverride, OxfmtOptions, isOxfmtIgnored, loadOxfmtConfig, resolveOxfmtrcPath };
226
+ //#region src/config.d.ts
227
+ /**
228
+ * Build a cache key for path resolution (cwd + configPath).
229
+ *
230
+ * @param cwd - Current working directory.
231
+ * @param configPath - Optional config path.
232
+ * @returns Cache key for resolve cache.
233
+ */
234
+ declare function getResolveCacheKey(cwd: string, configPath?: string): string;
235
+ /**
236
+ * Build a cache key for config content; prefixes missing entries.
237
+ *
238
+ * @param resolvedPath - Resolved oxfmt config path.
239
+ * @param editorconfigPath - Resolved editorconfig path.
240
+ * @param resolveKey - Resolution cache key.
241
+ * @returns Cache key for config content cache.
242
+ */
243
+ declare function getConfigCacheKey(resolvedPath: string | undefined, editorconfigPath: string | undefined, resolveKey: string): string;
244
+ /**
245
+ * Resolve the oxfmt config file path.
246
+ *
247
+ * - If `configPath` is provided, absolute paths are returned as-is;
248
+ * relative paths are joined to `cwd`.
249
+ * - Otherwise, walk upward from `cwd` to find known filenames.
250
+ *
251
+ * @param cwd - Starting directory for resolution.
252
+ * @param configPath - Optional explicit path.
253
+ * @returns Absolute path to config file, or undefined when not found.
254
+ *
255
+ * @example
256
+ * ```ts
257
+ * import { resolveOxfmtrcPath } from 'load-oxfmt-config'
258
+ *
259
+ * const path = await resolveOxfmtrcPath(process.cwd())
260
+ * ```
261
+ */
262
+ declare function resolveOxfmtrcPath(cwd: string, configPath?: string): Promise<string | undefined>;
263
+ /**
264
+ * Read and parse an oxfmt config file.
265
+ *
266
+ * @param resolvedPath - Absolute path to config file.
267
+ * @param options - Config loading options.
268
+ * @returns Parsed config object.
269
+ */
270
+ declare function readConfigFromFile(resolvedPath: string, options?: {
271
+ useCache?: boolean;
272
+ }): Promise<OxfmtOptions>;
273
+ //#endregion
274
+ export { EditorconfigOption, IsOxfmtIgnoredOptions, IsOxfmtIgnoredResult, LoadOxfmtConfigOptions, LoadOxfmtConfigResult, OxfmtConfigOverride, OxfmtOptions, getConfigCacheKey, getResolveCacheKey, isOxfmtIgnored, loadOxfmtConfig, readConfigFromFile, resolveOxfmtrcPath };
package/dist/index.mjs CHANGED
@@ -1,11 +1,12 @@
1
+ import { createRequire } from "node:module";
1
2
  import { basename, dirname, extname, isAbsolute, join, relative, resolve } from "node:path";
2
3
  import process from "node:process";
3
- import { interopDefault, isBoolean, isNumber, isObject } from "@ntnyq/utils";
4
+ import { hasOwn, interopDefault, isBoolean, isNumber, isObject, isRecord, isString, isUndefined } from "@ntnyq/utils";
4
5
  import { readFile, stat } from "node:fs/promises";
6
+ import { pathToFileURL } from "node:url";
5
7
  import { parse, printParseErrorCode } from "jsonc-parser";
6
8
  import { parseBuffer } from "editorconfig";
7
9
  import ignore from "ignore";
8
- import picomatch from "picomatch";
9
10
  //#region src/constants.ts
10
11
  /**
11
12
  * Supported configuration files for oxfmt.
@@ -34,8 +35,10 @@ const OXFMT_EXPLICIT_CONFIG_EXTENSIONS = [
34
35
  */
35
36
  const DEFAULT_IGNORED_DIRS = [
36
37
  ".git",
37
- ".svn",
38
38
  ".jj",
39
+ ".sl",
40
+ ".svn",
41
+ ".hg",
39
42
  "node_modules"
40
43
  ];
41
44
  /**
@@ -46,10 +49,21 @@ const DEFAULT_IGNORED_DIRS = [
46
49
  */
47
50
  const DEFAULT_IGNORED_LOCKFILES = [
48
51
  "package-lock.json",
49
- "npm-shrinkwrap.json",
50
52
  "pnpm-lock.yaml",
51
53
  "yarn.lock",
54
+ "MODULE.bazel.lock",
52
55
  "bun.lock",
56
+ "deno.lock",
57
+ "composer.lock",
58
+ "Package.resolved",
59
+ "Pipfile.lock",
60
+ "flake.lock",
61
+ "Cargo.lock",
62
+ "Gopkg.lock",
63
+ "pdm.lock",
64
+ "poetry.lock",
65
+ "uv.lock",
66
+ "npm-shrinkwrap.json",
53
67
  "bun.lockb"
54
68
  ];
55
69
  /**
@@ -61,7 +75,180 @@ const EDITORCONFIG_FILE = ".editorconfig";
61
75
  */
62
76
  const EDITORCONFIG_GLOBAL_SECTION_NAMES = ["*"];
63
77
  //#endregion
64
- //#region src/config-file.ts
78
+ //#region src/config.ts
79
+ /**
80
+ * CommonJS require scoped to this ESM module for loading `.cjs` config files.
81
+ */
82
+ const require = createRequire(import.meta.url);
83
+ /**
84
+ * Node error codes that mean CommonJS require should fall back to ESM loading.
85
+ */
86
+ const requireFallbackErrorCodes = /* @__PURE__ */ new Set(["ERR_REQUIRE_ASYNC_MODULE", "ERR_REQUIRE_ESM"]);
87
+ /**
88
+ * Syntax errors that indicate module syntax was parsed through CommonJS.
89
+ */
90
+ const syntaxFallbackMessages = [
91
+ /Cannot use import statement outside a module/u,
92
+ /Unexpected token 'export'/u,
93
+ /Unexpected token 'import'/u
94
+ ];
95
+ /**
96
+ * Check whether an unknown config export is an object accepted by oxfmt.
97
+ *
98
+ * @param value - Runtime value to validate.
99
+ * @returns True when the value can be treated as an oxfmt options object.
100
+ */
101
+ function isConfigObject(value) {
102
+ return isRecord(value);
103
+ }
104
+ /**
105
+ * Read a parsed JSON-like config value as an oxfmt config object.
106
+ *
107
+ * @param config - Runtime config value.
108
+ * @returns Oxfmt config object.
109
+ * @throws When the config value is not an object.
110
+ */
111
+ function readParsedConfigObject(config) {
112
+ if (!isConfigObject(config)) throw new Error("Configuration file must be an object.");
113
+ return config;
114
+ }
115
+ /**
116
+ * Read the default export from a JavaScript or TypeScript config module.
117
+ *
118
+ * @param mod - Imported config module namespace.
119
+ * @returns Oxfmt config object from the module default export.
120
+ * @throws When the module has no default export or the default export is not an object.
121
+ */
122
+ function readConfigDefaultExport(mod) {
123
+ if (!hasOwn(mod, "default")) throw new Error("Configuration file has no default export.");
124
+ const config = mod["default"];
125
+ if (!isConfigObject(config)) throw new Error("Configuration file must have a default export that is an object.");
126
+ return config;
127
+ }
128
+ /**
129
+ * Read a CommonJS module export as an oxfmt config object.
130
+ *
131
+ * @param config - Runtime CommonJS export value.
132
+ * @returns Oxfmt config object from the module export.
133
+ * @throws When the module export is not an object.
134
+ */
135
+ function readConfigModuleExports(config) {
136
+ if (!isConfigObject(config)) throw new Error("Configuration file must export an object.");
137
+ return config;
138
+ }
139
+ /**
140
+ * Import a JavaScript or TypeScript config module through jiti.
141
+ *
142
+ * @param resolvedPath - Absolute config file path to import.
143
+ * @param useCache - Whether jiti should use its filesystem and module caches.
144
+ * @returns Imported module namespace.
145
+ */
146
+ async function importJitiConfigModule(resolvedPath, useCache) {
147
+ return (await interopDefault(import("jiti")))(import.meta.url, useCache ? void 0 : {
148
+ fsCache: false,
149
+ moduleCache: false
150
+ }).import(resolvedPath);
151
+ }
152
+ /**
153
+ * Build a cache-busting import key from entry file metadata.
154
+ *
155
+ * @param resolvedPath - Absolute config file path.
156
+ * @returns Stable key that changes when the entry file mtime or size changes.
157
+ */
158
+ async function getFreshImportCacheKey(resolvedPath) {
159
+ const stats = await stat(resolvedPath, { bigint: true });
160
+ return `${stats.mtimeNs}:${stats.size}`;
161
+ }
162
+ /**
163
+ * Read a Node-style `code` field from an unknown thrown value.
164
+ *
165
+ * @param error - Thrown value to inspect.
166
+ * @returns Error code when present.
167
+ */
168
+ function getErrorCode(error) {
169
+ return isObject(error) && "code" in error && isString(error.code) ? error.code : void 0;
170
+ }
171
+ /**
172
+ * Check whether a loader error should continue the JS config fallback chain.
173
+ *
174
+ * @param error - Thrown value from require or native import.
175
+ * @returns True when the error is from loader compatibility, not config execution.
176
+ */
177
+ function isJavaScriptLoaderFallbackError(error) {
178
+ const code = getErrorCode(error);
179
+ if (code && requireFallbackErrorCodes.has(code)) return true;
180
+ return error instanceof SyntaxError && syntaxFallbackMessages.some((pattern) => pattern.test(error.message));
181
+ }
182
+ /**
183
+ * Import an ESM config module with entry-file cache busting.
184
+ *
185
+ * @param resolvedPath - Absolute config file path to import.
186
+ * @returns Imported module namespace.
187
+ */
188
+ async function importNativeFreshModule(resolvedPath) {
189
+ const url = pathToFileURL(resolvedPath);
190
+ url.searchParams.set("oxfmtConfigCacheBust", await getFreshImportCacheKey(resolvedPath));
191
+ return import(url.href);
192
+ }
193
+ /**
194
+ * Delete a CommonJS module and all cached children reachable from it.
195
+ *
196
+ * @param requirePath - Resolved CommonJS module id.
197
+ * @param seen - Visited module ids used to avoid cycles.
198
+ */
199
+ function deleteRequireCacheTree(requirePath, seen = /* @__PURE__ */ new Set()) {
200
+ if (seen.has(requirePath)) return;
201
+ seen.add(requirePath);
202
+ const cachedModule = require.cache[requirePath];
203
+ if (cachedModule) for (const child of cachedModule.children) deleteRequireCacheTree(child.id, seen);
204
+ Reflect.deleteProperty(require.cache, requirePath);
205
+ }
206
+ /**
207
+ * Require a CommonJS module after removing it from Node's require cache.
208
+ *
209
+ * @param resolvedPath - Absolute config file path to require.
210
+ * @returns Runtime module export value.
211
+ */
212
+ function requireFreshModule(resolvedPath) {
213
+ const requirePath = require.resolve(resolvedPath);
214
+ deleteRequireCacheTree(requirePath);
215
+ return require(requirePath);
216
+ }
217
+ /**
218
+ * Load a CommonJS config file without reusing Node's require cache.
219
+ *
220
+ * @param resolvedPath - Absolute `.cjs` config file path.
221
+ * @returns Oxfmt config object from default or module exports.
222
+ */
223
+ function requireFreshCommonJSConfig(resolvedPath) {
224
+ const configModule = requireFreshModule(resolvedPath);
225
+ if (Object.prototype.toString.call(configModule) === "[object Module]") return readConfigDefaultExport(configModule);
226
+ return readConfigModuleExports(configModule);
227
+ }
228
+ /**
229
+ * Load a JavaScript config file without reusing stale module contents.
230
+ *
231
+ * This supports CommonJS, native ESM, and jiti fallback loading so package type
232
+ * and syntax differences can be handled consistently.
233
+ *
234
+ * @param resolvedPath - Absolute `.js` config file path.
235
+ * @returns Imported module namespace with a default config export.
236
+ */
237
+ async function importFreshJavaScriptConfigModule(resolvedPath) {
238
+ try {
239
+ const configModule = requireFreshModule(resolvedPath);
240
+ if (Object.prototype.toString.call(configModule) === "[object Module]") return importNativeFreshModule(resolvedPath);
241
+ return { default: readConfigModuleExports(configModule) };
242
+ } catch (error) {
243
+ if (!isJavaScriptLoaderFallbackError(error)) throw error;
244
+ try {
245
+ return await importNativeFreshModule(resolvedPath);
246
+ } catch (importError) {
247
+ if (!isJavaScriptLoaderFallbackError(importError)) throw importError;
248
+ return importJitiConfigModule(resolvedPath, false);
249
+ }
250
+ }
251
+ }
65
252
  /**
66
253
  * Build a cache key for path resolution (cwd + configPath).
67
254
  *
@@ -124,13 +311,17 @@ async function resolveOxfmtrcPath(cwd, configPath) {
124
311
  * Read and parse an oxfmt config file.
125
312
  *
126
313
  * @param resolvedPath - Absolute path to config file.
314
+ * @param options - Config loading options.
127
315
  * @returns Parsed config object.
128
316
  */
129
- async function readConfigFromFile(resolvedPath) {
317
+ async function readConfigFromFile(resolvedPath, options = {}) {
130
318
  const extension = extname(resolvedPath);
319
+ const useCache = options.useCache !== false;
131
320
  if (extension === ".ts" || extension === ".mts" || extension === ".cts" || extension === ".js" || extension === ".mjs" || extension === ".cjs") {
132
- const mod = await (await interopDefault(import("jiti")))(import.meta.url).import(resolvedPath);
133
- return mod["default"] ?? mod;
321
+ if (!useCache && extension === ".cjs") return requireFreshCommonJSConfig(resolvedPath);
322
+ if (!useCache && extension === ".mjs") return readConfigDefaultExport(await importNativeFreshModule(resolvedPath));
323
+ if (!useCache && extension === ".js") return readConfigDefaultExport(await importFreshJavaScriptConfigModule(resolvedPath));
324
+ return readConfigDefaultExport(await importJitiConfigModule(resolvedPath, useCache));
134
325
  }
135
326
  const content = await readFile(resolvedPath, "utf8");
136
327
  if (extension === ".jsonc") {
@@ -141,15 +332,15 @@ async function readConfigFromFile(resolvedPath) {
141
332
  });
142
333
  if (parseErrors.length > 0) {
143
334
  const firstError = parseErrors[0];
144
- const errorCode = firstError === void 0 ? "Unknown" : printParseErrorCode(firstError.error);
335
+ const errorCode = isUndefined(firstError) ? "Unknown" : printParseErrorCode(firstError.error);
145
336
  throw new Error(`Invalid JSONC syntax: ${errorCode}`);
146
337
  }
147
- return parsed ?? {};
338
+ return readParsedConfigObject(isUndefined(parsed) && content.trim() === "" ? {} : parsed);
148
339
  }
149
- if (extension === ".json") return JSON.parse(content);
150
- if (!extension) return JSON.parse(content);
340
+ if (extension === ".json") return readParsedConfigObject(JSON.parse(content));
341
+ if (!extension) return readParsedConfigObject(JSON.parse(content));
151
342
  if (!OXFMT_EXPLICIT_CONFIG_EXTENSIONS.includes(extension)) throw new Error(`Unsupported oxfmt config extension "${extension}" at ${resolvedPath}`);
152
- return JSON.parse(content);
343
+ return readParsedConfigObject(JSON.parse(content));
153
344
  }
154
345
  //#endregion
155
346
  //#region src/utils.ts
@@ -386,7 +577,13 @@ async function readEditorconfigFromFile(editorconfigPath, anchorDir) {
386
577
  }
387
578
  //#endregion
388
579
  //#region src/core.ts
580
+ /**
581
+ * Cache resolved config paths keyed by the effective lookup directory and optional config path.
582
+ */
389
583
  const resolveCache = /* @__PURE__ */ new Map();
584
+ /**
585
+ * Cache parsed and merged config objects keyed by resolved config and EditorConfig paths.
586
+ */
390
587
  const configCache = /* @__PURE__ */ new Map();
391
588
  /**
392
589
  * Resolve config + editorconfig and return merged config with metadata.
@@ -419,7 +616,7 @@ async function loadOxfmtConfig(options = {}) {
419
616
  const editorconfigPath = useEditorconfig ? await (useCache ? cachePromise(resolveCache, editorconfigResolveKey, () => resolveEditorconfigPath(editorconfigSearchDir, onlyCwd)) : resolveEditorconfigPath(editorconfigSearchDir, onlyCwd)) : void 0;
420
617
  const anchorDir = dirname(resolvedPath || editorconfigPath || cwd);
421
618
  const loadTask = async () => {
422
- const oxfmtConfig = resolvedPath ? await readConfigFromFile(resolvedPath).catch((error) => {
619
+ const oxfmtConfig = resolvedPath ? await readConfigFromFile(resolvedPath, { useCache }).catch((error) => {
423
620
  throw new Error(`Failed to parse oxfmt configuration file at ${resolvedPath}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
424
621
  }) : {};
425
622
  if (!editorconfigPath) return oxfmtConfig;
@@ -446,8 +643,15 @@ async function loadOxfmtConfig(options = {}) {
446
643
  }
447
644
  //#endregion
448
645
  //#region src/ignore.ts
646
+ /**
647
+ * Cache parsed ignore file matchers by ignore file path.
648
+ */
449
649
  const ignoreMatcherCache = /* @__PURE__ */ new Map();
450
650
  /**
651
+ * Cache compiled matchers for config-level `ignorePatterns`.
652
+ */
653
+ const configIgnoreMatcherCache = /* @__PURE__ */ new Map();
654
+ /**
451
655
  * Check whether a file is under oxfmt's default ignored directories.
452
656
  *
453
657
  * @param filepath - Absolute file path to test.
@@ -515,6 +719,27 @@ async function matchIgnoreFile(filepath, ignoreFilePath, useCache, baseDir) {
515
719
  return matcher.ignores(relativeToIgnore);
516
720
  }
517
721
  /**
722
+ * Match a file path against ordered ignore files while preserving negation state.
723
+ *
724
+ * @param filepath - Absolute file path.
725
+ * @param ignoreFileEntries - Ignore files in increasing precedence order.
726
+ * @param useCache - Whether to use matcher cache.
727
+ * @returns True when the ordered ignore files mark the file as ignored.
728
+ */
729
+ async function matchIgnoreFileChain(filepath, ignoreFileEntries, useCache) {
730
+ let ignored = false;
731
+ for (const entry of ignoreFileEntries) {
732
+ const matcher = await loadIgnoreMatcher(entry.path, useCache);
733
+ if (!matcher) continue;
734
+ const relativeToIgnore = relativeSafe(entry.baseDir ?? dirname(entry.path), filepath);
735
+ if (relativeToIgnore === ".." || relativeToIgnore.startsWith("../")) continue;
736
+ const result = matcher.test(relativeToIgnore);
737
+ if (result.ignored) ignored = true;
738
+ else if (result.unignored) ignored = false;
739
+ }
740
+ return ignored;
741
+ }
742
+ /**
518
743
  * Resolve an ignore file path against cwd when needed.
519
744
  *
520
745
  * @param path - Absolute or relative path.
@@ -543,6 +768,29 @@ async function hasGitEntry(dir) {
543
768
  }
544
769
  }
545
770
  /**
771
+ * Resolve the git info exclude file from a repo root.
772
+ *
773
+ * Worktrees and submodules store `.git` as a file containing a `gitdir:` pointer.
774
+ *
775
+ * @param repoRoot - Git repository working tree root.
776
+ * @returns Absolute path to the git info exclude file, or undefined when unavailable.
777
+ */
778
+ async function resolveGitInfoExcludePath(repoRoot) {
779
+ const gitEntryPath = join(repoRoot, ".git");
780
+ try {
781
+ const stats = await stat(gitEntryPath);
782
+ if (stats.isDirectory()) return join(gitEntryPath, "info", "exclude");
783
+ if (!stats.isFile()) return;
784
+ const gitdir = (await readFile(gitEntryPath, "utf8")).split(/\r?\n/u).find((line) => line.startsWith("gitdir:"))?.slice(7).trim();
785
+ if (!gitdir) return;
786
+ return join(isAbsolute(gitdir) ? gitdir : resolve(repoRoot, gitdir), "info", "exclude");
787
+ } catch (error) {
788
+ const code = error.code;
789
+ if (code === "ENOENT" || code === "ENOTDIR") return;
790
+ throw error;
791
+ }
792
+ }
793
+ /**
546
794
  * Find the nearest git repo root by walking up from a start directory.
547
795
  *
548
796
  * @param fromDir - Directory to start from.
@@ -586,19 +834,19 @@ async function collectGitignorePaths(filepath) {
586
834
  * @param filepath - Absolute file path.
587
835
  * @param configDir - Resolved config directory.
588
836
  * @param patterns - Config ignore patterns.
837
+ * @param useCache - Whether to reuse compiled pattern matchers.
589
838
  * @returns True when patterns mark the file as ignored.
590
839
  */
591
- function matchConfigIgnorePatterns(filepath, configDir, patterns) {
840
+ function matchConfigIgnorePatterns(filepath, configDir, patterns, useCache) {
592
841
  const relativeFile = relativeSafe(configDir, filepath);
593
- let ignored = false;
594
- for (const rawPattern of patterns) {
595
- if (!rawPattern) continue;
596
- const isNegative = rawPattern.startsWith("!");
597
- const pattern = isNegative ? rawPattern.slice(1) : rawPattern;
598
- if (!pattern) continue;
599
- if (picomatch(pattern, { dot: true })(relativeFile)) ignored = !isNegative;
600
- }
601
- return ignored;
842
+ if (relativeFile === ".." || relativeFile.startsWith("../")) return false;
843
+ if (!useCache) return ignore().add(patterns).ignores(relativeFile);
844
+ const cacheKey = `${configDir}::${JSON.stringify(patterns)}`;
845
+ const cachedMatcher = configIgnoreMatcherCache.get(cacheKey);
846
+ if (cachedMatcher) return cachedMatcher.ignores(relativeFile);
847
+ const matcher = ignore().add(patterns);
848
+ configIgnoreMatcherCache.set(cacheKey, matcher);
849
+ return matcher.ignores(relativeFile);
602
850
  }
603
851
  /**
604
852
  * Resolve whether a file should be ignored using oxfmt-like CLI semantics.
@@ -631,28 +879,27 @@ async function isOxfmtIgnored(options) {
631
879
  reason: "lockfile"
632
880
  };
633
881
  const explicitIgnorePaths = (typeof options.ignorePath === "string" ? [options.ignorePath] : options.ignorePath)?.map((path) => resolveIgnoreFilePath(path, cwd));
634
- if (explicitIgnorePaths && explicitIgnorePaths.length > 0) {
635
- for (const ignoreFilePath of explicitIgnorePaths) if (await matchIgnoreFile(filepath, ignoreFilePath, useCache)) return {
636
- ignored: true,
637
- reason: "ignore-path"
638
- };
639
- } else {
640
- const { paths: gitignorePaths, repoRoot } = await collectGitignorePaths(filepath);
641
- for (const ignorePath of gitignorePaths) if (await matchIgnoreFile(filepath, ignorePath, useCache)) return {
882
+ const { paths: gitignorePaths, repoRoot } = await collectGitignorePaths(filepath);
883
+ if (await matchIgnoreFileChain(filepath, [...gitignorePaths].reverse().map((path) => ({ path })), useCache)) return {
884
+ ignored: true,
885
+ reason: "gitignore"
886
+ };
887
+ if (repoRoot) {
888
+ const infoExcludePath = await resolveGitInfoExcludePath(repoRoot);
889
+ if (infoExcludePath && await matchIgnoreFile(filepath, infoExcludePath, useCache, repoRoot)) return {
642
890
  ignored: true,
643
- reason: "gitignore"
891
+ reason: "git-info-exclude"
644
892
  };
645
- if (repoRoot) {
646
- if (await matchIgnoreFile(filepath, join(repoRoot, ".git", "info", "exclude"), useCache, repoRoot)) return {
647
- ignored: true,
648
- reason: "git-info-exclude"
649
- };
650
- }
651
- if (await matchIgnoreFile(filepath, resolve(cwd, ".prettierignore"), useCache)) return {
893
+ }
894
+ if (explicitIgnorePaths && explicitIgnorePaths.length > 0) {
895
+ if (await matchIgnoreFileChain(filepath, explicitIgnorePaths.map((path) => ({ path })), useCache)) return {
652
896
  ignored: true,
653
- reason: "prettierignore"
897
+ reason: "ignore-path"
654
898
  };
655
- }
899
+ } else if (await matchIgnoreFile(filepath, resolve(cwd, ".prettierignore"), useCache)) return {
900
+ ignored: true,
901
+ reason: "prettierignore"
902
+ };
656
903
  if (!loadConfigForIgnorePatterns) return { ignored: false };
657
904
  const configResult = await loadOxfmtConfig({
658
905
  cwd,
@@ -662,11 +909,11 @@ async function isOxfmtIgnored(options) {
662
909
  editorconfig: false,
663
910
  useCache
664
911
  });
665
- if (includeConfigIgnorePatterns && configResult.dirname && configResult.config.ignorePatterns && configResult.config.ignorePatterns.length > 0 && matchConfigIgnorePatterns(filepath, configResult.dirname, configResult.config.ignorePatterns)) return {
912
+ if (includeConfigIgnorePatterns && configResult.dirname && configResult.config.ignorePatterns && configResult.config.ignorePatterns.length > 0 && matchConfigIgnorePatterns(filepath, configResult.dirname, configResult.config.ignorePatterns, useCache)) return {
666
913
  ignored: true,
667
914
  reason: "config-ignore-patterns"
668
915
  };
669
916
  return { ignored: false };
670
917
  }
671
918
  //#endregion
672
- export { isOxfmtIgnored, loadOxfmtConfig, resolveOxfmtrcPath };
919
+ export { getConfigCacheKey, getResolveCacheKey, isOxfmtIgnored, loadOxfmtConfig, readConfigFromFile, resolveOxfmtrcPath };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "load-oxfmt-config",
3
- "version": "0.12.1",
3
+ "version": "0.14.0",
4
4
  "description": "Load and resolve oxfmt configuration files, including explicit JS/TS config paths, and merge supported `.editorconfig` settings for Oxfmt.",
5
5
  "keywords": [
6
6
  "editorconfig",
@@ -42,29 +42,27 @@
42
42
  "access": "public"
43
43
  },
44
44
  "dependencies": {
45
- "@ntnyq/utils": "^0.15.0",
45
+ "@ntnyq/utils": "^0.16.0",
46
46
  "editorconfig": "^3.0.2",
47
47
  "ignore": "^7.0.5",
48
48
  "jiti": "^2.7.0",
49
- "jsonc-parser": "^3.3.1",
50
- "picomatch": "^4.0.4"
49
+ "jsonc-parser": "^3.3.1"
51
50
  },
52
51
  "devDependencies": {
53
52
  "@ntnyq/tsconfig": "^3.1.0",
54
- "@types/node": "^26.0.0",
55
- "@types/picomatch": "^4.0.3",
56
- "@typescript/native-preview": "^7.0.0-dev.20260622.1",
53
+ "@types/node": "^26.1.0",
54
+ "@typescript/native-preview": "^7.0.0-dev.20260706.1",
57
55
  "bumpp": "^11.1.0",
58
56
  "husky": "^9.1.7",
59
57
  "nano-staged": "^1.0.2",
60
58
  "npm-run-all2": "^9.0.2",
61
- "oxfmt": "^0.56.0",
62
- "oxlint": "^1.71.0",
59
+ "oxfmt": "^0.58.0",
60
+ "oxlint": "^1.73.0",
63
61
  "tsdown": "^0.22.3",
64
- "vitest": "^4.1.9"
62
+ "vitest": "^4.1.10"
65
63
  },
66
64
  "peerDependencies": {
67
- "oxfmt": ">=0.56.0"
65
+ "oxfmt": ">=0.58.0"
68
66
  },
69
67
  "nano-staged": {
70
68
  "*.{js,ts,mjs,tsx}": "oxlint --fix",