How muze-nl/metro works
Project Type and Purpose
• This is an open-source JavaScript/TypeScript library (published on npm as @muze-nl/metro) that provides an HTTPS/Fetch client with a middleware pipeline (a Chain of Responsibility pattern) for both browser and Node environments.
File-Structure Analysis
• Top-level directories:
• src/ – ES module source files:
– api.mjs: exposes client() factory, HTTP verbs (get, post, etc.)
– browser.mjs: adapter for window.fetch in browsers
– metro.mjs: core orchestration of middleware + fetch
– everything.mjs: single entry bundling of all exports
– mw/: built-in middleware implementations (json, echo.mock, error.mock, thrower)
• dist/ – bundled distributables: browser.js (for CDN/UMD), everything.js
• test/ – TAP-based unit tests for each module
• docs/ – user docs, tutorials, API reference
• esbuild.mjs – build script using esbuild
• package.json & .terserrc – packaging, versioning, minification
• Patterns and choices:
• Middleware pipeline (ordered stack of functions)
• Immutable Request/Response wrappers with .with() clone API
• Separate entry points for Node vs. browser (adapter pattern)
README Insights
• Purpose: extend standard Fetch API calls with user-provided or built-in middleware
• Usage examples show: client() factory → .with(middleware) → .get/.post → Promise<wrapped Response>
• Core concepts: middleware signature async (req, next) ⇒ res
1. Application Code (user’s script importing Metro)
2. Metro Client Factory (src/api.mjs)
3. Middleware Pipeline (ordered list of middleware modules)
– Built-in (json, echo.mock, error.mock, thrower)
– User-supplied functions
4. Core Orchestrator (src/metro.mjs)
5. Environment Adapter
– Browser (browser.mjs using window.fetch)
– Node (fallback to global.fetch or node-fetch)
6. Network Layer (actual HTTP request over TLS)
7. Build & Distribution
– esbuild bundler (esbuild.mjs) → dist/browser.js / dist/everything.js
– NPM package & CDN (jsdelivr)
• App Code → calls client() → returns Client Instance
• Client Instance → invokes HTTP verb method (get/post) → creates immutable Request
• Request enters Middleware Pipeline:
Middleware₁ → Middleware₂ → … → Middlewareₙ → Core Orchestrator
• Core Orchestrator → calls environment adapter → fetch(Request) → Promise<Response>
• Response returns → flows back through middleware chain in reverse → final Response to App
c. Architectural Patterns and Principles:
• Chain of Responsibility / Pipeline for middleware
• Immutability: every mutation via .with() produces a new object
• Adapter pattern: abstract over browser vs. Node fetch implementations
• Modular bundling: separate source modules, then single-file bundles in dist/
d. Key Technologies and Libraries:
• ES Modules (src/*.mjs)
• Fetch API (native in browser, polyfillable in Node)
• esbuild for bundling/minification
• TAP tests (test/*.mjs)
• NPM publishing, UMD/ESM distribution (dist/)