Repository navigation
💥 Compile src/ to lib/ with TypeScript - #783
alecgibson wants to merge 4 commits into
Conversation
This is the first step of converting ShareDB to TypeScript, replaying the approach from #707 on top of the current `main`. This commit only renames files, so that Git can follow each file's history through the conversion. The files are still CommonJS, and the build to put compiled JS back in `lib/` comes in a later commit. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Eric Hwang <6915076+ericyhwang@users.noreply.github.com> Co-Authored-By: Claude <noreply@anthropic.com>
A few behaviour-preserving tweaks so that the codemods in the next commit produce code that compiles and reads well: - Move `module.exports` above the class JSDoc in four files, so the comment ends up on the class (from #707) - Export `next-tick`'s `setTimeout()` via a differently-named function, since the codemod would otherwise turn it into an `export function setTimeout()` that calls itself. #707 called `global.setTimeout()` instead, but `global` doesn't exist in browsers, where the client also runs - Turn a function declaration inside a block in `QueryEmitter` into a function expression, since TypeScript refuses block-level function declarations in strict mode when targeting ES5 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Eric Hwang <6915076+ericyhwang@users.noreply.github.com> Co-Authored-By: Claude <noreply@anthropic.com>
This commit is entirely generated, by running Eric's two codemods from #707, which convert CommonJS to ES module syntax[1], and ES5 constructor functions to ES6 classes[2]: ``` npx jscodeshift@17.4.0 --parser=ts --extensions=ts \ --transform codemod-cjs-to-esm.ts src npx jscodeshift@17.4.0 --parser=ts --extensions=ts \ --transform codemod-es5-classes.ts src ``` It doesn't compile yet, which the next commit fixes. [1]: https://gist.github.com/ericyhwang/4ef3a6b02d0b86a4a7beda4d57520ccb/0e7636cd5b618a6e903e63170c1fefef63722950 [2]: https://gist.github.com/ericyhwang/32046cc7bcf569c34fda1afefa4d4b0c/50758b0d9497e241089239f92f56817d949417fa 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Eric Hwang <6915076+ericyhwang@users.noreply.github.com> Co-Authored-By: Claude <noreply@anthropic.com>
526a453 to
8b5cd85
Compare
|
Restore util.inherits for OpStream and ServerStream so browser bundles without a stream polyfill load, and turn on strictFunctionTypes Diff |
| "noImplicitAny": false, | ||
| "noImplicitThis": false, | ||
| "strictNullChecks": false, | ||
| "useUnknownInCatchVariables": false, | ||
| "strictBindCallApply": false, | ||
| "strictPropertyInitialization": false |
There was a problem hiding this comment.
These come from the typescript branch, where they were off "until the codebase is more properly typed". Turning each one on today reports:
| Flag | Errors | What they are |
|---|---|---|
noImplicitAny |
1276 in 37 files | Untyped parameters, which is #787 |
noImplicitThis |
9 in 3 files | this in plain functions: OpStream, ServerStream, and a .bind(this) callback in MemoryMilestoneDB |
strictNullChecks |
21 in 11 files | Mostly [] literals inferred as never[], plus a few real ones, like op possibly undefined in Agent |
strictPropertyInitialization |
None of its own | Only takes effect with strictNullChecks on |
useUnknownInCatchVariables |
4 in 2 files | err.message in a catch |
strictBindCallApply |
6 in 2 files | .call() and .apply() arguments in LocalDocPresence and Query |
The fixes would all be type-only, but they'd grow this PR's hand-written diff, so it leaves them off. The follow-up that ships our own declarations turns on everything except noImplicitAny.
8b5cd85 to
bb7fdad
Compare
|
Fix lib/client's ESM named exports (only Connection was detected, so import {types} from 'sharedb/lib/client/index.js' failed) by exporting an object of identifiers, and reword point 4. Diff |
| "target": "ES5", | ||
| "module": "CommonJS", | ||
| "types": [ | ||
| "node" | ||
| ], | ||
| "strict": true, | ||
| "forceConsistentCasingInFileNames": true, | ||
| "ignoreDeprecations": "6.0", | ||
| "noImplicitAny": false, | ||
| "noImplicitThis": false, | ||
| "strictNullChecks": false, | ||
| "useUnknownInCatchVariables": false, | ||
| "strictBindCallApply": false, | ||
| "strictPropertyInitialization": false |
There was a problem hiding this comment.
[🤖 Readability · nit] This config turns strict on and then switches six of its flags off. It also targets ES5 under ignoreDeprecations, and none of it is explained. Someone reading it can't tell what strictness is left, or whether the disabled flags are permanent. They also can't tell that ES5 is what keeps constructors callable without new. tsconfig allows comments, so a few lines here, plus a link to #786, would stop someone from "tidying" it into a broken build.
Details
What's still on after the overrides: strict-mode emit ("use strict"), strictFunctionTypes and alwaysStrict.
Suggestion:
// ES5 so constructors stay callable without `new` (adapters do `DB.call(this)`). See #786.
"target": "ES5",
// TS 6.0 deprecates ES5 output and 7.0 removes it; typescript is pinned to ~6.0 for this.
"ignoreDeprecations": "6.0",
// Strict-mode emit + strictFunctionTypes. The flags below stay off until src/ has real types.
"strict": true,There was a problem hiding this comment.
I'd rather not. We keep comments for what neither the code nor git blame can tell you, and git blame here lands on this commit, which explains the ES5 target and the TS 6 pin. The thread above covers the strict flags, and the declarations follow-up turns most of them back on.
None of them can be tidied away quietly either:
- dropping
ignoreDeprecationsfailstscwith TS5107 - a native-class target fails every test at load (
Cannot assign to read only property 'prototype'onShareDBError) - turning a flag on fails
tscwith the errors in that table
| } | ||
| module.exports = OpStream; | ||
|
|
||
| util.inherits(OpStream, Readable); |
There was a problem hiding this comment.
[🤖 Readability + Tests & conventions · nit] Nearly everything else in src/ is now a class, so function plus util.inherits here, and on ServerStream in stream-socket.ts, looks like something the codemod missed. The obvious tidy-up back to class extends Readable would bring back the browser breakage this PR fixes, and no test would fail until #785 lands. A one-line comment at both sites would keep it from coming back.
Details
I swapped in the codemod's class OpStream extends Readable and class ServerStream extends Duplex from 0d2f206. tsc still emits (it only reports type errors) and mocha gives 1112 passing.
Suggestion (here and at src/stream-socket.ts:76):
// Not `class extends Readable`: a browser bundle without a `stream` polyfill has no parent class,
// and __extends throws on that, while the browser `inherits` package doesn't. See #785.
util.inherits(OpStream, Readable);There was a problem hiding this comment.
I'd rather guard this with a test than a comment. #785 has it as item 5, with a note on why that test needs a stubbed browser inherits. Until it lands, git blame on this line gives the commit that explains it.
|
|
||
| ShareDBError.prototype = Object.create(Error.prototype); | ||
| ShareDBError.prototype.constructor = ShareDBError; | ||
| ShareDBError.prototype.name = 'ShareDBError'; |
There was a problem hiding this comment.
[🤖 Readability · nit] This line only works because it comes after the prototype is replaced, and that's exactly the ordering the codemod got wrong. With declare name still in the class body, moving it back into a static block looks like a harmless tidy-up, but it would quietly make every ShareDBError's name 'Error' again. A short comment on the ordering would protect it.
Details
Suggestion:
// After the prototype replacement above: setting `name` earlier (eg in a static block)
// writes to the prototype Object.create() then throws away.
ShareDBError.prototype.name = 'ShareDBError';There was a problem hiding this comment.
Same as the streams: #785 covers name as item 1, and git blame on this line gives the commit that explains the ordering.
| import Backend = require('./backend'); | ||
| export = Backend; | ||
|
|
||
| Backend.Agent = require('./agent'); |
There was a problem hiding this comment.
[🤖 Tests & conventions · nit] Nothing enforces the ES5 goal that motivated removing Object.assign here. @types/node pulls in ES2020 library types, so tsc accepts ES2015+ APIs, and the tests run on modern Node, where they work. The codemod's Object.assign version builds and passes every test. If ES5 output really matters, it needs a check. If it doesn't, the reason in the commit message is misleading.
Details
I swapped in export = Object.assign(Backend, {...}) from 0d2f206: tsc exits 0, mocha gives 1112 passing, and lib/index.js contains Object.assign. @types/node/index.d.ts has /// <reference lib="es2020" />, so adding lib: ["es5"] won't help while types: ["node"] is set.
Suggestion: an es-check es5 'lib/**/*.js' step in CI catches syntax only, so pair it with an API lint on src/ (eg eslint-plugin-es-x no-object-assign). Or drop "isn't ES5" as the reason.
There was a problem hiding this comment.
I think the reason holds. Nothing else in src/ uses a post-ES5 API, and util.isInteger even falls back when Number.isInteger is missing, so the codemod's Object.assign() would have been the first. Main never enforced this either: its ESLint ecmaVersion: 3 only covered syntax, which the ES5 target now guarantees. An API lint is worth weighing in #786, since that's where we decide whether we stay on ES5 at all.
This change builds `lib/` from the codemodded `src/` with `tsc` on
`prepare` and `pretest`, and fixes its type errors with type-only
changes, so the output matches the codemods' own emit, except where we
undo their mistakes:
1. `ShareDBError` gets its `name` back, which the codemod set before
replacing its `prototype`
2. `MemoryDB` and `MemoryPubSub` can be called without `new` again
3. `index.ts` assigns its exports again, since `Object.assign()` isn't
ES5
4. `lib/client` exports a plain object of identifiers again, so it
has no `__esModule` flag to make bundlers' default imports read
`.default`, and Node's ESM loader still finds its named exports
5. `OpStream` and `ServerStream` inherit with `util.inherits()` again,
so browser bundles without a `stream` polyfill still load
We target ES5 because tests and adapters call our constructors as
functions (eg `MemoryDB.apply(this, arguments)`), which native classes
forbid. TypeScript 6.0 [deprecates ES5 output][1] and 7.0 drops it, so
this pins TypeScript 6.0 and stops Dependabot offering 7.
Notably, `lib/` still behaves differently to today's in ways our tests
don't cover:
- it runs in strict mode, so mutating a frozen object a caller passed
in (eg `Query` options) now throws
- subclass prototypes get an enumerable `constructor`, so eg
`new MemoryDB().constructor` is now `MemoryDB` rather than `DB`
- internal modules like `lib/types` gain `__esModule`, so bundlers
and `esModuleInterop` resolve a default import of one (eg
`import types from 'sharedb/lib/types'`) to `undefined`
- `emitter.EventEmitter` becomes a read-only re-export
[1]: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-6-0.html#deprecated-target-es5
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
bb7fdad to
48a9c7e
Compare
src/ to lib/ with TypeScriptsrc/ to lib/ with TypeScript
|
Ignore TypeScript majors in Dependabot, retitle the commit 💥, and list default imports of internal modules as a breaking change. Diff |
This change builds
lib/from the codemoddedsrc/withtsconprepareandpretest, and fixes its type errors with type-only changes, so the output matches the codemods' own emit, except where we undo their mistakes:ShareDBErrorgets itsnameback, which the codemod set before replacing itsprototypeMemoryDBandMemoryPubSubcan be called withoutnewagainindex.tsassigns its exports again, sinceObject.assign()isn't ES5lib/clientexports a plain object of identifiers again, so it has no__esModuleflag to make bundlers' default imports read.default, and Node's ESM loader still finds its named exportsOpStreamandServerStreaminherit withutil.inherits()again, so browser bundles without astreampolyfill still loadWe target ES5 because tests and adapters call our constructors as functions (eg
MemoryDB.apply(this, arguments)), which native classes forbid. TypeScript 6.0 deprecates ES5 output and 7.0 drops it, so this pins TypeScript 6.0 and stops Dependabot offering 7.Notably,
lib/still behaves differently to today's in ways our tests don't cover:Queryoptions) now throwsconstructor, so egnew MemoryDB().constructoris nowMemoryDBrather thanDBlib/typesgain__esModule, so bundlers andesModuleInteropresolve a default import of one (egimport types from 'sharedb/lib/types') toundefinedemitter.EventEmitterbecomes a read-only re-export🤖 Generated with Claude Code
Co-Authored-By: Claude noreply@anthropic.com