Coder Social home page Coder Social logo

arethetypeswrong / arethetypeswrong.github.io Goto Github PK

View Code? Open in Web Editor NEW
858.0 858.0 25.0 25.34 MB

Tool for analyzing TypeScript types of npm packages

Home Page: https://arethetypeswrong.github.io

License: MIT License

TypeScript 86.14% HTML 1.86% CSS 1.64% JavaScript 10.37%

arethetypeswrong.github.io's People

Contributors

andarist avatar andrewbranch avatar compulim avatar cseas avatar ducin avatar ej-shafran avatar github-actions[bot] avatar johnnyreilly avatar karlhorky avatar not-my-profile avatar phryneas avatar remcohaszing avatar wojtekmaj avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

arethetypeswrong.github.io's Issues

`npm pack` does not work with pre/post scripts

The code relies on execSync returning the filename that was packed. But if there are any pre/post scripts, then this output will also be sucked into the final string.

execSync("npm pack", { cwd: fileOrDirectory, encoding: "utf8", stdio: "pipe" }).trim()

The fix could be using the --pack-destination flag to set a predictable path for the packed tarball, rather than relying on output.

Improving the public API

The @arethetypeswrong/core package currently exports two functions checkTgz and checkPackage, which both take an optional implementation of the following interface:

export interface Host {
  createPackageFS: (packageName: string, packageVersion?: string) => Promise<FS>;
  createPackageFSFromTarball: (tgz: Uint8Array) => Promise<FS>;
}

This API really doesn't make much sense to me ... especially since these two interface methods are completely unrelated and the two exported functions are only very small:

export async function checkTgz(tgz: Uint8Array, host: Host = fetchTarballHost): Promise<CheckResult> {
  const packageFS = await host.createPackageFSFromTarball(tgz);
  return checkPackageWorker(packageFS);
}

export async function checkPackage(
  packageName: string,
  packageVersion?: string,
  host: Host = fetchTarballHost
): Promise<CheckResult> {
  const packageFS = await host.createPackageFS(packageName, packageVersion);
  return checkPackageWorker(packageFS);
}

so there's really no need to customize their behavior with this Host interface ... it's just unnecessarily convoluted.

I think it would make much more sense to:

  1. Export the checkPackageWorker function accepting an FS and rename it to checkPackage and rename the FS interface to Package so that we end up with the signature:
     export async function checkPackage(package: Package): Promise<CheckResult> { ... }
  2. Remove checkTgz and checkPackage and replace them with public packageFromTarball and packageFromNPM functions, both returning Package.

So the public API usage would then look like:

const checkResult = await checkPackage(await packageFromNPM('foobar', '1.0.0'));

(which has the advantage that you can easily provide your own package that fulfills the required interface ... and it's clear how to do that)

This would be of course a breaking change but the core README already says:

⚠️ This package is in major version v0 and the API may change significantly in patch and minor releases.

Option to skip validation for Node10

Hi. Is there an option to entirely skip validation for Node10? It's possible to run it with --ignore-rules no-resolution but unless I'm wrong that also skips that rule for the other categories, correct?

Publish `are-the-types-wrong-core` as a package?

Hiya! I'm trying to set up some CI checks for Redux Toolkit that do the same sort of output as the ATTW website. It seems that the logic isn't actually published as a package yet, so I've had to clone the repo and do a local publish via yalc to get that to do anything useful.

Good news is that the checkTgz function does work and I've got it processing a package tarball I've created, so now it's mostly a question of formatting the results. But, this would be easier to do if the core logic was actually published.

Any chance you could go publish this in the near future?

Why doesn't rollup (and other tooling) insert the node16 compatibility layer during ESM->CJS transpilation?

I encountered a node16 (cjs) resolution mode problem after the transpilation of ESM module to CJS with rollup, and had to resort to inserting the compatibility layer in the code itself:

if (typeof module !== "undefined" && module.exports) {
  module.exports = defaultExport;
  module.exports.default = defaultExport;
}

I am curious as to why some tools don't insert the compatibility layer, since they already set the exports.default and exports.__esModule?
I was thinking about building a rollup plugin to insert it, but would like to know if there are any caveats/downsides.

typing exported JSON files

Thank you so much for this very useful tool. This issue is about asking questions relative to JSON files.

Typings of exported JSON files

I've tried to run it against a package that my team is publishing and I am wondering what's the right approach for typings exported JSON files? For example, the following package exports declaration:

"exports": {
   "./foo.json": "./dist/foo.json"
}

Result in the following errors:

Imports of "package/foo.json" under all modern module resolution settings resolved to JavaScript files, but no types.

And:

Imports of multiple entrypoints resolved to ES modules from a CJS importing module. CJS modules in Node will only be able to access this entrypoint with a dynamic import

Ignoring exported package.json?

On a side note, shall we ignore the entry that exports the package.json when present?

"exports": {
  "./package.json": "./package.json",
}

Happy to do a PR if you think that should be the default.

Looking forward to the TS documentation updates.

"Internal resolution error" issue for long file paths

While working on a project, attw CLI started to fail suddenly with an "Internal resolution error" when pushing a new component. The unique aspect of this new component is its relatively long name.

It's worth noting that I suspect this might not be an issue with attw itself but rather with TypeScript. I'm creating this issue to investigate, just in case my assumption is incorrect.

It appears that the failure is occurring here while trying to resolve imports within a specific source file.

Interestingly, I've noticed that if the file path length of the imported file exceeds approximately 82 characters (as far as I can tell), ts.getResolvedModule fails to resolve the import. This behavior doesn't make any sense, so I suspect there might be something off in my TypeScript configuration or elsewhere.

To assist with troubleshooting, I've created a repository to reproduce the issue:

https://github.com/inakiabt/ts-issue

`node-fetch` is no longer required

As of Node 18, fetch is within the globals:

https://dev.to/cloudx/nodejs-18-fetch-api-test-runner-module-and-more-2ckg

@types/node-fetch or lib: ["dom"] in tsconfig.json, however, might be required due to this issue (it's still experimental):

DefinitelyTyped/DefinitelyTyped#60924

Nevertheless, your amazing package requires Node 18 via one of its dependencies anyway:

[email protected]: The engine "node" is incompatible with this module. Expected version ">= 18". Got "16.20.0"

=> Found "[email protected]"
info Reasons this module exists
   - "@arethetypeswrong#cli" depends on it
   - Hoisted from "@arethetypeswrong#cli#marked"

, so I'd suggest to set

"engines": {
    "node": ">=18"
},

in package.json and remove node-fetch and fetch-ponyfill from the dependencies.

Crashes on `next`

Many versions of next, including 13.4.12, crash with File not found: /node_modules/next/types/misc.d.ts`. This is probably a next bug, but it would be great if we could report it instead of crashing.

No error about lack of the explicit extensions

This reports that everything is alright:
https://arethetypeswrong.github.io/?p=ts-pattern%404.2.4-test.0

but in reality this version of this package isn't quite consumable from ESM:

node_modules/ts-pattern/dist/index.d.ts:1:26 - error TS2834: Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node16' or 'nodenext'. Consider adding an extension to the import path.

1 import * as Pattern from './patterns';
                           ~~~~~~~~~~~~

node_modules/ts-pattern/dist/index.d.ts:2:23 - error TS2834: Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node16' or 'nodenext'. Consider adding an extension to the import path.

2 export { match } from './match';
                        ~~~~~~~~~

node_modules/ts-pattern/dist/index.d.ts:3:28 - error TS2834: Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node16' or 'nodenext'. Consider adding an extension to the import path.

3 export { isMatching } from './is-matching';

feature: detect inferred type cannot be named error

I was thinking about doing something similar.

Basically what's need is to get the package, install the dependencies, and see if the types in the output files can be resolved or not.

This is especially problematic with pnpm with monorepo as the transient packages are located at the top level ./node_modules/.pnpm/....

For example:

# Dependency graph
- lib-a
  - lib-b
    - lib-c
# folder
- packages
  - lib-a
    - node_modules
      - lib-b  # symlink to /node_modules/.pnpm/lib-b/version-y
- node_modules
  - .pnpm
    - lib-b@version-y
    - lib-c@version-x 

If lib-b does not re-exports the type from lib-c, you will get Inferred type cannot be named error.

Verify `export =` vs `export default` for CJS

A common mistake people make is to write or emit module.exports = thing in the CJS output, but export default thing in the type definitions. It would be nice if this tool could handle that and provide suggestions how to fix it.

This involves inspecting the actual source code instead of just file resolutions, so I understand if this is a big ask, or even out of scope of this project.

[FEATURE]: Add support for fetching lib via URL

Problem

Currently we either need to provide the public package name or bundled output of npm.

Would be nice if we can download the npm package from any arbitrary URL.

Usecase:

  • Use bundled library from Codesandbox CI
    eg: https://pkg.csb.dev/razorpay/blade/commit/3d845e9a/@razorpay/blade
  • This will also enable running this script inside a CI in future

Uneven edge of the CLI table

Not a big issue, but I was wondering why it looks like this having so advanced libraries used for the CLI formatting and colorizing.
My best guess is that emojies are UTF-16, while the tool making paddings only accepts UTF-8.
Perhaps there should be some special method that can figure out UTF-16 string length in order to make correct paddings.

image

It's also interesting that the space after green circle is only visible when I copy/paste the text from the console.
I'm using iTerm2.

┌───────────────────┬───────────────────┐
│                   │ "express-zod-api" │
├───────────────────┼───────────────────┤
│ node10            │ 🟢                │
├───────────────────┼───────────────────┤
│ node16 (from CJS) │ 🟢 (CJS)          │
├───────────────────┼───────────────────┤
│ node16 (from ESM) │ 🟢 (ESM)          │
├───────────────────┼───────────────────┤
│ bundler           │ 🟢                │
└───────────────────┴───────────────────┘

Update MissingExportEquals.md for import default = fetch

It seems that in the case where export default fetch and fetch refers to a namespace and something else being merged with that namespace, one has to add something like this to the namespace:

import _default = fetch;
export { _default as default };

whereas today, the recommendation is:

const _default = typeof fetch;
export { _default as default };

It would be great to update MissingExportEquals.md to cover this namespace edge case.

Support semver ranges

I'm trying to debug a problem with chalk@4 (the last version with CJS and still used by most users). However, I can only use [email protected] because we only accept exact semver versions. Is it possible to extend support for semver ranges like chalk@4 or chalk@^4.0.0 to mimic what happens with yarn install?

Can I ignore an entry in exports?

my packages have a legacy/support entrypoint, which isn't exactly public API, but is there for folks who know about.

It's also a CJS module, but with an ambiguous entry in the exports.
I'd like to ignore checking this file / exports, because it ultimately wouldn't be used by 99.999% of users.

Is this possible? possible soon? thanks!!

[cli] Run `npm pack` automatically and delete .tgz afterward

I'd like to use this library to prevent incorrectly publishing packages,

  • do what it does today, but read from a folder
  • assume all files to be published are already built
  • these should give a reasonable representation of what the "published version" will look like once npm pack is ran
    • checks package.json#files
    • checks .npmignore, if it exists, but package.json#files is better

Add LICENSE files

Everything in this project is intended to be MIT, but all the files and some package.json fields are missing.

Incorrectly passes `bundler` even if `exports.*.types` is missing

See https://arethetypeswrong.github.io/?p=css-selector-generator%403.6.4

See https://github.com/fczbkk/css-selector-generator/blob/68902ba94b61ed819eb4847c8cceab1d483d1f1d/package.json#L10-L13

From what I see, moduleResolution:bundler and node16 actually fails if the types are not specified in the exports map, but this tool passes them both.

Screenshot

I submitted a PR to fix it https://togithub.com/fczbkk/css-selector-generator/pull/577/files

Report invalid `module` field in `package.json`

Some packages define the top-level module field in package.json. Although it’s non-standard, bundlers use it. This can lead to differences between usage in the browser and Node.js, but it is not possible to add type definitions for it.

I think it would be useful to report the module field if it does not match the import condition in the package.json exports field nor the main field.

For example:

Suggest removing unnecessary `types` conditions

For packages like this:

{
  "name": "pkg",
  "exports": {
    "types": "./dist/index.d.ts",
    "default": "./dist/index.js"
  }
}

It might be nice to say that the types condition here is unnecessary and suggest removing it.

What to do for missing export = when it's TypeScript's fault (kinda)

ajv is an example of a package that uses TypeScript, but the generated .d.ts by TypeScript suffers from the missing export = issue (extra .default is needed when imported with NodeNext).

As a workaround, I'm opening a PR to their library to explicitly export the Ajv class, but I wasn't able to figure out the settings needed to get TypeScript to generate a better .d.ts. It would be great to update the docs to cover that case.

Clarity on node16 importing CJS from ESM

I've seen with multiple packages that the website shows the types are resolved to CJS and this is marked as a successful check. What determines this interpretation of ESM or CJS and is this something a package author should be concerned about?

Screenshot 2023-02-28 at 2 23 17 PM

What does the (CJS) mean here exactly?

And shouldn't it be a point of concern that node16 from ESM is resolving to the CJS type definition for a package that provides ESM too?

I've tried the following packages:

  • @use-gesture/core: This has a dual package build but node16-esm resolves to CJS instead of ESM.
  • @razorpay/blade: This only has an ESM build but node16-esm shows the file resolved is CJS.
  • @adobe/react-spectrum: Dual build. This shows node16-esm "Masquerading as CJS". The explanation makes sense, that types of ESM imports are resolving to CJS. But how is this situation different from the above two packages which pass the check?

Incorrect fallback bug detection

For a package like this:

// package.json
{
  "name": "some-pkg",
  "version": "0.0.0",
  "exports": {
    ".": {
      "import": {},
      "require": {},
      "default": "./index.js"
    }
  }
}
// index.js
console.log('a')
// index.d.ts
export {};

Importing it works in Node (and TypeScript) but arethetypeswrong reports that it's relying on microsoft/TypeScript#50762 when it's not since TypeScript is doing the correct thing in this case and working like Node.

(of course it makes no sense to do what's in the example, it's just to illustrate the problem)

Crashes on DT packages

  • When the implementation package is missing from the registry, the error message is bad (cannot convert null or undefined to object)
  • These threw Cannot read properties of undefined (reading 'filename'):
    • is
    • openurl
    • youtube
  • There was one instance of #89
  • These threw fetch error (probably transient network issue):
    • emartech__cls-adapter
    • ember-cli-fastboot
    • ember-mocha
    • ember-changeset-validations
    • switchery
    • swiz
    • sx127x-driver
    • sybase-promised
    • sylvester
    • sylvester-es6
    • symlink-or-copy
    • symbol-tree
    • symphony-api-client-node
    • sync-fetch
    • synaptic

All errors:

Expand
3box
acc-wizard
add2home
adeira__test-utils
akumina-core
akumina-core/v4
ali-oss
allure-js-commons
amazon-cognito-auth-js
amcharts
amplifier
amplify
amplify-deferred
angular
angular-agility
angular-animate
angular-aria
angular-bootstrap-calendar
angular-cookies
angular-dialog-service
angular-httpi
angular-idle
angular-material
angular-meteor
angular-notifications
angular-notify
angular-odata-resources
angular-q-spread
angular-resource
angular-route
angular-sanitize
angular-scenario
angular-ui-notification
angular-ui-router
angular-ui-tree
angular.throttle
angularfire
angularlocalstorage
ansicolors
aos
apigee-access
app-root-dir
appframework
applepayjs
appletvjs
aqb
arbiter
arcgis-to-geojson-utils
argv
artillery
assertsharp
async-cache
async-polling
async-retry
atlaskit__layer
atmosphere.js
atpl
audio-context
auth0.widget
aws-lambda
axe-webdriverjs
azdata
azure-mobile-services-client
azure-sb
babel-types
babylon-walk
backbone.localstorage
backgrid
better-curry
bgiframe
bigint
bignum
bit-array
bitcoin-computer__lib
bitcoin-computer-bitcore
blissfuljs
bluebird-global
boolify-string
boom
boom/v3
boom/v4
bootstrap-colorpicker
bootstrap-datepicker
bootstrap-filestyle
bootstrap-maxlength
bootstrap-switch
bootstrap-touchspin
bootstrap-treeview
bootstrap.paginator
bootstrap.timepicker
bootstrap.v3.datetimepicker/v3
box2d
breeze
bunyan-blackhole
calq
cannon
canvasjs
carbon__layout
carbon__motion
carbon__themes
carbon__type
catbox
catbox/v7
chai-datetime
chartjs-plugin-doughnutlabel-rebourne
chessboardjs
chocolatechipjs
chrome-apps
chui
closure-compiler
cls-hooked
code
coinbase
colab
color/v0
com.wikitude.phonegap.wikitudeplugin
commangular
compose-function
connect-flash
consolidate
content-type
contextjs
cordova-ionic
cordova-plugin-background-mode
cordova-plugin-email-composer
cordova-plugin-ibeacon
cordova-plugin-mapsforge
cordova-plugin-ms-adal
core-js
countdown
coverup
cradle
createjs-lib
crossfilter
crossroads
crumb
cryptiles
cryptojs
css
css-font-loading-module
css-generator
css-modules
csurf
cybozulabs-md5
d3-box
d3-tip
d3.slider
data-driven
db-migrate-base
db-migrate-pg
debug
decorum
deep-freeze
deku
deoxxa-content-type
deployjava
desmos
devexpress-web
devexpress-web/v161
devexpress-web/v162
devexpress-web/v171
devexpress-web/v172
devexpress-web/v181
devexpress-web/v182
devexpress-web/v191
devexpress-web/v192
devexpress-web/v201
df-visible
dhtmlxgantt
dhtmlxscheduler
doccookies
dock-spawn
documentdb
documentdb-server
documentdb-session
domurl
double-ended-queue
dropboxjs
dts-bundle
duosecurity__duo_web
durandal/v1
dvtng-jss
dw-bxslider-4
dymo-label-framework
dynatable
dynatrace
easy-api-request
easy-jsend
easy-xapi
easy-xapi-utils
easydate
ebongarde-root
egg.js
ejs-locals
elasticsearch
email-templates
emartech__cls-adapter
ember
ember-changeset-validations
ember-cli-fastboot
ember-mocha
ember-test-helpers
ember-test-helpers/v0
ember-testing-helpers
ember/v1
ember/v1
ember/v2
ember/v2
ember/v3
ember/v3
emissary
emscripten
engine-check
epub
eq.js
es6-collections
es6-weak-map
esbuild-plugin-import-map
espruino
eth-sig-util
event-to-promise
express-pino-logger
express-serve-static-core
express-simple-locale
express-wechat-access
extjs
extract-text-webpack-plugin
facebook-js-sdk
facebook-pixel
factory-girl-objection-adapter
farbtastic
fast-levenshtein
favico.js
featherlight
ffi
ffmpeg
ffmpeg__libav-core
ffmpeg-static
ffmpeg.js
fibjs
figma
filesystem
filewriter
finch
flight
flipsnap
flot
flowjs
fm-websync
fontoxml
formidable/v1
foundation
friendly-errors-webpack-plugin
ftdomdelegate
gae.channel.api
gamequery
gandi-livedns
gapi.analytics
gapi.calendar
gapi.drive
gapi.pagespeedonline
gapi.people
gapi.plus
gapi.translate
gapi.urlshortener
gapi.youtube
gapi.youtubeanalytics
gaugejs
generic-functions
gensync
gently
geometry-dom
git
gldatepicker
glidejs
glue
glue/v4
go
google__maps
google-ads-scripts
google-closure-compiler
google-drive-realtime-api
google-earth
google-libphonenumber
google-one-tap
google.analytics
google.feeds
google.geolocation
google.visualization
googlemaps.infobubble
gorilla-engine
graphql-resolve-batch
greasemonkey
greasemonkey/v3
grecaptcha
grecaptcha/v0
guid
gulp-angular-templatecache
gulp-changed
gulp-cheerio
gulp-coffeeify
gulp-dtsm
gulp-espower
gulp-help-doc
gulp-jasmine-browser
gulp-load-plugins
gulp-minify-css
gulp-mocha
gulp-ng-annotate
gulp-remember
gulp-sourcemaps
gulp-task-listing
gulp-util
h2o2
hapi
hapi__catbox
hapi__catbox-memory
hapi__joi
hapi__shot
hapi-auth-basic
hapi-auth-cookie
hapi/v12
hapi/v15
hapi/v16
hapi/v17
hapi/v8
hard-source-webpack-plugin
hasher
hashset
hashtable
hasura
headroom
hellosign-sdk
heroku-logger
hexo-bunyan
highlightjs
hmscore__react-native-hms-push
hoek
hookrouter
html-pdf
html-webpack-plugin
htmltojsx
hubspot-pace
hyperscript
hypertext-application-language
i18next-node-fs-backend
ibm-mobilefirst
iltorb
imagemagick
imagemapster
imgur-rest-api
inert
inert/v4
inherits
iniparser
intercomjs
ion-rangeslider/v1
ipaiva
iron
is
iscroll
iscroll/v4
isomorphic-fetch
istanbul
istanbul-middleware
ix.js
jade
jake
jasmine-jquery
jasmine/v1
java-applet
javascript-astar
javascript-bignum
jdataview
jee-jsf
jfp
jpm
jqgrid
jquery-alertable
jquery-backstretch
jquery-cropbox
jquery-deparam
jquery-fullscreen
jquery-galleria
jquery-handsontable
jquery-jcrop
jquery-timeentry
jquery-truncate-html
jquery-urlparam
jquery.address
jquery.are-you-sure
jquery.autosize
jquery.base64
jquery.bbq
jquery.blockui
jquery.bootstrap.wizard
jquery.cleditor
jquery.clientsidelogging
jquery.color
jquery.colorbox
jquery.colorpicker
jquery.contextmenu
jquery.customselect
jquery.cycle
jquery.dropotron
jquery.dynatree
jquery.elang
jquery.fancytree
jquery.fileupload
jquery.filtertable
jquery.finger
jquery.flagstrap
jquery.form
jquery.fullscreen
jquery.gridster
jquery.highlight-bartaz
jquery.jnotify
jquery.joyride
jquery.jsignature
jquery.leanmodal
jquery.livestampjs
jquery.menuaim
jquery.mmenu
jquery.notifybar
jquery.noty
jquery.pjax
jquery.placeholder
jquery.pnotify
jquery.postmessage
jquery.prettyphoto
jquery.qrcode
jquery.rowgrid
jquery.simplemodal
jquery.simplepagination
jquery.simulate
jquery.sortelements
jquery.superlink
jquery.tagsmanager
jquery.tile
jquery.timeago
jquery.timepicker
jquery.timer
jquery.tinycarousel
jquery.tinyscrollbar
jquery.tipsy
jquery.total-storage
jquery.ui.datetimepicker
jquery.ui.layout
jquery.uniform
jquery.watermark
jquery.window
jquery/v1
jquery/v2
jquerymobile
jqueryui
js-clipper
js-schema
js-url
js.spec
jsbn
jsdeferred
jsfl
jsgraph
json-editor
json-merge-patch
json-patch
json-pointer
json-schema
json2csv
jsoneditoronline
jsonstream
jstorage
jsum
justifiedgallery
jwplayer
jxon
k6
kahoot.js-updated
kap-plugin
kendo-ui
kik-browser
kineticjs
knockback
knockout-amd-helpers
knockout-postbox
knockout-secure-binding
knockout.deferred.updates
knockout.editables
knockout.es5
knockout.kogrid
knockout.mapper
knockout.mapping
knockout.projections
knockout.punches
knockout.rx
knockout.validation
knockout.viewmodel
knockstrap
koa-csrf
koa-multer
koa-proxy
koa-router
koji-tools
kolite
konami.js
kos-core
kube-probe
lab
later
layui-src
lazypipe
leadfoot
leaflet-curve
leaflet-editable/v0
leaflet-gpx
leaflet-label
leaflet.awesome-markers/v0
leaflet.pm
leapmotionts
ledgerhq__hw-transport-u2f
lestate
level-sublevel
lightpick
line-reader
lls
lodash.isarray
lodash.now
logg
loopback-boot
lowlight
macaca-circular-json
magic-number
maildev
mailgun-js
mandrill-api
mapbox
mapbox__s3urls
mapsjs
markdown-it-lazy-headers
markitup
maskedinput
material-ui
mathjax
mcrypt
mcustomscrollbar
mdast
mdast/v3
mem-cache
merge-stream
messenger
meteor-accounts-phone
meteor-jboulhous-dev
meteor-persistent-session
meteor-prime8consulting-oauth2
meteor-publish-composite
meteor-roles
meteor-sjobs
method-override
microservice-utilities
microsoft-ajax
microsoft-live-connect
microsoft-sdk-soap
milliseconds
mimos
mina
minapp-env
mixpanel
mixto
mochaccino
mojang-gametest
mojang-minecraft
mojang-minecraft-server-admin
mojang-minecraft-ui
mojang-net
moment-business
moment-holiday
moment-precise-range-plugin
moment-shortformat
moment-strftime2
mongoose-promise
mongoose-sequence
msgpack
mu2
multer
multiparty
mumath
musickit-js
natural-sort
naver-whale
nedb-logger
neo4j
nes
netlify-auth-providers
ng-command
ng-facebook
ng-flow
ng-grid
ng-i18next
ngbootbox
ngprogress-lite
node_redis
node-fibers
node-mysql-wrapper
node-sass-middleware
node-uuid
node-xmpp-client
node-xmpp-core
nodegit
nodemailer/v3
nodeunit
noisejs
nomnom
noteflight-client
notify
notifyjs-browser
npmcli__ci-detect
nunjucks-date
nw.gui
nw.js
oauth.js
oblo-util
office-js
office-js-preview
oidc-token-manager
onflow__flow-js-testing
openjscad
openlayers
openlayers/v2
openlayers/v3
openssi-websdk
openui5
openurl
optimist
oracledb/v3
paralleljs
parcel-bundler
parcel-env
parse-torrent-file
passport
passport-github2
passport-saml
passport-strategy
passport-vkontakte
passport.socketio
pathfinding
paypal-cordova-plugin
payu-emea-sdk
pebblekitjs
phantom
phonegap
phonegap-facebook-plugin
phonegap-nfc
phonegap-plugin-barcodescanner
photoshop
pi-spi
picturefill
pino-multi-stream
pinterest-sdk
piwik-tracker
places
playerframework
playmusic
plupload
pngjs2
podium
polyline
polymer
popcorn
post-message-stream
postlight__mercury-parser
pouchdb-http
preact-i18n
precise
preloadjs
prismic-dom
proclaim
progressjs
project-name-generator
projections
promise-pg
promise-pool
promise-sftp
pump
purifycss-webpack
purl
q-retry
quill
qunit/v1
radius
random-string
rangy
raspi-pwm
raty
raven
raygun4js
rbac-a
rdf-data-model
rdfjs__serializer-jsonld-ext
react-better-password
react-cache
react-color
react-date-range/v0
react-document-meta
react-fa
react-facebook-login-component
react-geosuggest
react-infinite
react-input-mask
react-instantsearch-dom
react-instantsearch-native
react-jsonschema-form
react-key-handler
react-leaflet-markercluster
react-leaflet-markercluster/v2
react-linkify
react-native-bluetooth-serial
react-native-dotenv
react-native-google-signin
react-native-huawei-protected-apps
react-native-material-ui
react-native-modern-datepicker
react-native-orientation
react-native-toast-native
react-native/v0.63
react-native/v0.64
react-native/v0.65
react-native/v0.66
react-native/v0.67
react-native/v0.68
react-onsenui
react-pie-menu
react-pointable
react-router-navigation
react-router-navigation-core
react-router-redux
react-s-alert
react-scrollspy
react-sortable-tree
react-sortable-tree-theme-file-explorer
react-swf
react-tap-event-plugin
react-touch
react-user-tour
react-virtual-keyboard
read-package-tree
readmore-js
recharts-scale
redux-action-utils
redux-form/v7
redux-localstorage
remotedev-serialize
request
request-promise
request-promise-native
restify-plugins
rickshaw
riderize__passport-strava-oauth2
riot-api-nodejs
riot-games-api
riotjs
rison
rn-fetch-blob
rollup-plugin-buble
rollup-plugin-json
rollup-plugin-svelte-svg
rollup-plugin-url
rosie
route-parser
routie
royalslider
run-sequence
rx-jquery
rx-node
s3-uploader
safari-extension
safari-extension-content
sammy
sane
sanitize-s3-objectkey
sat
satnav
screeps-arena
scriptjs
scroller
scrollreveal
scrolltofixed
segment-analytics
sencha_touch
sequelize
sequelize/v3
sequencify
servicenow
set-tz
sharepoint
short-css-vars
shortid
shot
shot/v3
sigmajs
signalfx-collect
signalr/v1
simple-cw-node
simple-oauth2/v1
simple-oauth2/v2
simple-react-lightbox
simple-url-cache
simple-xml
sinon
sipml
six-runtime
ski
sleep
smart-fox-server
snekfetch
snowpack-env
sntp
socket.io.users
soundjs
space-pen
spectrum
sphere-engine-browser
sphere-engine-browser/v1
sprintf
standard-version
statsd-client
steam
storage-helper
stream-meter
stream-series
stream-to-array/v0
string-similarity
string-similarity/v1
stripe-v2
stripe-v3
strophe
styled-components-react-native
succinct
suitescript
superagent
supertest-as-promised
svg-injector
svg-maps__common
svgjs.draggable
svgjs.resize
sw-precache
swagger-express-middleware
swagger-schema-official
swig
swipe
swipeview
switchery
swiz
sx127x-driver
sybase-promised
sylvester
sylvester-es6
symbol-tree
symlink-or-copy
symphony-api-client-node
synaptic
sync-fetch
tableau
tea-merge
teechart
tether-shepherd
text-encoding
tile-reduce
timelinejs
timezone-js
tinajs__tina-redux
to-markdown
to-title-case-gouch
tooltipster
topo
topojson
torrent-stream
trayballoon
trim
twitch-browser
twitter-for-web
tz-format
uglify-es
umbraco
underscore-ko
underscore.string
unity-webapi
unzalgo
uploadcare
urix
url-join/v0
url-regex-safe
url-search-params
urlparser
urlrouter
usage
use-sync-external-store
user-event
user-idle-observer
utils-merge
uuid-browser
uuid/v2
uuid/v3
uws
valdr-message
vanilla-modal
vast-client
vast-client/v2
venn
vertx3-eventbus-client
viewporter
vimeo
vinyl-paths
vis
vision
vision/v4
viz.js
vmap
vortex-web-client
vscode
vscode-windows-registry
vue-datetime
w3c-hr-time
waitme
wallabyjs
wampy
weapp-api
webassembly-web-api
webcl
webcrypto
webgl-ext
webgl2
webpack-env
webrtc
websql
webvr-api
wepy-redux
why-did-you-update
wiiu
windows-mutex
winjs/v1
winjs/v2
winrt
winrt-uwp
winston-dynamodb
wonder.js
wordpress__custom-templated-path-webpack-plugin
wordpress__library-export-default-webpack-plugin
workerb-api
wreck
wreck/v7
wrench
xmldom
xmltojson
xmpp__jid
xrm
xrm/v6
xrm/v7
xrm/v8
xsockets
xss-filters
yandex-money-sdk
yar
ydn-db
youtube
youtube-dl
zeit__next-source-maps
zeit__next-typescript
zengin-code
zip.js
zmq

Getting a `Cannot find package 'readline'` error

Good morning! 👋

When I tried running the latest version, I'm seeing this Cannot find package 'readline' error.

This seems to be an issue on 0.4 and up:

$ npx -y @arethetypeswrong/cli@latest
node:internal/errors:478
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'readline' imported from /Users/nvie/.npm/_npx/79a7df4224f5fbd6/node_modules/@arethetypeswrong/cli/dist/index.js
    at new NodeError (node:internal/errors:387:5)
    at packageResolve (node:internal/modules/esm/resolve:852:9)
    at moduleResolve (node:internal/modules/esm/resolve:901:20)
    at defaultResolve (node:internal/modules/esm/resolve:1115:11)
    at nextResolve (node:internal/modules/esm/loader:163:28)
    at ESMLoader.resolve (node:internal/modules/esm/loader:841:30)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:424:18)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:76:40)
    at link (node:internal/modules/esm/module_job:75:36) {
  code: 'ERR_MODULE_NOT_FOUND'
}

Version 0.3 still works fine 👍

$ npx -y @arethetypeswrong/[email protected]
error: missing required argument 'file-name'

Here is some extra info on my environment:

$ node --version
v16.20.1
$ npx --version
8.19.4

Is running this on node 16 no longer supported? I have a couple projects that I haven't upgraded to Node 18 yet.

`FalseCJS` problem - severity and suggested fixes?

(I realize this is really more of a TS question than it is an attw question, but given our recent discussions I figured it was worth filing here. Feel free to close this once you see it.)

I'm working on redoing the redux-thunk build setup atm, and also trying out https://github.com/egoist/tsup as a potential build tool.

My current package setup looks like this:

  "main": "dist/cjs/index.cjs",
  "module": "dist/index.mjs",
  "types": "dist/index.d.ts",
  "exports": {
    "./package.json": "./package.json",
    ".": {
      "types": "./dist/index.d.ts",
      "import": "./dist/index.mjs",
      "default": "./dist/cjs/index.cjs"
    },
    "./extend-redux": {
      "types": "./extend-redux.d.ts"
    }
  },

Using the CLI wrapper I've set up for attw, I get this output:

image

I'm getting that FalseCJS warning, and I'm guessing it's because I have dist/index.mjs but dist/index.d.ts.

A few questions based on that:

  • How critical is that mismatch in general? I know you've mentioned that "CJS and ESM output files can/should have different types". How much of a concern is that actually in practice? How much effort should I spend on trying to resolve this attw warning?
  • tsup doesn't currently have a way to generate .d.mts output , per egoist/tsup#760 . Is it reasonable to copy over index.d.ts -> index.d.mts in this case?
  • redux-thunk only has the one output index.d.ts file. For RTK, we have many source files, and thus many .d.ts files:
    • Does only the index.d.mts file need to exist with that extension (ie, there could be index.d.mts and otherFile.d.ts and that would work)? Or does every output declaration file need to have the .d.mts extension for TS to load those properly in the ESM case?
  • We've briefly discussed trying to bundle up TS declarations. What is the right tool for that currently?

Question around default exports in a dual ESM/CJS package

Sorry if this isn't the right place to raise this, but I'm having some troubles handling default exports in a dual CJS/ESM package.
I'm using tsup in a real project and am seeing this error:

Build tools:
- @arethetypeswrong/cli@^0.12.2
- typescript@^5.2.2

🤨 CommonJS module simulates a default export with exports.default and exports.__esModule, but does not also set module.exports for compatibility with Node. Node, and some bundlers under certain conditions, do not respect the __esModule marker, so accessing the intended default export will require a .default property access on the default import. https://github.com/arethetypeswrong/arethetypeswrong.github.io/blob/main/docs/problems/CJSOnlyExportsDefault.md


┌───────────────────┬───────────────────────┬───────────────────────────────┬──────────────────────────┐
│                   │ "package-a"           │ "package-a/second-entrypoint" │ "package-a/package.json" │
├───────────────────┼───────────────────────┼───────────────────────────────┼──────────────────────────┤
│ node10            │ 🤨 CJS default export │ 🟢                            │ 🟢 (JSON)                │
├───────────────────┼───────────────────────┼───────────────────────────────┼──────────────────────────┤
│ node16 (from CJS) │ 🤨 CJS default export │ 🤨 CJS default export         │ 🟢 (JSON)                │
├───────────────────┼───────────────────────┼───────────────────────────────┼──────────────────────────┤
│ node16 (from ESM) │ 🟢 (ESM)              │ 🟢 (ESM)                      │ 🟢 (JSON)                │
├───────────────────┼───────────────────────┼───────────────────────────────┼──────────────────────────┤
│ bundler           │ 🟢                    │ 🟢                            │ 🟢 (JSON)                │
└───────────────────┴───────────────────────┴───────────────────────────────┴──────────────────────────┘
 ELIFECYCLE  Command failed with exit code 1.

I've put together a reproduction here: https://github.com/lukebennett88/dual-package-example.
My question is — how do I change my code to support this. Am I using tsup incorrectly? Do I need to change my source code? Is everything configured correctly, do I need a custom esbuild plugin?

Hopefully this isn't too specific to tsup I'm happy to ask there instead if this is the wrong place 😅

Doesn’t check that imports inside the package work

When I check [email protected] it appears to show that everything is okay, and I can use that package with node module resolution. But when I try to use that package with nodenext module resolution, I get errors like Module '"antlr4"' has no exported member 'CommonTokenStream'.

CommonTokenStream shows up in the node16-esm resolutions on arethetypeswrong so it seems like it may not be matching the behavior of tsc 5.0.3. That or maybe there's a bug in tsc? The docs don't make it very clear what I should expect tsc to do in this case.

I haven't figured out what I would need to change in a PR to antlr4 but I've been asking around. In addition to needing better package authoring guidance from the docs, it would be good if arethetypeswrong catches problems like this.

Thanks so much for this project!

Hi @andrewbranch,

Just wanted to open this issue to say thanks for this! As a user, it's really hard to know if types are correct in all module constellations, and this is a big help.

Thanks again for your continued effort here and also in the ecosystem - I'll close this issue now.

How to check globs in exports

I wrote a wrapper around the invocation of attw, some may find it helpful:

async function lintPublishedTypes({ cwd }) {
  let manifest = await packageJson.read(cwd);
  let name = manifest.name;

  let entrypoints = [];

  for (let [entryGlob, mapping] of Object.entries(manifest['exports'])) {
    if (!entryGlob.includes('*')) {
      let entry = path.join(name, entryGlob);

      entrypoints.push(entry);
      continue;
    }

    const files = globbySync(mapping.types.replace('*', '**/*'), {cwd});

    // Map the files to full module paths
    const mappedFiles = files.map(file => {
      // Now that we found files, we need to map them _back_ to entrypoints.
      // Based on the entryGlob, we need to remove the path leading up until the '*',
      let toRemove = mapping.types.split('*')[0];
      let moduleName = file.split(toRemove)[1];

      // we need to chop off the extension IFF the mapping.types includes it
      if (mapping.types.endsWith('.d.ts')) {
        moduleName = moduleName.replace('.d.ts', '');
      }

      return moduleName;
    });

    entrypoints.push(...mappedFiles);
  }

  entrypoints = entrypoints
    // Remove stuff we are going to exclude
    .filter(entry => !entry.endsWith('*'))
    .filter(entry => !entry.endsWith('addon-main'))
    // Remove index files
    .filter(entry => !entry.endsWith('index'));

  let args = [
    'attw', '--pack',
    // This does not provide types
    '--exclude-entrypoints', 'addon-main',
    // We turn this one off because we don't care about CJS consumers
    '--ignore-rules', 'cjs-resolves-to-esm',
    // Wildcard is not official supported
    '--ignore-rules', 'wildcard',
    // publint will handle resolving
    '--ignore-rules', 'internal-resolution-error',
    '--include-entrypoints', ...entrypoints
  ];


  console.info(chalk.blueBright('Running:\n', args.join(' ')));

  await execa('pnpm', args, {
    cwd,
    stdio: 'inherit',
  });
}

This takes my exports:

  "exports": {
    ".": {
      "types": "./dist-types/index.d.ts",
      "default": "./dist/index.js"
    },
    "./*": {
      "types": "./dist-types/*.d.ts",
      "default": "./dist/*.js"
    },
    "./test-support": {
      "types": "./dist-types/test-support/index.d.ts",
      "default": "./dist/test-support/index.js"
    },
    "./addon-main": "./addon-main.cjs"
  },

and invokes this command:

attw --pack \
  --exclude-entrypoints addon-main \
  --ignore-rules cjs-resolves-to-esm \
  --ignore-rules wildcard \
  --ignore-rules internal-resolution-error \
  --include-entrypoints \
    ember-primitives color-scheme helpers iframe proper-links template-registry utils \
    components/dialog components/external-link components/link components/popover components/portal-targets components/portal components/shadowed components/switch components/toggle helpers/service \
    test-support/routing \
    components/-private/typed-elements components/-private/utils components/dialog/element-state components/dialog/state \
    ember-primitives/test-support

it's not perfect -- but it's progress

Allow additional entrypoints to be specified

When a package doesn’t have package.json exports or exposes a wildcard in its exports, it would be nice to allow the user to manually specify an entrypoint to check. On the website, this could be done interactively; in the CLI, a new option will be needed. This would effectively eliminate the “Wildcard subpaths cannot yet be analyzed by this tool” problem kind.

lodash types are wrong (or lying?)

I'm not sure 100% what's going on (lodash's js style of exporting is not written in the most standard way — somewhat difficult to parse out in my head), but attw claims lodash's types are correct.

image

However, named lodash imports fail at runtime in node ESM. For example:

import { random } from "lodash";

This will fail with:

SyntaxError: The requested module 'lodash' does not provide an export named 'random'
    at ModuleJob._instantiate (node:internal/modules/esm/module_job:132:21)
    at async ModuleJob.run (node:internal/modules/esm/module_job:214:5)
    at async ModuleLoader.import (node:internal/modules/esm/loader:329:24)
    at async loadESM (node:internal/process/esm_loader:34:7)
    at async handleMainPromise (node:internal/modules/run_main:113:12)

Node.js v20.10.0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.