Initial Commit
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* Basic usage example. Wire the `hyperswarmFactory` to the real
|
||||
* `hyperswarm` package at the application boundary; the package itself
|
||||
* never imports `hyperswarm` directly so consumers retain control over
|
||||
* keypair management, dht bootstrap nodes, and lifecycle.
|
||||
*/
|
||||
import {
|
||||
HyperswarmPlugin,
|
||||
type HyperswarmFactory,
|
||||
type HyperswarmInstanceLike,
|
||||
} from "../src/index.js";
|
||||
|
||||
// In production, you'd write:
|
||||
//
|
||||
// import Hyperswarm from "hyperswarm";
|
||||
// const factory: HyperswarmFactory = (opts) =>
|
||||
// new Hyperswarm({ maxPeers: opts?.maxPeers ?? 100 });
|
||||
//
|
||||
// Here we stub it out so the example is type-checked without
|
||||
// requiring the native deps.
|
||||
const factory: HyperswarmFactory = () => {
|
||||
throw new Error("wire to real hyperswarm at the application boundary");
|
||||
};
|
||||
|
||||
export async function main(): Promise<void> {
|
||||
const plugin = new HyperswarmPlugin({
|
||||
topic: "example-room",
|
||||
hyperswarmFactory: factory,
|
||||
maxPeers: 32,
|
||||
});
|
||||
|
||||
// Pretend we have a NetworkNode.
|
||||
const fakeNode = {
|
||||
registerTransport: (_t: unknown): void => undefined,
|
||||
unregisterTransport: (_id: string): void => undefined,
|
||||
};
|
||||
|
||||
plugin.install(fakeNode as never);
|
||||
try {
|
||||
await plugin.start();
|
||||
|
||||
plugin.transport.onMessage((peerId, envelope) => {
|
||||
console.log(`from ${peerId}:`, envelope.type);
|
||||
});
|
||||
|
||||
plugin.transport.onPeerEvent((peerId, event) => {
|
||||
console.log(`peer ${peerId} ${event}`);
|
||||
});
|
||||
} finally {
|
||||
await plugin.stop();
|
||||
plugin.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
// Type-only import to satisfy lint that we use the export.
|
||||
const _T: HyperswarmInstanceLike | null = null;
|
||||
void _T;
|
||||
Reference in New Issue
Block a user