Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ From there, choose the path that matches the code you have:

1. Keep an application's `socket.io-client` import with the
[test-runner integration guide](./test-runner-integration.md).
2. Choose among the four supported imports in the
2. Choose the supported import in the
[package entry-point guide](./package-entry-points.md).
3. Share one caller-owned mock server across same-origin browser tabs with the
[SharedWorker workflow](./shared-worker.md).
Expand Down
11 changes: 10 additions & 1 deletion docs/package-entry-points.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,23 @@

> **TL;DR** `smocket` owns the in-process server, `smocket-client` is the
> `socket.io-client` substitution, and their `/shared-worker` subpaths expose the
> explicit worker-host and page-client bridge. Keep both packages on one exact version.
> explicit worker-host and page-client bridge. smocket/ws supplies selected Node ws APIs.

## Choose the import by owner

| Import | Owner and role | Main exports |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |
| `smocket` | Test or application fixture in the process that owns the mock server. | `Server`, adapters, server contracts, and retained `connect` / `io` client aliases. |
| `smocket/shared-worker` | SharedWorker bridge code. A worker normally attaches a caller-owned port to its `Server`; lower-level bridge tests may also create the page facade directly. | `attachSharedWorker`, `connectSharedWorker`, and bridge types. |
| `smocket/ws` | Node application code using the selected in-memory ws API. | default/named `WebSocket`, `WebSocketServer`, and selected ws types. |
| `smocket-client` | Application-facing replacement for `socket.io-client` in an in-process test. | default lookup, `io`, `connect`, client `Socket`, and supported options. |
| `smocket-client/shared-worker` | Browser page code connecting through a caller-created `SharedWorker` port. | `connectSharedWorker` and page-socket types. |

`smocket-client` delegates to its exact-version `smocket` peer; it does not own another
server registry. Load both packages through ESM or both through CommonJS so they share the
same module instance. Test-runner aliases should map `socket.io-client` to
`smocket-client`, not to a private `src` or `dist` path.
Keep both packages on one exact version.

## SharedWorker boundary

Expand All @@ -34,3 +36,10 @@ page-client ownership visible as recorded in
See the [SharedWorker workflow](./shared-worker.md) for lifecycle and storage-partition
limits, or the [test-runner guide](./test-runner-integration.md) for Vitest and Jest
substitution examples.

## ws boundary

Use `import WebSocket, { WebSocketServer } from 'smocket/ws'` or
`require('smocket/ws').default` with CommonJS. Keep a server/client pair on one loader.
The [ws contract](./ws-contract.md) defines the selected API and exclusions;
the [package review](./ws-package-review.md) separates package checks from behavioral comparisons.
5 changes: 4 additions & 1 deletion docs/package-policy.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ payload.

`pnpm check:package` remains the standalone root check. The release path instead creates
one [immutable candidate set](./release-candidates.md), checks that the built files import
no external modules, and passes its digest-verified root tarball to package policy,
no external modules in browser entries and only Node Buffer in smocket/ws, and passes its digest-verified root tarball to package policy,
Publint, Are The Types Wrong, and the independent candidate consumers.

The separate `smocket-client` package follows [ADR 0023](./decisions/0023-client-package-is-a-thin-facade.md).
Expand All @@ -23,6 +23,9 @@ tarball must also carry the package README and MIT license. The release candidat
applies the same policy plus Publint and Are The Types Wrong to the manifest's exact
facade tarball.

The Node-only [ws entry](./ws-package-review.md) uses the built-in buffer module;
this adds no installed dependency and does not change browser-entry imports.

A release bumps both manifests to one version. Publish `smocket` first, then publish
`smocket-client`. The authoritative candidate publisher reads the registry and rejects
the client publication until that exact root version exists, including its
Expand Down
6 changes: 3 additions & 3 deletions docs/ws-client-tracking-review.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,6 @@ forwarding with or without the sender, and consecutive text messages followed by
a marker. It also compares normal server close with tracking disabled.
Packed consumers and the application example remain in
[#539](https://github.com/electrohyun/smocket/issues/539).
Payload semantics and complete failure ordering belong to
[#540](https://github.com/electrohyun/smocket/issues/540); package entry checks belong to
[#562](https://github.com/electrohyun/smocket/issues/562).
Payload and failure semantics are described in the [payload](./ws-payloads-review.md)
and [failure](./ws-failure-review.md) reviews; package entry checks belong to
the [package review](./ws-package-review.md).
11 changes: 5 additions & 6 deletions docs/ws-contract.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# ws application contract

> **TL;DR** The ws contract defines selected calls, events, and application-visible
> values independently of transport. Basic source typing is checked here; generated
> declarations, package exports, and independent consumers belong to [#562](https://github.com/electrohyun/smocket/issues/562).
> values independently of transport. Source types and the generated package are
> checked separately; the [package review](./ws-package-review.md) describes their evidence.

## Target usage

Expand Down Expand Up @@ -31,8 +31,7 @@ server.on('connection', (socket, request) => {
CommonJS uses `const WebSocket = require('smocket/ws').default` and
`const { WebSocketServer } = require('smocket/ws')`, as decided in
[0045](./decisions/0045-ws-commonjs-uses-default-export.md). No environment factory or
Buffer injection is required. These are target imports, not evidence of an available
runtime entry. The support decision and exclusions live in
Buffer injection is required. The build supplies both entry formats. The support decision and exclusions live in
[0044](./decisions/0044-ws-api-without-transport.md).

## Type contract
Expand All @@ -59,8 +58,8 @@ IncomingMessage or HTTP Server classes, and it does not create missing runtime b
Run `pnpm check:ws-types` (also included in `pnpm typecheck`). The compile-only fixtures
check inference, explicit socket annotations, callbacks, Buffer interoperability, and
rejection of excluded options. The no-Node case uses types=[] and skipLibCheck=false.
This checks the source contract, not generated declarations, module exports, a packed
package, runtime delivery, or all supported TypeScript versions.
This checks the source contract. `pnpm check:ws-package --tarball <path>` checks one
packed artifact in isolated TS 5.0.2/6.0.3 consumers and exercises both loaders.

The [runtime review notes](./ws-runtime-review.md) describe the internal connection,
text, EventEmitter, and event-listener paths, their real-ws comparisons, and remaining limits.
6 changes: 3 additions & 3 deletions docs/ws-event-listeners-review.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,6 @@ live byte sends and binaryType conversion.
runtime callback receivers, event data, read-only fields, and excluded options.

The [close-race comparisons](./ws-close-races-review.md) cover pending sends and
per-socket close information during termination. Additional failure ordering and
caller-buffer mutation are tracked in [#540](https://github.com/electrohyun/smocket/issues/540).
The package binding and independent consumer checks remain [#562](https://github.com/electrohyun/smocket/issues/562).
per-socket close information during termination. The [payload review](./ws-payloads-review.md)
also covers caller-owned byte storage changed after send.
The [package review](./ws-package-review.md) describes binding and independent consumer checks.
2 changes: 1 addition & 1 deletion docs/ws-input-validation-review.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,4 @@ secure cases abort immediately and do not verify TLS success.
The [receive validation review](./ws-receive-validation-review.md) covers malformed
UTF-8 and fractional codes that truncate to reserved values. The
[close-race review](./ws-close-races-review.md) covers pending work and concurrent close.
The public package binding remains [#562](https://github.com/electrohyun/smocket/issues/562).
The [package review](./ws-package-review.md) describes binding and independent consumer checks.
48 changes: 48 additions & 0 deletions docs/ws-package-review.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# ws package review notes

> **TL;DR** smocket/ws binds its in-memory constructors to the selected public contract and
> generates ESM/CJS declarations. Isolated consumers check one packed artifact;
> package success does not establish full ws behavioral compatibility.

## Implementation choices

[`ws.ts`](../src/ws.ts) assigns actual constructors to the contract structurally,
without casting a partial implementation to the whole contract. Its public exports
describe application APIs without exposing internal classes or requiring Node types.
Default/named constructor identity and CommonJS's explicit default lookup follow
[0045](./decisions/0045-ws-commonjs-uses-default-export.md).

The constructor's address controls the URL type; the server's tracking option
controls clients. TypeScript cannot narrow a generic parameter from a runtime branch,
so assertions are confined to the URL getter and guarded clients initialization.
They do not substitute for implementing public methods. Typed constructor bindings
and consumer examples separately check the resulting relationships.

Real ws supplies null to successful send callbacks even though its declaration uses
an optional Error. The selected type preserves that upstream declaration; the runtime
uses Reflect.apply only for the null success argument. Error callbacks receive Error.
Changing successful calls to undefined would differ from observed ws behavior.

The Node-only entry uses Node Buffer under [0044](./decisions/0044-ws-api-without-transport.md).
The import guard permits buffer/node:buffer only in ws bundles. Browser-facing root
and SharedWorker entries retain zero external imports; package dependencies stay empty.
ESM and CJS own separate registries, so each server/client pair uses the same loader.

## Validation limits

[`check-ws-package.mjs`](../scripts/check-ws-package.mjs) installs the same tarball in
independent TS 5.0.2/6.0.3 consumers, with and without Node types. NodeNext exercises
ESM/CJS declarations; Bundler exercises import declarations. Examples check Buffer
assignments, constructor aliases, client URL types, and client-tracking inference.
Runtime checks load both formats and repeat connection, byte/text exchange, send
callbacks, normal close, and cleanup. The release-candidate gate uses its digest-checked
root tarball for these checks. Test-only fixture mode exercises the checker separately.

[`payloads.test.ts`](../test/ws/payloads.test.ts) compares selected sends, binary
overrides, and live binaryType changes against real ws.
[`client-tracking.test.ts`](../test/ws/client-tracking.test.ts) separately compares
client membership and an all-client broadcast.
The [failure](./ws-failure-review.md), [close-race](./ws-close-races-review.md), and
[receive validation](./ws-receive-validation-review.md) reviews describe the lifecycle
comparisons. The payload review also covers changes to caller-owned byte storage.
TLS, transport, browser-native WebSocket, and Blob remain outside the selected scope.
4 changes: 2 additions & 2 deletions docs/ws-payloads-review.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,5 +43,5 @@ The [close-race review](./ws-close-races-review.md) covers accepted sends during
termination and messages received while normal closing is pending.

Client membership comparisons live in the [client set review](./ws-client-tracking-review.md).
Production entry-point binding and independent package consumers belong to
[#562](https://github.com/electrohyun/smocket/issues/562).
Production entry-point binding and independent package consumers are described in
the [package review](./ws-package-review.md).
12 changes: 5 additions & 7 deletions docs/ws-runtime-review.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

> **TL;DR** The internal ws runtime models server registration, asynchronous
> connection, selected payload delivery, and normal close. Real-ws comparison and mock-specific
> isolation checks establish separate guarantees; package binding belongs to #562.
> isolation checks establish guarantees distinct from the package checks.

## Implementation choices

Expand Down Expand Up @@ -41,12 +41,10 @@ comparison covers Error objects, not Node's formatting of arbitrary unhandled va
[`emitter.typecheck.ts`](../test/ws/emitter.typecheck.ts) checks the actual runtime's
callback receivers, event arguments, aliases, and raw-wrapper typing.

Both constructors must structurally satisfy the test adapter's exercised subset,
without type assertions. Request fixture types keep Node's optional url/method,
while runtime assertions pin their values. This does not establish the complete
public contract or provide a production package entry.
Binding must account for every selected method before [#562](https://github.com/electrohyun/smocket/issues/562)
can validate the actual package.
Both constructors structurally satisfy the public contract at [`ws.ts`](../src/ws.ts)
without whole-contract assertions. Request fixture types keep Node's optional
url/method, while runtime assertions pin their values. The
[package review](./ws-package-review.md) explains generated declarations and consumers.

The [event listener review notes](./ws-event-listeners-review.md) explain event
properties, listener identity, event values, and their comparison limits.
Expand Down
13 changes: 13 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@
"*": {
"shared-worker": [
"./dist/shared-worker.d.ts"
],
"ws": [
"./dist/ws.d.ts"
]
}
},
Expand All @@ -45,6 +48,16 @@
"default": "./dist/index.cjs"
}
},
"./ws": {
"import": {
"types": "./dist/ws.d.ts",
"default": "./dist/ws.js"
},
"require": {
"types": "./dist/ws.d.cts",
"default": "./dist/ws.cjs"
}
},
"./shared-worker": {
"import": {
"types": "./dist/shared-worker.d.ts",
Expand Down
7 changes: 4 additions & 3 deletions scripts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,14 @@

`pnpm check:ws-types` checks the source ws contract and compile-only examples with
and without Node types. It runs as part of `pnpm typecheck`; it does not build or
validate a published `smocket/ws` entry point.
validate a packed `smocket/ws` entry point.

`pnpm check:ws-package:fixture` builds a temporary package from the ws contract and
test-only constructors to exercise the checker independently of the production runtime.
Fixture success proves the validation setup, not a production ws entry or delivery
behavior. The package command requires an explicit tarball and fails if its ws export
is missing.
behavior. The package command requires an explicit tarball, rejects a missing ws
export, and exercises connection, bytes, callbacks, and cleanup through both loaders.
The release-candidate check passes its digest-verified root tarball to this command.

Files named `scripts/*.test.ts` are collected only by the mock Vitest project because
they test repository tooling rather than Socket.IO behavior. `check-public-surface.test.mjs`
Expand Down
16 changes: 9 additions & 7 deletions scripts/assert-no-imports.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,36 @@
// Assert the built bundle imports nothing external.
//
// Every smocket runtime entry bundles to a self-contained file. Importing
// Browser-facing smocket entries bundle to self-contained files. Importing
// nothing is what lets those files run in a browser at all (#105) and keeps
// them from dragging a polyfill into every consumer's build. A `node:` import
// that a bundler shims cleanly would still pass the browser job while doing
// exactly that. The packaging job checks resolution, not contents, so nothing
// but this holds the property. #140 removed the last import (`node:crypto`);
// this keeps it out.
//
// The bundle should contain zero module references, so any match here is a
// regression. Runs after `pnpm build` (wired into `check:package`). The
// The Node-only ws entry may import Node Buffer under ADR 0044. Every other
// external reference remains a regression. Runs after `pnpm build` (wired into `check:package`). The
// reference-detecting regexes and their fixtures live in
// `detect-external-imports.js` and its test.

import { readFileSync } from 'node:fs';
import { pathToFileURL } from 'node:url';
import { detectExternalImports } from './detect-external-imports.js';
import { unexpectedImports } from './detect-external-imports.js';

const files = [
'dist/index.js',
'dist/index.cjs',
'dist/shared-worker.js',
'dist/shared-worker.cjs',
'dist/ws.js',
'dist/ws.cjs',
];

function findOffenders() {
const offenders = [];
for (const file of files) {
const source = readFileSync(new URL(`../${file}`, import.meta.url), 'utf8');
for (const specifier of detectExternalImports(source)) {
for (const specifier of unexpectedImports(file, source)) {
offenders.push({ file, specifier });
}
}
Expand All @@ -40,14 +42,14 @@ function main() {
if (offenders.length > 0) {
const list = offenders.map((o) => ` ${o.file}: ${o.specifier}`).join('\n');
console.error(
`The built bundle references external modules, but it must import nothing:\n${list}\n\n` +
`The built bundle references unsupported external modules:\n${list}\n\n` +
'The zero-import property is what lets the bundle run in a browser and keeps\n' +
"a polyfill out of every consumer's build. If an import is genuinely needed,\n" +
'that is a design change to raise in an issue, not a check to silence.',
);
process.exit(1);
}
console.log(`No external imports in ${files.join(' or ')}.`);
console.log(`External import policy passed for ${files.join(', ')}.`);
}

// Run only when invoked directly, so a test can import the detector without
Expand Down
6 changes: 6 additions & 0 deletions scripts/check-release-candidate.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,12 @@ await run(process.execPath, [
candidate.clientTarball,
]);
candidate = await verifiedCandidate(manifestPath);
await run(process.execPath, [
join(repositoryRoot, 'scripts', 'check-ws-package.mjs'),
'--tarball',
candidate.rootTarball,
]);
candidate = await verifiedCandidate(manifestPath);
await run(process.execPath, [
join(repositoryRoot, 'scripts', 'check-client-package.mjs'),
'--tarball',
Expand Down
Loading
Loading