Skip to content

Commit

Permalink
feat: bump sort-package-json to v2
Browse files Browse the repository at this point in the history
  • Loading branch information
matzkoh committed Jan 16, 2023
1 parent 319fc41 commit 0dfc9f5
Show file tree
Hide file tree
Showing 8 changed files with 369 additions and 141 deletions.
2 changes: 1 addition & 1 deletion cspell.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"version": "0.2",
"dictionaries": [],
"words": ["packagejson"]
"words": ["packagejson", "synckit"]
}
8 changes: 8 additions & 0 deletions lib/esm-proxy/chain.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
function chain(fn, path = []) {
return new Proxy(() => {}, {
get: (_, prop) => chain(fn, [...path, prop]),
apply: (_, __, args) => fn(path, args),
})
}

module.exports = chain
10 changes: 10 additions & 0 deletions lib/esm-proxy/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const { createSyncFn } = require('synckit')
const chain = require('./chain')

const exec = createSyncFn(require.resolve('./worker'))

function esmProxy(id) {
return chain(exec.bind(null, id))
}

module.exports = esmProxy
8 changes: 8 additions & 0 deletions lib/esm-proxy/worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const { runAsWorker } = require('synckit')

runAsWorker(async (id, path, args) => {
const root = await import(id)
const method = path.pop()
const receiver = path.reduce((acc, cur) => acc[cur], root)
return receiver[method](...args)
})
12 changes: 9 additions & 3 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,25 @@
const requireSafe = require('./require')
const { parsers } = requireSafe('prettier/parser-babel') || requireSafe('prettier/parser-babylon')
const sortPackageJson = require('sort-package-json')
const sortPackageJson = require('./sort-package-json')

const { parsers } =
requireSafe('prettier/parser-babel') ||
// istanbul ignore next
requireSafe('prettier/parser-babylon')

const parser = parsers['json-stringify']

/** @type {import('prettier').Plugin['parsers']} */
exports.parsers = {
'json-stringify': {
...parser,
preprocess(text, options) {
// istanbul ignore next
if (parser.preprocess) {
text = parser.preprocess(text, options)
}

return options.filepath && /(^|\\|\/)package\.json$/.test(options.filepath)
? sortPackageJson(text)
? sortPackageJson.default(text)
: text
},
},
Expand Down
4 changes: 4 additions & 0 deletions lib/sort-package-json.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
const esmProxy = require('./esm-proxy')

/** @type {import('sort-package-json')} */
module.exports = esmProxy('sort-package-json')
Loading

0 comments on commit 0dfc9f5

Please sign in to comment.