Commit 698b53b

Mikhail Avdeev <39246971+easymikey@users.noreply.github.com>
2025-04-08 18:18:16
feat(jsr): improve jsr support (#1186)
* chore: fix grep alias * chore: add NodeJS types * feat: add corect types to JSR publish * feat(jsr): add correct publishing to JSR * build(jsr): add support for cli * build(size): update size limit * improve: reduce func of resolving version * test: add some tests * build(size): update size limit
1 parent 785dbc2
scripts/build-jsr.mjs
@@ -55,7 +55,7 @@ fs.writeFileSync(
       exports: {
         '.': './src/index.ts',
         './core': './src/core.ts',
-        // './cli': './src/cli.ts',
+        './cli': './src/cli.ts',
       },
       publish: {
         include: ['src', 'README.md', 'LICENSE'],
src/cli.ts
@@ -34,6 +34,7 @@ import { startRepl } from './repl.ts'
 import { randomId } from './util.ts'
 import { transformMarkdown } from './md.ts'
 import { createRequire, type minimist } from './vendor.ts'
+import process from 'node:process'
 
 const EXT = '.mjs'
 const EXT_RE = /^\.[mc]?[jt]sx?$/
@@ -92,7 +93,7 @@ export const argv: minimist.ParsedArgs = parseArgv(process.argv.slice(2), {
 }, resolveDefaults({} as any, 'ZX_', process.env, new Set(['env', 'install', 'registry'])))
 
 export async function main(): Promise<void> {
-  await import('./globals.js')
+  await import('./globals.ts')
   argv.ext = normalizeExt(argv.ext)
   if (argv.cwd) $.cwd = argv.cwd
   if (argv.env) {
src/core.ts
@@ -66,6 +66,8 @@ import { log } from './log.ts'
 
 export { default as path } from 'node:path'
 export * as os from 'node:os'
+import { Buffer } from 'node:buffer'
+import process from 'node:process'
 export { log, type LogEntry } from './log.ts'
 export { chalk, which, ps } from './vendor-core.ts'
 export { quote, quotePowerShell } from './util.ts'
@@ -236,7 +238,7 @@ export class ProcessPromise extends Promise<ProcessOutput> {
   private _verbose?: boolean
   private _timeout?: number
   private _timeoutSignal?: NodeJS.Signals
-  private _timeoutId?: NodeJS.Timeout
+  private _timeoutId?: ReturnType<typeof setTimeout>
   private _piped = false
   private _pipedFrom?: ProcessPromise
   private _ee = new EventEmitter()
@@ -504,7 +506,7 @@ export class ProcessPromise extends Promise<ProcessOutput> {
     return this._stage
   }
 
-  get [Symbol.toStringTag](): string {
+  override get [Symbol.toStringTag](): string {
     return 'ProcessPromise'
   }
 
@@ -604,7 +606,7 @@ export class ProcessPromise extends Promise<ProcessOutput> {
   }
 
   // Promise API
-  then<R = ProcessOutput, E = ProcessOutput>(
+  override then<R = ProcessOutput, E = ProcessOutput>(
     onfulfilled?:
       | ((value: ProcessOutput) => PromiseLike<R> | R)
       | undefined
@@ -617,7 +619,7 @@ export class ProcessPromise extends Promise<ProcessOutput> {
     return super.then(onfulfilled, onrejected)
   }
 
-  catch<T = ProcessOutput>(
+  override catch<T = ProcessOutput>(
     onrejected?:
       | ((reason: ProcessOutput) => PromiseLike<T> | T)
       | undefined
@@ -658,7 +660,7 @@ export class ProcessPromise extends Promise<ProcessOutput> {
     this._stdin.once(event, cb)
     return this
   }
-  private write(data: any, encoding: BufferEncoding, cb: any) {
+  private write(data: any, encoding: NodeJS.BufferEncoding, cb: any) {
     this._stdin.write(data, encoding, cb)
     return this
   }
@@ -765,7 +767,7 @@ export class ProcessOutput extends Error {
     return this.valueOf()
   }
 
-  toString(): string {
+  override toString(): string {
     return this.stdall
   }
 
@@ -795,7 +797,7 @@ export class ProcessOutput extends Error {
     return [...this]
   }
 
-  valueOf(): string {
+  override valueOf(): string {
     return this.stdall.trim()
   }
 
src/goods.ts
@@ -30,6 +30,8 @@ import {
   nodeFetch,
   minimist,
 } from './vendor.ts'
+import { Buffer } from 'node:buffer'
+import process from 'node:process'
 
 type ArgvOpts = minimist.Opts & { camelCase?: boolean; parseBoolean?: boolean }
 
@@ -38,7 +40,7 @@ export const parseArgv = (
   opts: ArgvOpts = {},
   defs: Record<string, any> = {}
 ): minimist.ParsedArgs =>
-  Object.entries(minimist(args, opts)).reduce<minimist.ParsedArgs>(
+  Object.entries<string>(minimist(args, opts)).reduce<minimist.ParsedArgs>(
     (m, [k, v]) => {
       const kTrans = opts.camelCase ? toCamelCase : identity
       const vTrans = opts.parseBoolean ? parseBool : identity
@@ -240,7 +242,7 @@ export async function spinner<T>(
     try {
       return await callback!()
     } finally {
-      clearInterval(id as NodeJS.Timeout)
+      clearInterval(id as ReturnType<typeof setTimeout>)
       process.stderr.write(' '.repeat((process.stdout.columns || 1) - 1) + '\r')
     }
   })
src/index.ts
@@ -19,10 +19,12 @@ export * from './core.ts'
 export * from './goods.ts'
 export { minimist, dotenv, fs, YAML, glob, glob as globby } from './vendor.ts'
 
-export const VERSION: string = fs.readJsonSync(
-  new URL('../package.json', import.meta.url),
-  { throws: false }
-)?.version
+export const VERSION: string = (() => {
+  const f = (file: string) =>
+    fs.readJsonSync(new URL(file, import.meta.url), { throws: false })
+  return (f('../package.json') || f('../jsr.json'))?.version
+})()
+
 export const version: string = VERSION
 
 export {
src/log.ts
@@ -14,6 +14,8 @@
 
 import { chalk, type RequestInfo, type RequestInit } from './vendor-core.ts'
 import { inspect } from 'node:util'
+import { type Buffer } from 'node:buffer'
+import process from 'node:process'
 
 export type LogEntry = {
   verbose?: boolean
src/md.ts
@@ -12,6 +12,7 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+import { type Buffer } from 'node:buffer'
 import { bufToString } from './util.ts'
 
 export function transformMarkdown(buf: Buffer | string): string {
src/repl.ts
@@ -18,6 +18,7 @@ import repl from 'node:repl'
 import { inspect } from 'node:util'
 import { ProcessOutput, defaults } from './core.ts'
 import { chalk } from './vendor-core.ts'
+import process from 'node:process'
 
 const HISTORY =
   process.env.ZX_REPL_HISTORY ?? path.join(os.homedir(), '.zx_repl_history')
src/util.ts
@@ -15,7 +15,9 @@
 import os from 'node:os'
 import path from 'node:path'
 import fs, { type Mode } from 'node:fs'
+import { type Buffer } from 'node:buffer'
 import { type TSpawnStoreChunks } from './vendor-core.ts'
+import process from 'node:process'
 
 export { isStringLiteral } from './vendor-core.ts'
 
src/vendor-core.ts
@@ -23,7 +23,7 @@ const wrap = <T extends object>(name: string, api: T): T => {
   override(name, api)
   return new Proxy<T>(api, {
     get(_, key) {
-      return store.get(name)[key]
+      return store.get(name)[key] || store.get(name)?.default?.[key]
     },
     apply(_, self, args) {
       return (store.get(name) as TCallable).apply(self, args)
@@ -46,7 +46,9 @@ export {
 } from 'zurk/spawn'
 
 export type RequestInfo = Parameters<typeof globalThis.fetch>[0]
-export type RequestInit = Parameters<typeof globalThis.fetch>[1]
+export type RequestInit = Parameters<typeof globalThis.fetch>[1] & {
+  signal?: AbortSignal
+}
 
 export { type ChalkInstance } from 'chalk'
 export const chalk: typeof _chalk = wrap('chalk', _chalk)
src/vendor-extra.ts
@@ -32,7 +32,11 @@ import { AbortController } from 'node-fetch-native'
 
 export { fetch as nodeFetch } from 'node-fetch-native'
 
-global.AbortController = global.AbortController || AbortController
+// Calculate a global variable for use (Deno/NodeJS) runtime.
+// deno-lint-ignore no-node-globals
+const globalVar = 'Deno' in globalThis ? globalThis : global
+
+globalVar.AbortController = globalVar.AbortController || AbortController
 
 export const createRequire = _createRequire as unknown as (
   filename: string | URL
test/cli.test.js
@@ -373,6 +373,10 @@ console.log(a);
       }
     })
 
+    test('isMain() function is running from the wrong path', () => {
+      assert.equal(isMain('///root/zx/test/cli.test.js'), false)
+    })
+
     test('normalizeExt()', () => {
       assert.equal(normalizeExt('.ts'), '.ts')
       assert.equal(normalizeExt('ts'), '.ts')
test/log.test.ts
@@ -34,6 +34,16 @@ describe('log', () => {
 
     beforeEach(() => (data.length = 0))
 
+    test('empty log', () => {
+      log({
+        kind: 'cmd',
+        cmd: 'echo hi',
+        id: '1',
+        verbose: false,
+      })
+      assert.equal(data.join(''), '')
+    })
+
     test('cmd', () => {
       log({
         kind: 'cmd',
.size-limit.json
@@ -17,35 +17,35 @@
       "README.md",
       "LICENSE"
     ],
-    "limit": "114.35 kB",
+    "limit": "115.10 kB",
     "brotli": false,
     "gzip": false
   },
   {
     "name": "js parts",
     "path": "build/*.{js,cjs}",
-    "limit": "815.7 kB",
+    "limit": "817.10 kB",
     "brotli": false,
     "gzip": false
   },
   {
     "name": "libdefs",
     "path": "build/*.d.ts",
-    "limit": "39.55 kB",
+    "limit": "39.75 kB",
     "brotli": false,
     "gzip": false
   },
   {
     "name": "vendor",
     "path": "build/vendor-*",
-    "limit": "769.0 kB",
+    "limit": "769.20 kB",
     "brotli": false,
     "gzip": false
   },
   {
     "name": "all",
     "path": ["build/*", "man/*", "README.md", "LICENSE"],
-    "limit": "871.6 kB",
+    "limit": "873.20 kB",
     "brotli": false,
     "gzip": false
   }