@kitschpatrol/prettier-config 7.1.0 → 7.2.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/bin/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{cosmiconfig as e}from"cosmiconfig";import{TypeScriptLoader as t}from"cosmiconfig-typescript-loader";import{execa as n}from"execa";import r from"fs-extra";import i from"node:fs";import a from"node:path";import{PassThrough as o,Transform as s}from"node:stream";import{fileURLToPath as c}from"node:url";import{packageUp as l,packageUpSync as u}from"package-up";import d from"picocolors";import f from"yargs";import{hideBin as p}from"yargs/helpers";import m from"@pinojs/json-colorizer";import h from"decircular";import g from"deepmerge";import _ from"json-stringify-pretty-compact";import{findWorkspacesRoot as v}from"find-workspaces";import y from"node:fs/promises";import{stripVTControlCharacters as b}from"node:util";var x=`7.1.0`;function S(e){return e instanceof Error&&`exitCode`in e&&typeof e.exitCode==`number`}function C(e){return m(_(h(e),{indent:2,replacer(e,t){return typeof t==`function`?t.name:t}}),{colors:{BRACKET:`gray`}})}const w=(e,t,n)=>{let r=[...e];for(let[i,a]of t.entries())r[i]===void 0?r[i]=n.cloneUnlessOtherwiseSpecified(a,n):n.isMergeableObject(a)?r[i]=T(e[i],a,n):e.includes(a)||r.push(a);return r};function T(e,t,n={arrayMerge:w}){return g(e,t,n)}function E(){let e=u();if(e===void 0)throw Error(`No package.json found.`);return a.dirname(e)}function D(){let e=v();return e===null?E():a.resolve(e.location)}function O(e){let t=a.join(D(),e);if(r.existsSync(t))return t}function k(e){if(e===`workspace-root`)return D();if(e===`package-dir`)return E();if(typeof e==`string`){if(!r.pathExistsSync(e))throw Error(`Custom cwd directory does not exist: ${e}`);return e}return process.cwd()}async function A(e,t){try{let{default:n}=await import(`prettier`),r=await n.resolveConfig(e),i=await n.format(t,{filepath:e,...r});await y.writeFile(e,i,`utf8`)}catch{console.warn(`Skipped formatting ${e} since Prettier is not installed.`)}}async function j(e){try{await A(e,await y.readFile(e,`utf8`))}catch{}}const M=/\r?\n/;function N(e){return new s({transform(t,n,r){let i=t.toString().split(M).filter(t=>t.trim()!==``&&!e(b(t))).join(`
2
+ import{cosmiconfig as e}from"cosmiconfig";import{TypeScriptLoader as t}from"cosmiconfig-typescript-loader";import{execa as n}from"execa";import r from"fs-extra";import i from"node:fs";import a from"node:path";import{PassThrough as o,Transform as s}from"node:stream";import{fileURLToPath as c}from"node:url";import{packageUp as l,packageUpSync as u}from"package-up";import d from"picocolors";import f from"yargs";import{hideBin as p}from"yargs/helpers";import m from"@pinojs/json-colorizer";import h from"decircular";import g from"deepmerge";import _ from"json-stringify-pretty-compact";import{findWorkspacesRoot as v}from"find-workspaces";import y from"node:fs/promises";import{stripVTControlCharacters as b}from"node:util";var x=`7.2.0`;function S(e){return e instanceof Error&&`exitCode`in e&&typeof e.exitCode==`number`}function C(e){return m(_(h(e),{indent:2,replacer(e,t){return typeof t==`function`?t.name:t}}),{colors:{BRACKET:`gray`}})}const w=(e,t,n)=>{let r=[...e];for(let[i,a]of t.entries())r[i]===void 0?r[i]=n.cloneUnlessOtherwiseSpecified(a,n):n.isMergeableObject(a)?r[i]=T(e[i],a,n):e.includes(a)||r.push(a);return r};function T(e,t,n={arrayMerge:w}){return g(e,t,n)}function E(){let e=u();if(e===void 0)throw Error(`No package.json found.`);return a.dirname(e)}function D(){let e=v();return e===null?E():a.resolve(e.location)}function O(e){let t=a.join(D(),e);if(r.existsSync(t))return t}function k(e){if(e===`workspace-root`)return D();if(e===`package-dir`)return E();if(typeof e==`string`){if(!r.pathExistsSync(e))throw Error(`Custom cwd directory does not exist: ${e}`);return e}return process.cwd()}async function A(e,t){try{let{default:n}=await import(`prettier`),r=await n.resolveConfig(e),i=await n.format(t,{filepath:e,...r});await y.writeFile(e,i,`utf8`)}catch{console.warn(`Skipped formatting ${e} since Prettier is not installed.`)}}async function j(e){try{await A(e,await y.readFile(e,`utf8`))}catch{}}const M=/\r?\n/;function N(e){return new s({transform(t,n,r){let i=t.toString().split(M).filter(t=>t.trim()!==``&&!e(b(t))).join(`
3
3
  `);this.push(i+`
4
4
  `),r()}})}function P(e,t){return new s({transform(n,r,i){let a=n.toString().split(M).filter(e=>e.trim().length>0).map(n=>`${e?t===void 0?e:d[t](e):``} ${n}\n`).join(``);this.push(a),i()}})}async function F(e){let t=[];return new Promise((n,r)=>{e.on(`data`,e=>t.push(e)),e.on(`error`,e=>{r(e)}),e.on(`end`,()=>{n(Buffer.concat(t).toString(`utf8`))})})}function I(e,t){return t===1?e:e+`s`}async function L(e,t,n,r,i){let a=1,o;if(r.logPrefix===void 0)o=e;else{let t=P(r.logPrefix,r.logColor);t.pipe(e),o=t}i&&o.write(d.bold(`Running: "${r.name}() with Positional arguments: ${String(t)} and Option flags: ${String(n)}"`));try{a=await r.execute(o,t,n)}catch(e){console.error(String(e)),a=1}return a}async function R(e,t,r,i,a){let s=1,c;if(i.logPrefix===void 0)c=e;else{let t=P(i.logPrefix,i.logColor);t.pipe(e),c=t}let l=i.subcommands??[],u=[...i.receivePositionalArguments?t:[],...i.positionalArguments??[]],d=[...i.receiveOptionFlags?r:[],...i.optionFlags??[]],f=[...l,...d,...u],p=k(i.cwdOverride);a&&c.write(`Running: "${i.name} ${f.join(` `)}"`);let m=i.prettyJsonOutput?new o:c;try{let e=n(i.name,f,{cwd:p,env:{...process.env.NO_COLOR===void 0?{FORCE_COLOR:`true`}:{}},preferLocal:!0,reject:!1,stdin:`inherit`});if(i.outputFilter){let t=N(i.outputFilter),n=N(i.outputFilter);e.stdout.pipe(t).pipe(m,{end:!1}),e.stderr.pipe(n).pipe(m,{end:!1})}else e.stdout.pipe(m,{end:!1}),e.stderr.pipe(m,{end:!1});if(await e,i.prettyJsonOutput){m.end();let e=await F(m),t=C(JSON.parse(e)).split(`
5
5
  `);for(let e of t)c.write(`${e}\n`)}s=e.exitCode??1}catch(e){console.error(`${i.name} failed with error:`),console.error(e),S(e)&&(s=typeof e.exitCode==`number`?e.exitCode:1)}return s}function z(e){return`execute`in e}const B=/^ksc-/;function V(e){return e.replace(B,``)}function H(e){return e===void 0||e.length===0?[]:e.flatMap(e=>e.split(`,`)).map(e=>V(e.trim()))}function U(e){return e.option(`skip`,{array:!0,describe:`Tool names to skip (with or without "ksc-" prefix).`,type:`string`})}async function W(e,t,n,r,i,a,o){let s=o??[],c=[],l=[];for(let e of r)s.length>0&&s.includes(V(e.name))?l.push(e):c.push(e);if(s.length>0){let t=new Set(l.map(e=>V(e.name))),n=s.filter(e=>!t.has(e));if(n.length>0){let t=r.map(e=>V(e.name)).join(`, `);e.write(`⚠️ ${d.yellow(`Unrecognized --skip ${I(`value`,n.length)}: ${n.join(`, `)}. Available: ${t}`)}\n`)}}let u=[];for(let r of c){let a=await(z(r)?L(e,t,n,r,i):R(e,t,n,r,i));u.push({exitCode:a,name:r.name})}let f=r.length;if(l.length>0){let t=l.map(({name:e})=>e);e.write(`⏭️ ${d.dim(d.bold(`${t.length} / ${f} ${I(`Command`,t.length)} Skipped:`))} ${d.dim(t.join(`, `))}\n`)}if(a){let t=u.filter(({exitCode:e})=>e===0).map(({name:e})=>e),n=u.filter(({exitCode:e})=>e!==0).map(({name:e})=>e);t.length>0&&e.write(`✅ ${d.green(d.bold(`${t.length} / ${f} ${I(`Command`,t.length)} Succeeded:`))} ${d.green(t.join(`, `))}\n`),n.length>0&&e.write(`❌ ${d.red(d.bold(`${n.length} / ${f} ${I(`Command`,n.length)} Failed:`))} ${d.red(n.join(`, `))}\n`)}return u.every(({exitCode:e})=>e===0)?0:1}async function G(e,t,n,o){let s=await l();if(s===void 0)throw Error("The `init` command must be used in a directory with a package.json file");let u=await l({cwd:c(import.meta.url)});if(u===void 0)return e.write(`Error: The script being called was not in a package, weird.
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Config } from "prettier";
2
2
  import { Options } from "prettier-plugin-jsdoc";
3
3
 
4
- //#region src/index.d.ts
4
+ //#region src/config.d.ts
5
5
  type PrettierConfig = Config & Options;
6
6
  declare const sharedPrettierConfig: PrettierConfig;
7
7
  /**
@@ -17,4 +17,38 @@ declare const sharedPrettierConfig: PrettierConfig;
17
17
  */
18
18
  declare function prettierConfig(config?: PrettierConfig): PrettierConfig;
19
19
  //#endregion
20
- export { sharedPrettierConfig as default, prettierConfig };
20
+ //#region src/api.d.ts
21
+ /**
22
+ * File extension or filepath hint for parser inference and config override
23
+ * matching. Accepts a bare extension (e.g. `'md'`), a virtual filename (e.g.
24
+ * `'file.md'`), or a full path. Known extensions supported by the default
25
+ * shared config are offered as autocomplete suggestions.
26
+ */
27
+ type FileType = 'astro' | 'bash' | 'css' | 'fish' | 'html' | 'js' | 'json' | 'jsx' | 'md' | 'mdx' | 'php' | 'rb' | 'sh' | 'svelte' | 'toml' | 'ts' | 'tsx' | 'xml' | 'yml' | 'zsh' | (string & {});
28
+ /**
29
+ * Format a source string using the shared Prettier configuration.
30
+ *
31
+ * @param source - The source code to format.
32
+ * @param fileTypeOrConfig - A file extension (e.g. `'md'`), virtual filepath
33
+ * (e.g. `'file.md'`), or a `PrettierConfig` object for overrides. Defaults to
34
+ * `'ts'` (TypeScript parser).
35
+ * @param config - Optional `PrettierConfig` overrides when a file type is
36
+ * provided as the second argument.
37
+ *
38
+ * @returns The formatted source string.
39
+ */
40
+ declare function fix(source: string, fileTypeOrConfig?: FileType | PrettierConfig, config?: PrettierConfig): Promise<string>;
41
+ /**
42
+ * Format a file in place using the shared Prettier configuration.
43
+ *
44
+ * @param filePath - Path to the file to format.
45
+ * @param config - Optional `PrettierConfig` overrides.
46
+ */
47
+ declare function fixFile(filePath: string, config?: PrettierConfig): Promise<void>;
48
+ /**
49
+ * Clear the cached Prettier module and resolved plugin paths. Subsequent calls
50
+ * to `fix` or `fixFile` will re-import Prettier and re-resolve plugins.
51
+ */
52
+ declare function clearCache(): void;
53
+ //#endregion
54
+ export { type FileType, type PrettierConfig, clearCache, sharedPrettierConfig as default, sharedPrettierConfig, fix, fixFile, prettierConfig };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{deepmerge as e}from"deepmerge-ts";import{homedir as t}from"node:os";import{sortOrder as n}from"sort-package-json";function r(e,t){return[...e.filter(e=>!t.includes(e)),...t]}const i={bracketSpacing:!0,endOfLine:`lf`,jsdocCommentLineStrategy:`keep`,jsdocPreferCodeFences:!0,jsdocPrintWidth:80,jsdocSeparateReturnsFromParam:!0,overrides:[{files:[`*.md`,`*.mdx`,`*.yml`],options:{useTabs:!1}},{files:`*.astro`,options:{parser:`astro`,plugins:[`prettier-plugin-astro`]}},{files:`*.svelte`,options:{parser:`svelte`,plugins:[`prettier-plugin-svelte`]}},{files:`*.rb`,options:{rubyExecutablePath:`${t()}/.rbenv/shims/ruby`}},{files:[`*rc`,`*ignore`,`*.sh`,`*.zsh`,`*.bash`,`*.fish`],options:{parser:`sh`,plugins:[`prettier-plugin-sh`]}},{files:`package.json`,options:{packageSortOrder:r(n,[`cspell`,`knip`,`mdat`,`prettier`,`remarkConfig`,`stylelint`])}}],plugins:[`@prettier/plugin-php`,`@prettier/plugin-ruby`,`@prettier/plugin-xml`,`prettier-plugin-packagejson`,`prettier-plugin-sh`,`prettier-plugin-toml`,`prettier-plugin-jsdoc`],printWidth:100,semi:!1,singleQuote:!0,tabWidth:2,trailingComma:`all`,useTabs:!0};function a(t){return e(i,t)}export{i as default,a as prettierConfig};
1
+ import{deepmerge as e}from"deepmerge-ts";import t from"node:fs/promises";import{fileURLToPath as n}from"node:url";import{homedir as r}from"node:os";import{sortOrder as i}from"sort-package-json";function a(e,t){return[...e.filter(e=>!t.includes(e)),...t]}const o={bracketSpacing:!0,endOfLine:`lf`,jsdocCommentLineStrategy:`keep`,jsdocPreferCodeFences:!0,jsdocPrintWidth:80,jsdocSeparateReturnsFromParam:!0,overrides:[{files:[`*.md`,`*.mdx`,`*.yml`],options:{useTabs:!1}},{files:`*.astro`,options:{parser:`astro`,plugins:[`prettier-plugin-astro`]}},{files:`*.svelte`,options:{parser:`svelte`,plugins:[`prettier-plugin-svelte`]}},{files:`*.rb`,options:{rubyExecutablePath:`${r()}/.rbenv/shims/ruby`}},{files:[`*rc`,`*ignore`,`*.sh`,`*.zsh`,`*.bash`,`*.fish`],options:{parser:`sh`,plugins:[`prettier-plugin-sh`]}},{files:`package.json`,options:{packageSortOrder:a(i,[`cspell`,`knip`,`mdat`,`prettier`,`remarkConfig`,`stylelint`])}}],plugins:[`@prettier/plugin-php`,`@prettier/plugin-ruby`,`@prettier/plugin-xml`,`prettier-plugin-packagejson`,`prettier-plugin-sh`,`prettier-plugin-toml`,`prettier-plugin-jsdoc`],printWidth:100,semi:!1,singleQuote:!0,tabWidth:2,trailingComma:`all`,useTabs:!0};function s(t){return e(o,t)}const c=/[./\\]/;function l(e){return c.test(e)?e:`file.${e}`}let u,d;async function f(){return u??=await import(`prettier`),u}function p(e){if(d??=new Map,!d.has(e))try{d.set(e,n(import.meta.resolve(e)))}catch{d.set(e,e)}return d.get(e)}function m(e){let t={...e};return t.plugins&&=t.plugins.map(e=>typeof e==`string`?p(e):e),t.overrides&&=t.overrides.map(e=>e.options?.plugins?{...e,options:{...e.options,plugins:e.options.plugins.map(e=>typeof e==`string`?p(e):e)}}:e),t}async function h(t,n){let r=await(await f()).resolveConfig(t,{editorconfig:!0})??o;return m(n?e(r,n):r)}async function g(e,t,n){let r=`file.ts`,i=n;typeof t==`string`?r=l(t):t!==void 0&&(i=t);let a=await h(r,i);return(await f()).format(e,{...a,filepath:r})}async function _(e,n){let r=await t.readFile(e,`utf8`),i=await h(e,n),a=await(await f()).format(r,{...i,filepath:e});await t.writeFile(e,a,`utf8`)}function v(){u=void 0,d=void 0}export{v as clearCache,o as default,o as sharedPrettierConfig,g as fix,_ as fixFile,s as prettierConfig};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kitschpatrol/prettier-config",
3
- "version": "7.1.0",
3
+ "version": "7.2.0",
4
4
  "description": "Prettier configuration for @kitschpatrol/shared-config.",
5
5
  "keywords": [
6
6
  "shared-config",
@@ -61,7 +61,7 @@
61
61
  "prettier-plugin-astro": "^0.14.1",
62
62
  "prettier-plugin-jsdoc": "^1.8.0",
63
63
  "prettier-plugin-packagejson": "^3.0.2",
64
- "prettier-plugin-sh": "^0.18.0",
64
+ "prettier-plugin-sh": "^0.18.1",
65
65
  "prettier-plugin-svelte": "^3.5.1",
66
66
  "prettier-plugin-tailwindcss": "^0.7.2",
67
67
  "prettier-plugin-toml": "^2.0.6",
@@ -76,6 +76,7 @@
76
76
  },
77
77
  "scripts": {
78
78
  "build": "tsdown",
79
- "cli": "node ./bin/cli.js"
79
+ "cli": "node ./bin/cli.js",
80
+ "test": "vitest run"
80
81
  }
81
82
  }
package/readme.md CHANGED
@@ -193,9 +193,36 @@ ksc-prettier print-config
193
193
 
194
194
  <!-- /cli-help -->
195
195
 
196
+ ### API
197
+
198
+ The package also exports `fix`, `fixFile` functions for formatting code programmatically, pre-configured with the shared Prettier configuration.
199
+
200
+ ```typescript
201
+ import { clearCache, fix, fixFile } from '@kitschpatrol/prettier-config'
202
+
203
+ // Format a string (defaults to TypeScript parser)
204
+ const formatted = await fix('const x=1')
205
+
206
+ // Format with a virtual filepath for parser inference and override matching
207
+ const markdown = await fix('# Hello\nworld', 'file.md')
208
+
209
+ // Both filepath and config overrides
210
+ const result = await fix('const x = 1', 'file.ts', { printWidth: 80 })
211
+
212
+ // Format a file in place with config overrides
213
+ await fixFile('./src/index.ts', { printWidth: 80 })
214
+
215
+ // Clear cached Prettier module and resolved plugin paths
216
+ clearCache()
217
+ ```
218
+
219
+ Config is resolved in priority order: shared defaults < local project config (via `prettier.resolveConfig`) < per-call overrides.
220
+
221
+ The Prettier module and resolved plugin paths are cached internally for performance across multiple calls. Use `clearCache()` to force re-initialization.
222
+
196
223
  ## Ruby support
197
224
 
198
- Ruby formatting Expects a global Ruby install >=2.7 via `rbenv` at `~/.rbenv/shims/ruby` with the following gems:
225
+ Ruby formatting Expects a global Ruby install >=2.7 with the following gems:
199
226
 
200
227
  - `bundler`
201
228
  - `prettier_print`
@@ -203,6 +230,8 @@ Ruby formatting Expects a global Ruby install >=2.7 via `rbenv` at `~/.rbenv/shi
203
230
  - `syntax_tree-haml`
204
231
  - `syntax_tree-rbs`
205
232
 
233
+ Locally, I provide this via `rbenv` at `~/.rbenv/shims/ruby`, but other install techniques should work.
234
+
206
235
  Note: Do _not_ add `plugins: ['prettier-plugin-ruby']` to the per-file scope, it must be global.
207
236
 
208
237
  ## SQL support