How to design a module system
I take module, package, and library to have interchangeable meanings that are free to vary between contexts, similar to the way that the meanings of promise, task, and future vary between contexts.
For this article, I take package to mean the unit of publication. Packages are versioned and contain modules. I take the meaning of library to be much more flexible, and therefore, much less useful.
The contract #
At the heart of a module system is the contract between a package’s author and the authors of the packages that depend upon it. Packages have versions. In a useful package versioning system, we try to manage the ramifications of change. Portions of a dot delimited version number indicate whether dependent packages may upgrade without a migration, or will need to perform migration steps when they upgrade.
The contract is not absolute. If you take Hyrum’s Law at face value, all changes are breaking changes, since at the limit, someone may have come to rely upon every interface and behavior. However, there is a window between when a package arrives in an ecosystem and when (or if) an ecosystem arrives at the package, and in that window, there is a wondrous period where the probability of a change breaking anyone is relatively low. Beyond some point, it is easier to assume that every behavior and interface is exercised, and that many implicit forms of coupling have crept into the ecosystem. At this point, your package must turn to stone or weigh carefully the cost of change.
We mitigate these risks with interfaces, protocols, contracts, and encapsulation. There are ways that a package can become dependent on implementation details that the author meant to leave flexible. We have conventions that limit the scope of a compatibility guarantee.
For example, in JavaScript, if you monkey-patch a dependency, and a patch to that dependency breaks your application, you get to keep both pieces. You can blame no one but yourself for overcoupling.
For example, in C++, if you compile your program against headers that you have modified to make private fields public, and an upgrade to your dependency changes the structure of internal private state, that one’s on you. If you reach into private state with pointer arithmetic, you may be reminded that the Greek pantheon exists to remind you about the consequences of hubris.
Languages and module systems provide mechanisms to enable the author of a package to express what they consider to be a breaking change, and to communicate that boundary, so that security fixes can be propagated smoothly, and the costs of a migration are borne with collective agency.
Sovereign namespaces #
One of the purposes of a module system is to mitigate the troubles with global namespaces. As with so many problems, we solve this one with levels of indirection. If a module system does not mitigate global namespace problems by providing a reliable contract that allows individual packages to evolve independently and without coordination, that module system has failed to enable a Cambrian explosion of development. It has created a dark forest, where any change can be a breaking change if it tries hard and believes in itself.
For example, if your module system encourages users to carve out a portion of
a global namespace with pithy abbreviations like NS, and your community
contains both Netscape and NeXTSTEP, this module system has failed as a
module system and maybe isn’t even worthy of the name.
If your module system supports wildcard imports, it has embraced a global namespace. It has deferred but not eliminated the possibility that modules from two packages, evolving independently and without coordination, may choose to export the same name, such that another program that imports both will be broken when these packages inevitably do, thereby breaking the contract that small changes do not obligate the consumer to modify their software when they upgrade.
Every module should have a sovereign lexical namespace on which no other module can intrude. Names that are imported or exported should be entirely explicit.
This is the kind of problem that is easy to dismiss as long as the probability is so low that you never experience it yourself. You only need to experience a breaking change in a patch release once to understand that this kind of problem can be and should be made impossible.
Python failed this test by supporting wildcard imports. CommonJS passed this test. ECMAScript modules failed this test by supporting multiple wildcard exports, making the problem more subtle, although ultimately the same. Do not fail.
In Python, from a import * followed by from b import * lets b
quietly shadow any name a also exports, the day b adds it.
In CommonJS, require returns an object and the importer names what it takes
from it, so a new export in a dependency cannot land in anyone’s scope
uninvited.
In ECMAScript modules, a module that says export * from "a" and
export * from "b" exports neither when both export the same name, so the
day b adds a name that a already has, every module that imports that name
from the aggregate fails to link.
A module system and language should strive to minimize the amount of effort necessary to make a change. For example, it should be possible to import a file relative to another file, so that if they move together in a directory, their internal linkage does not break.
It should not be necessary to change every import statement in a package to reflect a minor version change in a dependency. For this reason, packages have manifests. A manifest is a level of indirection between a package’s modules and its dependencies, so a version change does not perturb imports. That is, another level of indirection.
Every namespace should be sovereign. In a module, the lexical namespace should be sovereign. An exported name should not dictate the imported name. To do so would imply global coupling: yet another dark forest where breaking changes can only be avoided with global coordination.
Within a package, the module namespace should be sovereign. A dependency should not be able to dictate the name you use to link against it. Same argument.
The last global namespace #
Most module systems bottom out at yet another global namespace. For the npm ecosystem, this is the package namespace. The npm registry mitigated this somewhat with scopes, allowing an author or organization to stake a claim on a subtree. It is not an absolute failure to minimize coordination without eliminating coordination.
However, it is possible to eliminate coordination with public key cryptography. If a package is identified by its public key, no one needs to agree on who gets which name, because no one can claim a key that someone else holds. The name a package goes by is the business of whoever depends upon it, in their own manifest, which is sovereignty again, one level up.
Registries remain, to solve the problem of individual publishers losing their private keys. But we can have more than one. The key, not the registry, says what the package is, so a registry becomes a service that a publisher chooses and can leave.
And registries can federate and a bill of materials can subscribe to multiple mirrors. A manifest can declare hints about where a package can be found. A version can be identified by its integrity hash, so it does not matter which mirror served it. The list of versions can be addressed in a registry by the package’s public key, signed with it. The package itself, the whole train of versions, is identified by that public key.
Public keys also mitigate eval twins.
When a program loads two copies of the same package, through two paths in
its dependency graph, it gets two instances that do not recognize each
other’s objects: a class from one fails instanceof against the other, and
a registry or a weak map in one is invisible to the other.
The public key solves equality.
A system that knows two copies are the same package, and can see which of
two versions is newer, can avoid multiple instances of the same package.
Semantic versioning is sentimental #
Semver is not actually semantic. It is very much sentimental.
The only bit that matters is whether the author of a package thinks they might have broken a dependent package. The difference between adding a feature and fixing a bug is sentimental if you have not, in practice, created a burden for your consumers. To satisfy the semantics of managing change, you only need to identify a package, and within that package, a single, monotonically increasing version number, indicating whether a version is better than a prior one in some way.
A breaking change, then, is not a bigger number. It is a new package, with a new identity, that can live beside the old one in the same program while its dependents migrate at their own pace.
Manifests and bills of materials #
Differentiate the manifest from the bill of materials.
The manifest is what an author asks for: the packages they depend upon, and the least version of each that they have tested against. The bill of materials is what a program actually gets: every package in the transitive closure, at one exact version, with an integrity hash. Most package managers compute the bill of materials from the manifest by asking a registry for the newest versions that satisfy a range, and the answer changes whenever anyone publishes, so they write it down in a lock file to keep it from moving.
In the npm ecosystem, a package that is left behind, beyond a certain
distance, cannot catch up.
An author cannot gradually raise the version numbers of their dependencies, probing
for the first change that inadvertently broke their package, against a backdrop
of contemporary packages that their dependencies were tested against.
It is possible, but fraught, to try this rising-tide approach based on all
contemporary packages published before a certain time.
The metadata are available, and npm even has npm install --before=<date>,
but the tools do not teach you to do this.
Go gets version management right. The working set is the transitive closure of the greatest version that any manifest mentions for every named package. To change the bill of materials, you must change the manifest. A static manifest never breaks. If a pair of packages fails to compose on their most recent versions, dependent packages are not broken, but cannot upgrade until the maintainers of the two packages coordinate a fix.
Nothing anyone publishes later can change what a program builds with, because the versions it builds with are all named in manifests it already has. Upgrading is an edit, and an edit is a commit that someone made on purpose and can revert. The bill of materials simply captures the integrity hashes of the packages in the solution set, which settles deterministically, unless a version is definitively withdrawn.
In conclusion #
A module system is a contract for managing change without coordination. Wherever a module system falls short, some namespace is still shared: the lexical scope of a module, opened by a wildcard; the names a package uses for its dependencies, dictated by those dependencies; the names of packages, allotted by a registry; or the versions a program runs, chosen by a resolver from whatever was published last. We solve each of these the same way, with another level of indirection that puts the choice in the hands of the party that has to live with it.
So, to design a module system:
- Make every import and export explicit, and let the importer choose the name.
- Link modules within a package by relative paths, and link dependencies through a manifest.
- Identify packages by public key, so that registries and mirrors are interchangeable and twins can be recognized.
- Give each package a single increasing version number, and make a breaking change a new package.
- Keep the manifest apart from the bill of materials, so that only an edit to a manifest can change what a program runs.
A module system like that cannot stop a package from turning to stone once the ecosystem arrives at it. It can keep the wondrous window open for as long as a package is young enough to change, and it can spare everyone else the dark forest, so that each of us need only pay attention to the packages we choose.
On Modules:
- JavaScript Modules Revisited
- JavaScript Module Loader
- JavaScript Module Standard
- Interoperable JavaScript Modules
- How to design a module system
- Previous: Yet Another YAML
- Next: Board Book Shop