### Basic start with createServer Source: https://github.com/bcomnes/domstack-sync Starts the server with a static directory, file patterns, and a port. After startup, logs the server URL and the UI URL (which defaults to port 3001 when the UI panel is enabled). ```js import { createServer } from '@domstack/sync' const sync = await createServer({ server: './public', files: ['public/**/*.css', 'public/**/*.html'], port: 3000, }) console.log(sync.url) // http://localhost:3000 console.log(sync.uiUrl) // http://localhost:3001 ``` -------------------------------- ### Install @domstack/sync Source: https://github.com/bcomnes/domstack-sync/blob/master/README.md Install the package. Requires Node.js 22.18 or newer. ```sh npm install @domstack/sync ``` -------------------------------- ### sync.addMiddleware Usage Example Source: https://github.com/bcomnes/domstack-sync Example of adding a middleware to '/api' that sets a header and calls next(), then removing it with sync.removeMiddleware. ```javascript const id = sync.addMiddleware('/api', (req, res, next) => { res.setHeader('x-powered-by', 'domstack') next() }) sync.removeMiddleware(id) ``` -------------------------------- ### CLI commands: init, start, reload, and dss alias Source: https://github.com/bcomnes/domstack-sync Shows the four main CLI invocations: init to write a starter config, start with server and files flags, reload with a port and file, and the dss alias for start. ```sh domstack-sync init ``` ```sh domstack-sync --server . --files '**/*.css' '**/*.html' ``` ```sh domstack-sync reload --port 3000 styles/main.css ``` ```sh dss --server . --files '**/*' ``` -------------------------------- ### createThrottleServer usage example Source: https://github.com/bcomnes/domstack-sync Example of creating a throttle server targeting localhost:3000 with speed 400 KB/s and latency 20 ms, then listening on port 4000. ```js import { createThrottleServer } from '@domstack/sync/lib/throttle-server.ts' const throttle = createThrottleServer({ target: { hostname: 'localhost', port: 3000 }, speed: { speed: 400, latency: 20 } }) throttle.server.listen(4000, '0.0.0.0') ``` -------------------------------- ### GET /help Source: https://github.com/bcomnes/domstack-sync Renders the Help page with the full HTMX layout. ```APIDOC ## [GET] /help ### Description Renders the Help page with the full HTMX layout. ### Method GET ### Endpoint /help ``` -------------------------------- ### domstack-sync CLI usage examples Source: https://github.com/bcomnes/domstack-sync/blob/master/README.md CLI usage examples. The `--server` flag serves a directory, `--files` watches glob patterns, `--watch` watches the served root, and `--no-ui` disables the UI panel. `init` writes a starter config file, and `reload` triggers a reload from another terminal. ```sh # Serve current directory, watch CSS and HTML domstack-sync --server . --files '**/*.css' '**/*.html' # Serve current directory and watch the served root domstack-sync --server . --watch # Watch files without serving (snippet-injection mode) domstack-sync --files '**/*.css' # Short alias dss --server . --files '**/*' # Disable the UI panel domstack-sync --server . --no-ui # Write a starter ESM config file domstack-sync init # Trigger a reload from another terminal domstack-sync reload --port 3000 ``` -------------------------------- ### createServer(options) Source: https://github.com/bcomnes/domstack-sync/blob/master/README.md Creates and starts a sync server instance. Returns a Promise that resolves to a sync server object with properties url and uiUrl. ```APIDOC ## createServer(options) ### Description Creates and starts a sync server instance. Returns a Promise that resolves to a sync server object with properties url and uiUrl. ### Method async function ### Endpoint createServer(options) ### Parameters #### Options Object - **server** (string) - Required - Path to the static directory to serve. - **files** (array of strings) - Required - Glob patterns of files to watch for changes. - **port** (number) - Optional - Port for the main server. Defaults to 3000. - **logger** (pino.Logger) - Optional - A raw Pino logger instance for embedded usage. ### Request Example ```js const sync = await createServer({ server: './public', files: ['public/**/*.css', 'public/**/*.html'], port: 3000, }) ``` ### Response #### Success Response - **sync.url** (string) - The main server URL (e.g., http://localhost:3000). - **sync.uiUrl** (string) - The UI server URL (e.g., http://localhost:3001). ``` -------------------------------- ### GET / Source: https://github.com/bcomnes/domstack-sync Renders the Overview page with the full HTMX layout. ```APIDOC ## [GET] / ### Description Renders the Overview page with the full HTMX layout. ### Method GET ### Endpoint / ``` -------------------------------- ### Starter config file domstack-sync.config.mjs Source: https://github.com/bcomnes/domstack-sync Written by `domstack-sync init` as a starting point. Uses the `default` export as `BsOptionsInput`; CLI flags override per-key. ```javascript // domstack-sync.config.mjs export default { server: '.', files: ['**/*.html', '**/*.css', '**/*.js'], port: 3000, } ``` -------------------------------- ### GET /plugins Source: https://github.com/bcomnes/domstack-sync Renders the Plugins page with the full HTMX layout. ```APIDOC ## [GET] /plugins ### Description Renders the Plugins page with the full HTMX layout. ### Method GET ### Endpoint /plugins ``` -------------------------------- ### GET /sync-options Source: https://github.com/bcomnes/domstack-sync Renders the Sync Options page with the full HTMX layout. ```APIDOC ## [GET] /sync-options ### Description Renders the Sync Options page with the full HTMX layout. ### Method GET ### Endpoint /sync-options ``` -------------------------------- ### Configure logging with createLogger and logAccessUrls Source: https://github.com/bcomnes/domstack-sync/blob/master/README.md Shows two logging setups: standalone usage with createLogger('info') for a pretty Pino logger, and embedded usage passing a raw pino.Logger to createServer. logAccessUrls(logger, urls) prints the access-URL table with your own logger. ```javascript import pino from 'pino' import { createLogger, createServer, logAccessUrls } from '@domstack/sync' // Standalone helper: returns a regular pino.Logger with domstack-sync's pretty formatter. const standaloneLogger = createLogger('info') // Embedded/library usage: pass your own raw pino.Logger. const ownerLogger = pino({ level: 'info' }) const sync = await createServer({ server: './public', files: ['public/**/*.css', 'public/**/*.html'], logger: ownerLogger.child({ component: 'sync', logPrefix: '[domstack-sync]' }), }) logAccessUrls(standaloneLogger, { local: sync.url, ui: sync.uiUrl, }) ``` -------------------------------- ### GET /help Source: https://github.com/bcomnes/domstack-sync Returns the Help page of the UI panel. This is one of the HTML pages served by the UI panel server. ```APIDOC ## [GET] /help ### Description Returns the Help page of the UI panel. ### Method GET ### Endpoint /help ### Response #### Success Response (200) - Content-Type: text/html; charset=utf-8 ``` -------------------------------- ### GET /connections Source: https://github.com/bcomnes/domstack-sync Renders the Connections page with the full HTMX layout. ```APIDOC ## [GET] /connections ### Description Renders the Connections page with the full HTMX layout. ### Method GET ### Endpoint /connections ``` -------------------------------- ### package.json browser-sync:ui configuration Source: https://github.com/bcomnes/domstack-sync Example of the 'browser-sync:ui' key in package.json for UI assets. Loads templates and client:js into string maps keyed by file path, and optional markup/page. ```jsonc { "browser-sync:ui": { "hooks": { "markup": "path/to/markup.html", "page": { "path": "/my-page", "title": "My Page", "template": "…" }, "templates": ["templates/one.html"], "client:js": ["client/one.js"] } } } ``` -------------------------------- ### GET / Source: https://github.com/bcomnes/domstack-sync Returns the Overview page of the UI panel. This is one of the HTML pages served by the UI panel server. ```APIDOC ## [GET] / ### Description Returns the Overview page of the UI panel. ### Method GET ### Endpoint / ### Response #### Success Response (200) - Content-Type: text/html; charset=utf-8 ``` -------------------------------- ### POST /actions/network-throttle/create Source: https://github.com/bcomnes/domstack-sync Starts a throttle proxy. The request body is form-encoded. ```APIDOC ## [POST] /actions/network-throttle/create ### Description Start a throttle proxy (port must be 1024–65535, 4–5 digits, else free port). ### Method POST ### Endpoint /actions/network-throttle/create ### Parameters #### Request Body - **targetId** (string) - Required - Target browser ID - **port** (string) - Optional - Port number (1024–65535, 4–5 digits) - **returnTo** (string) - Optional - Selects the fragment page ### Response #### Success Response (200) - Content-Type: text/html ``` -------------------------------- ### buildSnippet usage example Source: https://github.com/bcomnes/domstack-sync Imports buildSnippet and calls it with port, version, and token to generate the HTML snippet. ```js import { buildSnippet } from '@domstack/sync/lib/snippet.ts' const html = buildSnippet({ port: 3000, version: '0.0.8', token: 'abc' }) ``` -------------------------------- ### Example: using BsSockets Source: https://github.com/bcomnes/domstack-sync Shows importing BsSockets from '@domstack/sync/lib/sockets.ts', creating with logger and options, listening for client:connect, and calling handleUpgrade in an HTTP upgrade handler. ```js import { BsSockets } from '@domstack/sync/lib/sockets.ts' import { createLogger } from '@domstack/sync' const sockets = new BsSockets({ logger: createLogger('debug'), getRuntimeOptions: () => ({ /* ClientRuntimeOptions */ }), }) sockets.on('client:connect', (info) => console.log(info.browser.name)) // later, in an HTTP upgrade handler: sockets.handleUpgrade(req, socket, head) ``` -------------------------------- ### Handling a broken setup with createServer Source: https://github.com/bcomnes/domstack-sync Wraps createServer in a try/catch to handle startup failures. When a plugin cannot be resolved, the error message is 'Could not resolve plugin module ...'. ```js import { createServer } from '@domstack/sync' try { const sync = await createServer({ server: './public', plugins: ['@scope/plugin-that-does-not-exist'], }) } catch (err) { console.error('startup failed:', err.message) // "Could not resolve plugin module ..." } ``` -------------------------------- ### createThrottleServer Source: https://github.com/bcomnes/domstack-sync Creates an unstarted net.Server that proxies inbound connections to a target host through rate-limit transforms. The server is not started automatically; you must call server.listen(port, host) yourself. ```APIDOC ## createThrottleServer ### Description Creates an unstarted `net.Server` that proxies each inbound connection to the specified target through two rate-limit `Transform`s: upstream fixed at 10 KB/s, downstream at `speed.speed * 1024` bytes/s, both delayed by `speed.latency` ms. Sockets are tracked; `close()` destroys them and closes the server. ### Signature ```ts export function createThrottleServer (opts: ThrottleServerOptions): ThrottleServerInstance ``` ### Parameters #### Options - **target** (ThrottleTarget) - Required - `{ hostname: string; port: number }` - The target host and port to proxy connections to. - **speed** (ThrottleSpeed) - Required - `{ speed: number; latency: number }` - Speed in KB/s and latency in ms for downstream throttling. - **listenHost** (string) - Optional - Host to bind the server to (passed to `server.listen`). ### Returns - **ThrottleServerInstance** - `{ server: Server; close: () => Promise }` - An unstarted `net.Server` and a `close` function that destroys tracked sockets and closes the server. ### Example ```js import { createThrottleServer } from '@domstack/sync/lib/throttle-server.ts' const throttle = createThrottleServer({ target: { hostname: 'localhost', port: 3000 }, speed: { speed: 400, latency: 20 } }) throttle.server.listen(4000, '0.0.0.0') ``` ``` -------------------------------- ### createServer Source: https://github.com/bcomnes/domstack-sync Starts the Fastify HTTP server, static file serving, snippet injection, file watcher, WebSocket relay, plugin manager, and optionally the UI panel. It is the single entry point for embedding @domstack/sync in a tool. ```APIDOC ## createServer ### Description Starts the Fastify HTTP server, static file serving, snippet injection, file watcher, WebSocket relay, plugin manager, and optionally the UI panel. It is the single entry point for embedding @domstack/sync in a tool. ### Method async function ### Signature ```ts export async function createServer (rawOpts: BsOptionsInput | BsOptions = {}): Promise ``` ### Parameters #### Parameters - **rawOpts** (`BsOptionsInput | BsOptions`) - Optional - Default: `{}` - Full option object (see configuration.md). Pass an already-normalized `BsOptions` object to skip re-parsing. ### Returns `Promise` — resolves once the Fastify server is listening. ### Throws/Rejects - **AggregateError** - Startup failed *and* cleanup of already-allocated resources also failed; message: `Failed to start domstack-sync and clean up allocated resources` (see errors.md) - **any startup error** - The underlying error from `parseOptions`, `fastify.listen`, plugin loading, etc., re-thrown after cleanup ### Request Example ```js import { createServer } from '@domstack/sync' const sync = await createServer({ server: './public', files: ['public/**/*.css', 'public/**/*.html'], port: 3000, }) console.log(sync.url) // http://localhost:3000 console.log(sync.uiUrl) // http://localhost:3001 ``` ### Request Example (handling a broken setup) ```js import { createServer } from '@domstack/sync' try { const sync = await createServer({ server: './public', plugins: ['@scope/plugin-that-does-not-exist'], }) } catch (err) { console.error('startup failed:', err.message) // "Could not resolve plugin module ..." } ``` ``` -------------------------------- ### parseOptions usage example Source: https://github.com/bcomnes/domstack-sync Shows how to import and call parseOptions. The output demonstrates that server is normalized to an object with baseDir, routes, directory, and index defaults, and ghostMode.forms is expanded to all three form flags. ```js import { parseOptions } from '@domstack/sync' const opts = parseOptions({ server: './public', ghostMode: { forms: false } }) console.log(opts.server) // { baseDir: ['./public'], routes: {}, directory: false, index: ['index.html', 'index.htm'] } console.log(opts.ghostMode.forms) // { submit: false, inputs: false, toggles: false } ``` -------------------------------- ### BsWatcher usage example Source: https://github.com/bcomnes/domstack-sync Creates a watcher with mixed glob and object entries, listens for debounced 'changes' events, then closes. ```js import { BsWatcher } from '@domstack/sync/lib/watcher.ts' const watcher = new BsWatcher({ files: ['src/**/*.css', { match: 'src/**/*.html', options: { awaitWriteFinish: true } }], debounceMs: 500, watchEvents: ['change', 'add'], }) watcher.on('changes', (batch) => console.log(batch.map(e => e.path))) await watcher.close() ``` -------------------------------- ### GET /network-throttle Source: https://github.com/bcomnes/domstack-sync Renders the Network Throttle page with the full HTMX layout. ```APIDOC ## [GET] /network-throttle ### Description Renders the Network Throttle page with the full HTMX layout. ### Method GET ### Endpoint /network-throttle ``` -------------------------------- ### logAccessUrls example Source: https://github.com/bcomnes/domstack-sync Creates a server and logger, then logs access URLs. The output shows a boxed table with a divider before the first 'ui*' entry; non-string/empty entries are skipped. ```js import { createLogger, createServer, logAccessUrls } from '@domstack/sync' const sync = await createServer({ server: './public' }) const logger = createLogger('info') logAccessUrls(logger, { local: sync.url, external: `http://${sync.localIp}:${sync.port}`, ui: sync.uiUrl, }) // Access URLs: // ------------------------------- // Local: http://localhost:3000 // External: http://192.168.1.10:3000 // ... ``` -------------------------------- ### GET /sync-options Source: https://github.com/bcomnes/domstack-sync Returns the Sync Options page of the UI panel. This is one of the HTML pages served by the UI panel server. ```APIDOC ## [GET] /sync-options ### Description Returns the Sync Options page of the UI panel. ### Method GET ### Endpoint /sync-options ### Response #### Success Response (200) - Content-Type: text/html; charset=utf-8 ``` -------------------------------- ### createServer function signature Source: https://github.com/bcomnes/domstack-sync Declares the createServer function that starts the Fastify HTTP server, static file serving, snippet injection, file watcher, WebSocket relay, plugin manager, and optionally the UI panel. It accepts either a BsOptionsInput or an already-normalized BsOptions object and returns a Promise that resolves once the server is listening. ```ts // lib/server.ts:92 export async function createServer (rawOpts: BsOptionsInput | BsOptions = {}): Promise ``` -------------------------------- ### curl GET /__browser_sync__ Source: https://github.com/bcomnes/domstack-sync Calls the legacy BrowserSync HTTP protocol with method=reload and args=core.css. ```sh curl 'http://localhost:3000/__browser_sync__?method=reload&args=core.css' ``` -------------------------------- ### GET /browser-sync/plugins/.js Source: https://github.com/bcomnes/domstack-sync Serves plugin client JavaScript assets. Each plugin has one asset identified by its slug. ```APIDOC ## [GET] /browser-sync/plugins/.js ### Description Plugin client JS assets (one per plugin, from the `client:js` hook). `slug` is `slugify(plugin.name)`. ### Method GET ### Endpoint /browser-sync/plugins/.js ### Parameters #### Path Parameters - **slug** (string) - Required - The slugified plugin name. ### Response #### Success Response (200) - **Content-Type**: `application/javascript; charset=utf-8` - **Body**: The plugin's client JavaScript. ``` -------------------------------- ### GET /plugins Source: https://github.com/bcomnes/domstack-sync Returns the Plugins page of the UI panel. This is one of the HTML pages served by the UI panel server. ```APIDOC ## [GET] /plugins ### Description Returns the Plugins page of the UI panel. ### Method GET ### Endpoint /plugins ### Response #### Success Response (200) - Content-Type: text/html; charset=utf-8 ``` -------------------------------- ### applyGhostModePatch usage example Source: https://github.com/bcomnes/domstack-sync Shows how to import and use applyGhostModePatch with parseOptions to update ghost-mode options at runtime. The comment shows the resulting options object. ```javascript import { applyGhostModePatch, parseOptions } from '@domstack/sync' let opts = parseOptions({}) opts.ghostMode = applyGhostModePatch(opts.ghostMode, { scroll: false, forms: { inputs: false } }) // { scroll: false, clicks: true, location: true, forms: { submit: true, inputs: false, toggles: true } } ``` -------------------------------- ### GET /connections Source: https://github.com/bcomnes/domstack-sync Returns the Connections page of the UI panel. This is one of the HTML pages served by the UI panel server. ```APIDOC ## [GET] /connections ### Description Returns the Connections page of the UI panel. ### Method GET ### Endpoint /connections ### Response #### Success Response (200) - Content-Type: text/html; charset=utf-8 ``` -------------------------------- ### BsWatcher constructor Source: https://github.com/bcomnes/domstack-sync Creates a watcher with options. String globs share one chokidar watcher; each FileWatchObject gets its own watcher with merged options. ```ts // lib/watcher.ts:32 constructor (opts: WatcherOptions) ``` -------------------------------- ### Standalone pretty logger example Source: https://github.com/bcomnes/domstack-sync Creates a standalone pretty logger with default prefix, a silent logger, and a custom-prefixed logger. The default prefix is '[domstack-sync]' and output is colorized on TTY. ```js import { createLogger } from '@domstack/sync' const logger = createLogger('info') // [domstack-sync] prefixed, colorized on TTY const quiet = createLogger('silent') const custom = createLogger('debug', {}, { prefix: '[my-tool]' }) ``` -------------------------------- ### AggregateError: Failed to start domstack-sync and clean up allocated resources Source: https://github.com/bcomnes/domstack-sync Triggered when createServer startup fails and post-startup cleanup tasks also fail. The aggregate contains both errors; cause is the startup error. Source: lib/server.ts:102. ```javascript try { await createServer({ ... }) } catch (err) { if (err instanceof AggregateError) { console.error(err.errors) // [startupError, cleanupError] } if (err?.cause) console.error('root cause:', err.cause) } ``` -------------------------------- ### Starter config written by init Source: https://github.com/bcomnes/domstack-sync Default configuration file created by the init command. Sets server root to '.', watches HTML/CSS/JS globs, and listens on port 3000. ```js // @domstack/sync config // https://github.com/bcomnes/domstack-sync export default { server: '.', files: ['**/*.html', '**/*.css', '**/*.js'], port: 3000, } ``` -------------------------------- ### POST /actions/network-throttle/create Source: https://github.com/bcomnes/domstack-sync Spawns a throttle proxy server. ```APIDOC ## [POST] /actions/network-throttle/create ### Description Spawns a throttle proxy server; `port` must be 4–5 digits in 1024–65535 or a free port is found. ### Method POST ### Endpoint /actions/network-throttle/create ### Parameters #### Request Body - `targetId` (string) - Required - Target identifier - `port` (number) - Optional - Port number (4-5 digits, 1024-65535) ``` -------------------------------- ### GET /history Source: https://github.com/bcomnes/domstack-sync Renders the History page with the full HTMX layout. ```APIDOC ## [GET] /history ### Description Renders the History page with the full HTMX layout. ### Method GET ### Endpoint /history ``` -------------------------------- ### GET /remote-debug Source: https://github.com/bcomnes/domstack-sync Renders the Remote Debug page with the full HTMX layout. ```APIDOC ## [GET] /remote-debug ### Description Renders the Remote Debug page with the full HTMX layout. ### Method GET ### Endpoint /remote-debug ``` -------------------------------- ### sync.serveFile(path, props) Source: https://github.com/bcomnes/domstack-sync Registers a middleware to serve custom content at a given route. Returns a middleware ID that can be used with removeMiddleware. ```APIDOC ## sync.serveFile(path, props) ### Description Registers a middleware to serve custom content at a given route. Returns a middleware ID that can be used with removeMiddleware. ### Method Function call ### Signature ```ts serveFile: (path: string, props: PluginServeFileOptions) => string ``` ### Parameters - `path` (string) - Required - Route to serve the content at (registered with `fastify.use`) - `props` (PluginServeFileOptions) - Required - `{ type: string; content: string | Buffer }` — content-type and body ### Returns - `string` — a middleware id (`Browsersync - `), usable with `removeMiddleware`. Registered with `{ override: true, exact: true }`. ### Request Example ```js const mwId = sync.serveFile('/health.json', { type: 'application/json', content: '{"ok":true}' }) sync.removeMiddleware(mwId) ``` ``` -------------------------------- ### GET /browser-sync/pesticide.css, /browser-sync/pesticide-depth.css Source: https://github.com/bcomnes/domstack-sync Serves remote-debug stylesheets for debugging layouts. These are static CSS assets. ```APIDOC ## [GET] /browser-sync/pesticide.css, /browser-sync/pesticide-depth.css ### Description Serves remote-debug stylesheets (vendored, `lib/remote-debug/`). ### Method GET ### Endpoint /browser-sync/pesticide.css /browser-sync/pesticide-depth.css ### Response #### Success Response (200) - **Content-Type**: `text/css; charset=utf-8` - **Body**: CSS stylesheet content. ``` -------------------------------- ### sync.serveFile() - serve custom content and remove middleware Source: https://github.com/bcomnes/domstack-sync Registers a route with fastify.use to serve content, returning a middleware id usable with removeMiddleware. The route is registered with override and exact options. ```js const mwId = sync.serveFile('/health.json', { type: 'application/json', content: '{"ok":true}' }) sync.removeMiddleware(mwId) ``` -------------------------------- ### GET /__browser_sync__ Source: https://github.com/bcomnes/domstack-sync Legacy BrowserSync HTTP protocol endpoint. Supports the `reload` method via query parameters. ```APIDOC ## [GET] /__browser_sync__ ### Description Legacy BrowserSync HTTP protocol (`legacyHttpProtocolRouteSchema`). ### Method GET ### Endpoint /__browser_sync__ ### Parameters #### Query Parameters - **method** (string) - Required - API method; only `reload` is implemented. - **args** (string, repeatable) - Optional - Reload argument (single or array). ### Response #### Success Response (200) - **Content-Type**: `text/plain` - **Body**: `Called public API method `.reload()`` + `With args: ` #### Error Response (404) - **Content-Type**: `text/plain` - **Body**: `Public API method \`\` not found.` #### Error Response (500) - **Content-Type**: `text/plain` - **Body**: `Error: No Parameters were provided.\nExample: http://localhost:3000/__browser_sync__?method=reload&args=core.css` ### Request Example ```sh curl 'http://localhost:3000/__browser_sync__?method=reload&args=core.css' ``` ``` -------------------------------- ### sync.getUserPlugins() / sync.getUserPlugin(name) Source: https://github.com/bcomnes/domstack-sync Retrieves user plugin state. getUserPlugins returns an array of all user plugin states; getUserPlugin returns a single plugin state by name. ```APIDOC ## sync.getUserPlugins() / sync.getUserPlugin(name) ### Description Retrieves user plugin state. getUserPlugins returns an array of all user plugin states; getUserPlugin returns a single plugin state by name. ### Method Function call ### Signatures ```ts getUserPlugins: () => UserPluginState[] getUserPlugin: (name: string) => UserPluginState | undefined ``` ### Parameters - `name` (string) - Required for getUserPlugin - The name of the plugin ### Returns - `UserPluginState` = `{ name, title, active, opts?, markup?, page?, templates?, clientJs? }` ### Request Example ```js const plugin = sync.getUserPlugin('my-plugin') if (plugin) console.log(plugin.title, plugin.active) ``` ``` -------------------------------- ### sync.addMiddleware(route, handle, opts?) Source: https://github.com/bcomnes/domstack-sync Registers a middleware function on a route prefix or globally. Returns the middleware id for later removal. ```APIDOC ## sync.addMiddleware(route, handle, opts?) ### Description Registers a middleware function on a route prefix or globally. Returns the middleware id for later removal. ### Method addMiddleware ### Parameters #### Path Parameters - **route** (string) - Required - Path prefix (or `'*'` for global). `'*'` registers a global middleware; anything else registers on that prefix via `fastify.use` - **handle** (PluginMiddleware) - Required - `(req: IncomingMessage, res: ServerResponse, next: () => void) => void \| Promise` - **opts.id** (string) - Optional - Middleware id for later removal. Default: `bs-mw-` - **opts.override** (boolean) - Optional - Accepted but not consulted by the runtime wrapper (kept for plugin compatibility) ### Response #### Success Response - **Returns** (string | undefined) - The middleware id (`opts.id` or generated). Runtime-placed entries are inactive when their owning plugin is deactivated; with `exact: true` (internal, set by `serveFile`) the handler only runs when the request pathname exactly equals the route. ### Request Example ```js const id = sync.addMiddleware('/api', (req, res, next) => { res.setHeader('x-powered-by', 'domstack') next() }) sync.removeMiddleware(id) ``` ``` -------------------------------- ### GET /history Source: https://github.com/bcomnes/domstack-sync Returns the History page of the UI panel. This is one of the HTML pages served by the UI panel server. ```APIDOC ## [GET] /history ### Description Returns the History page of the UI panel. ### Method GET ### Endpoint /history ### Response #### Success Response (200) - Content-Type: text/html; charset=utf-8 ``` -------------------------------- ### BsPluginManager.getUserPlugins() Source: https://github.com/bcomnes/domstack-sync Returns deep-enough copies of all plugin states (opts/templates/clientJs/page cloned). ```APIDOC ## BsPluginManager.getUserPlugins() ### Description Returns deep-enough copies of all plugin states (opts/templates/clientJs/page cloned). ### Method getUserPlugins ### Endpoint BsPluginManager.getUserPlugins() ### Parameters #### Parameters None ### Response #### Success Response - **UserPluginState[]** - Deep-enough copies of all plugin states (opts/templates/clientJs/page cloned) ``` -------------------------------- ### BsPluginManager.getClientJsAssets() Source: https://github.com/bcomnes/domstack-sync Returns bundled client JS per plugin. ```APIDOC ## BsPluginManager.getClientJsAssets() ### Description Returns bundled client JS per plugin. ### Method getClientJsAssets ### Endpoint BsPluginManager.getClientJsAssets() ### Parameters #### Parameters None ### Response #### Success Response - **Array<{ pluginName, id, src, content }>** - Bundled client JS per plugin: `src` is `/browser-sync/plugins/.js`, `id` is `__browser-sync-plugin--client-js__`; content is hook output joined with `';'` ``` -------------------------------- ### Import all types from @domstack/sync Source: https://github.com/bcomnes/domstack-sync/blob/master/README.md Import all exported types from the @domstack/sync package. Use this to get TypeScript type definitions for options, instances, and WebSocket messages. ```ts import type { AccessUrls, BsInstance, BsOptions, BsOptionsInput, LoggerOptions, LoggerStreams } from '@domstack/sync' import type { ServerToClientMessage, ClientToServerMessage } from '@domstack/sync' ``` -------------------------------- ### GET /network-throttle Source: https://github.com/bcomnes/domstack-sync Returns the Network Throttle page of the UI panel. This is one of the HTML pages served by the UI panel server. ```APIDOC ## [GET] /network-throttle ### Description Returns the Network Throttle page of the UI panel. ### Method GET ### Endpoint /network-throttle ### Response #### Success Response (200) - Content-Type: text/html; charset=utf-8 ``` -------------------------------- ### GET /remote-debug Source: https://github.com/bcomnes/domstack-sync Returns the Remote Debug page of the UI panel. This is one of the HTML pages served by the UI panel server. ```APIDOC ## [GET] /remote-debug ### Description Returns the Remote Debug page of the UI panel. ### Method GET ### Endpoint /remote-debug ### Response #### Success Response (200) - Content-Type: text/html; charset=utf-8 ``` -------------------------------- ### Catch createServer errors with try/catch Source: https://github.com/bcomnes/domstack-sync Wrap createServer in try/catch to handle startup failures. AggregateError exposes .errors array; other errors are logged and rethrown. ```javascript import { createServer } from '@domstack/sync' export async function start () { try { return await createServer({ server: './public' }) } catch (err) { if (err instanceof AggregateError) { for (const sub of err.errors) console.error('sub-error:', sub.message) } else { console.error('startup failed:', err.message) } throw err } } ``` -------------------------------- ### POST /actions/remote-debug/overlay-grid/update Source: https://github.com/bcomnes/domstack-sync Updates grid settings and re-pushes CSS. ```APIDOC ## [POST] /actions/remote-debug/overlay-grid/update ### Description Updates grid settings and re-pushes CSS. ### Method POST ### Endpoint /actions/remote-debug/overlay-grid/update ### Parameters #### Request Body - `size` (optional) - Grid size - `color` (optional) - Grid color - `selector` (optional) - CSS selector - `offsetY` (optional) - Y offset - `offsetX` (optional) - X offset - `vertical` (optional) - Vertical setting - `horizontal` (optional) - Horizontal setting ``` -------------------------------- ### GET /__bs/client.js Source: https://github.com/bcomnes/domstack-sync Serves the bundled browser client JavaScript file. This endpoint is used by the injected snippet to load the client-side script. ```APIDOC ## [GET] /__bs/client.js ### Description Serves the bundled browser client (`lib/client/dist/browser-sync-client.js`). ### Method GET ### Endpoint /__bs/client.js ### Parameters #### Query Parameters - **token** (string) - Optional - Session token used for WebSocket authentication (not used for this endpoint). ### Response #### Success Response (200) - **Content-Type**: `application/javascript; charset=utf-8` - **Body**: The IIFE client bundle. ### Request Example ```sh curl http://localhost:3000/__bs/client.js?v=1.0.0&token=abc123 ``` ``` -------------------------------- ### Use @domstack/sync createServer API Source: https://github.com/bcomnes/domstack-sync/blob/master/README.md Shows the full API surface of @domstack/sync: createServer with options, reload, notify, stream, events, pause/resume, and exit. The server URL is http://localhost:3000 and the UI URL is http://localhost:3001. reload(['styles/main.css']) falls back to a full reload if the file is not matched. ```javascript import { createServer, parseOptions } from '@domstack/sync' const sync = await createServer({ server: './public', files: ['public/**/*.css', 'public/**/*.html'], port: 3000, }) console.log(sync.url) // http://localhost:3000 console.log(sync.uiUrl) // http://localhost:3001 // Trigger a full reload sync.reload() // CSS-inject a specific file (falls back to full reload if not matched) sync.reload(['styles/main.css']) // Show a notification overlay in connected browsers sync.notify('Build complete') // Stream integration — pipe any { path } objects through to trigger reloads someReadableStream.pipe(sync.stream()) // Listen for server-side events sync.events.on('client:connect', (info) => console.log('connected', info.ua)) sync.events.on('client:disconnect', (id) => console.log('disconnected', id)) sync.events.on('file:change', (evt) => console.log('changed', evt.path)) // Pause / resume watcher-triggered reloads (e.g. during a build) sync.pause() sync.resume() // Graceful shutdown await sync.exit() ``` -------------------------------- ### BsPluginManager.init(api) Source: https://github.com/bcomnes/domstack-sync Initializes the plugin manager with the given plugin API. Calls each plugin's plugin function and collects client assets and events. ```APIDOC ## BsPluginManager.init(api) ### Description Initializes the plugin manager with the given plugin API. Calls each plugin's plugin function and collects client assets and events. ### Method init ### Endpoint BsPluginManager.init(api) ### Parameters #### Parameters - **api** (BrowserSyncPluginApi) - Required - The plugin API handed to each plugin's `plugin()` function (with the UI `listen` capability attached) ### Response #### Success Response - **Promise** - Calls each plugin's `plugin(pluginApi, options)` (awaited), then collects client JS assets, client event names, client elements, and plugin pages. ``` -------------------------------- ### getConnections method Source: https://github.com/bcomnes/domstack-sync Returns snapshot of all connected clients. ```ts // lib/sockets.ts:132 getConnections (): BsClientInfo[] ``` -------------------------------- ### POST /actions/options Source: https://github.com/bcomnes/domstack-sync Toggles a ghost-mode or form sub-option via setRuntimeOptions and broadcasts options to browsers. ```APIDOC ## [POST] /actions/options ### Description Toggles a ghost-mode (scroll/clicks/location) or form sub-option (inputs/toggles/submit) via setRuntimeOptions; broadcasts options to browsers. ### Method POST ### Endpoint /actions/options ### Parameters #### Request Body - `kind` (string) - Required - `'ghost'` or `'form'` - `key` (string) - Required - The option key - `active` (string) - Required - `'true'` to activate ``` -------------------------------- ### BsPluginManager.fromEntries Source: https://github.com/bcomnes/domstack-sync Static factory method to create a BsPluginManager instance from plugin entries. Resolves each entry via module resolution and UI asset loading. ```APIDOC ## BsPluginManager.fromEntries ### Description Static factory method to create a BsPluginManager instance from plugin entries. Resolves each entry via module resolution and UI asset loading. ### Method fromEntries ### Endpoint BsPluginManager.fromEntries ### Parameters #### Parameters - **entries** (BrowserSyncPluginEntry[]) - Required - Plugin entries (string spec, function, module object, or `{ module, options }`) - **cwd** (string) - Required - Base directory for resolving module names ### Response #### Success Response - **Promise** - Resolves each entry via `resolvePluginEntry` (module resolution, UI asset loading, query-option parsing). `undefined` entries are skipped. #### Error Response - **Error** - `Plugin was not configured correctly`, `Plugin must export a plugin function or plugin module object`, or `Could not resolve plugin module ""` ``` -------------------------------- ### POST /actions/remote-debug/overlay-grid Source: https://github.com/bcomnes/domstack-sync Toggles the overlay grid and pushes generated CSS to browsers. ```APIDOC ## [POST] /actions/remote-debug/overlay-grid ### Description Toggles the overlay grid; pushes generated CSS to browsers. ### Method POST ### Endpoint /actions/remote-debug/overlay-grid ### Parameters #### Request Body - `active` (string) - Required - `'true'` to activate ``` -------------------------------- ### registerInjector usage example Source: https://github.com/bcomnes/domstack-sync Imports registerInjector from '@domstack/sync/lib/injector.ts' and attaches it to a Fastify instance with a blacklist for '/admin' and '/api' paths and a custom rule that injects the snippet after the opening tag. ```js import { registerInjector } from '@domstack/sync/lib/injector.ts' registerInjector(fastify, snippetHtml, { blacklist: ['/admin', '/api'], rule: { match: /]*>/i, fn: (snippet, match) => match + snippet }, }) ``` -------------------------------- ### POST /actions/remote-debug/file Source: https://github.com/bcomnes/domstack-sync Toggles a client file (e.g. pesticide, pesticide-depth) and adds/removes the CSS element in browsers. ```APIDOC ## [POST] /actions/remote-debug/file ### Description Toggles a client file (e.g. `pesticide`, `pesticide-depth`); adds/removes the CSS element in browsers. ### Method POST ### Endpoint /actions/remote-debug/file ### Parameters #### Request Body - `name` (string) - Required - The client file name - `active` (string) - Required - `'true'` to activate ``` -------------------------------- ### BsPluginManager.getMiddlewares(api) Source: https://github.com/bcomnes/domstack-sync Returns middlewares from each plugin's 'server:middleware' hook. ```APIDOC ## BsPluginManager.getMiddlewares(api) ### Description Returns middlewares from each plugin's 'server:middleware' hook. ### Method getMiddlewares ### Endpoint BsPluginManager.getMiddlewares(api) ### Parameters #### Parameters - **api** (BrowserSyncPluginApi) - Required - Plugin API ### Response #### Success Response - **Array<{ pluginName: string; handle: PluginMiddleware }>** - Middlewares from each plugin's `'server:middleware'` hook (single or array) ``` -------------------------------- ### createLogger(level) Source: https://github.com/bcomnes/domstack-sync/blob/master/README.md Creates a standalone Pino logger with domstack-sync's pretty formatter. ```APIDOC ## createLogger(level) ### Description Creates a standalone Pino logger with domstack-sync's pretty formatter. ### Method function ### Endpoint createLogger(level) ### Parameters #### Required Arguments - **level** (string) - Required - Log level (e.g., 'info'). ### Request Example ```js const standaloneLogger = createLogger('info') ``` ``` -------------------------------- ### BsPluginManager.setOptions(name, opts) Source: https://github.com/bcomnes/domstack-sync Replaces the plugin's options wholesale. ```APIDOC ## BsPluginManager.setOptions(name, opts) ### Description Replaces the plugin's options wholesale. ### Method setOptions ### Endpoint BsPluginManager.setOptions(name, opts) ### Parameters #### Parameters - **name** (string) - Required - Plugin name - **opts** (Record) - Required - New options ### Response #### Success Response - **UserPluginState | undefined** - Updated plugin state, or `undefined` when unknown ``` -------------------------------- ### sync.getUserPlugin() - access plugin state Source: https://github.com/bcomnes/domstack-sync Retrieves a user plugin's state via the plugin manager proxy. Returns undefined if the plugin is not found. ```js const plugin = sync.getUserPlugin('my-plugin') if (plugin) console.log(plugin.title, plugin.active) ``` -------------------------------- ### sync.exit() Source: https://github.com/bcomnes/domstack-sync Gracefully shuts down the sync server. Clears timers, closes the watcher, UI server, throttle servers, plugin cleanup tasks, and the socket server, then closes Fastify. ```APIDOC ## sync.exit() ### Description Gracefully shuts down the sync server. Clears timers, closes the watcher, UI server, throttle servers, plugin cleanup tasks, and the socket server, then closes Fastify. ### Method Function call (async) ### Signature ```ts exit: () => Promise ``` ### Request Example ```js try { await sync.exit() } catch (err) { console.error('shutdown failed', err) } ``` ``` -------------------------------- ### sync.reload(files?) Source: https://github.com/bcomnes/domstack-sync Broadcasts a reload event to all connected browsers. With no argument, triggers a full reload; with file paths, filters and emits file-change events, then decides between file-reload and full reload. ```APIDOC ## sync.reload(files?) ### Description Broadcasts a reload event to all connected browsers. With no argument, triggers a full reload; with file paths, filters and emits file-change events, then decides between file-reload and full reload. ### Method Function call ### Signature ```ts reload: (files?: ReloadArg) => void | Transform ``` ### Parameters - `files` (ReloadArg) - Optional - A file path `string`, `string[]`, or a `{ stream: true, match?, once? }` options object. Passing the stream-object form returns a `Transform` stream instead of scheduling a broadcast. ### Returns - `void` when a plain reload argument is given; a `Transform` (object mode) stream when `files` is a `ReloadStreamOptions` object. ### Behavior With no argument, broadcasts `{ type: 'reload' }` to every browser (after debounce/throttle). With file paths, each path is filtered through `filterReloadFiles` (`.map` files are dropped) and emitted as a `file:change` event; the broadcast then runs through `getReloadDecision` — matching assets are broadcast as `file-reload`, otherwise a full `reload`. ### Request Example ```js // Full reload of all connected browsers sync.reload() // CSS-inject a specific file (falls back to full reload when not matched) sync.reload(['styles/main.css']) ``` ``` -------------------------------- ### Listen to sync.events events Source: https://github.com/bcomnes/domstack-sync Subscribe to documented events emitted by the shared EventEmitter instance. Handles client connect/disconnect, file changes, and stream changes with the provided payloads. ```javascript sync.events.on('client:connect', (info) => console.log('connected', info.ua)) sync.events.on('client:disconnect', (id) => console.log('disconnected', id)) sync.events.on('file:change', (evt) => console.log('changed', evt.path)) sync.events.on('stream:changed', ({ changed }) => console.log('stream changed:', changed.join(', '))) ```