@jakobm/portico
v0.10.1
Published
Compose policy-bounded modules and generate architecture views.
Readme
Portico
Portico composes modules from explicit dependency policies. Each module exposes a frozen facade, keeps its implementation factories private, and receives only the other facades and external services its policy permits. The same policy can produce YAML dependency views and an SVG architecture diagram.
Portico is a small, opinionated runtime for compiled CommonJS and ESM module trees. It is not a full Awilix implementation.
Install
npm install @jakobm/porticoNode.js 22.14 or later in the 22.x line is supported. The package ships CommonJS and TypeScript declarations. ESM applications can import its CommonJS default export.
Module tree
Portico supports the original flat layout shown below and two equivalent nested
layouts. In a nested TypeScript tree, every module directory is a boundary. Its
self-contained interface.ts is the authoritative type-only contract, while
exactly one directly owned runtime file exports the named porticoFacade
factory. Contracts and implementations may be colocated:
modules/
dependencies.yaml
external.js
dependencies/
interface.ts
facade.ts
dependencies.yaml
audit.js
planning/
interface.ts
facade.ts
service.js
storage/
interface.ts
facade.ts
service.jsAlternatively, contracts and policies may be split from the full implementation
hierarchy. A contract file is named after its module. Leaf contracts live
directly in their containing collection, while only modules with children keep
a directory in the interface tree. Every dependencies.yaml also belongs in
that tree; every runtime file, private type file, and external.ts belongs in
the implementation tree:
modules/
interfaces/
dependencies.yaml
cli.ts
dependencies/
dependencies.ts
dependencies.yaml
modules/
audit.ts
planning.ts
implementations/
external.ts
cli/
run.ts
dependencies/
facade.ts
audit/
run.ts
planning/
service.tsChild contracts of a branch module always live in its reserved modules/
directory. Portico reconciles those logical modules recursively against the
full implementation hierarchy and rejects a module present on only one side.
The split nested layout is selected by interfaces/dependencies.yaml; the
colocated layout remains fully supported.
The root policy describes top-level modules. A module with children has its own
dependencies.yaml, which describes those children. A child may use sibling
facades and dependencies made available by its parent, but every containing
policy must pass an outer dependency through. Children never receive their
parent facade. Test helpers and architecture output use a module's local name
when it is unique in the tree. If cousins reuse a name, full paths such as
dependencies/storage and secrets/storage distinguish them.
The root policy also selects whether children can inject factories directly from their parent module. Nested policies cannot override it:
module-options:
parent-implementations: available # or private; private is the defaultModule names are unambiguous among siblings and the sibling collections of all
ancestors. Cousins may reuse names. A module may combine local factories and
child modules, but injection names cannot collide. Compiled interface.js and
types.js files are ignored because they contain no runtime factories. Runtime
discovery therefore does not depend on TypeScript emitting an interface file.
The contract name is the directory name converted from kebab-case to PascalCase
(orders → Orders, data-source → DataSource). The facade hook may live in
any directly owned file, alone or beside a normal default factory:
// modules/data-source/interface.ts
export interface DataSource {
read(key: string): Promise<string>;
}
// modules/data-source/operations.ts (colocated layout)
import type { DataSource } from './interface.js';
export default () => async (key: string) => key;
export const porticoFacade = ({ operations }: {
operations: DataSource['read'];
}): DataSource => ({ read: operations });The original flat layout remains supported:
modules/
dependencies.yaml
external.js
interfaces/
source.js
consumer.js
implementations/
source/
consumer/dependencies.yaml defines every module's allowed facade and external
dependencies:
allowed-modules:
source: []
consumer: [source]
allowed-external:
source: [greeting]
consumer: []external.js exports a factory returning the available services:
module.exports = () => ({ greeting: 'hello' });Each interface file exports a facade factory. The factory receives a proxy
with module-local implementations, permitted module facades, and an external
object containing permitted services:
// modules/interfaces/source.js
module.exports = ({ external: { greeting } }) => ({ greeting });
// modules/interfaces/consumer.js
module.exports = ({ source }) => ({ message: `${source.greeting}, world` });Create a container from the compiled tree. Arguments are joined as path segments:
const { createRepositoryContainer } = require('@jakobm/portico');
const container = createRepositoryContainer(__dirname, 'modules');
console.log(container.resolve('consumer').message); // hello, worldTypeScript clients can use import portico = require('@jakobm/portico') in
CommonJS or import portico from '@jakobm/portico' in ESM. The package provides
declarations for both the runtime and testing entry points.
Module and implementation filenames use lowercase kebab-case. For example,
interfaces/data-source.js is resolved as dataSource; its policy key and
implementation directory use dataSource. Module dependency cycles, missing policy entries,
duplicate registration names, and forbidden dependency access fail clearly.
Factory lists
In every layout, a list-<name>/ directory directly inside a module's
implementation registers one dependency named <name> (kebab-case becomes
camelCase). For example, list-definitions/ provides definitions:
implementations/jobs/
facade.ts
service.ts
list-definitions/
reading/get.ts
writing/get.tsEvery factory under the list directory, at any depth, becomes an entry in one
flat list. These subdirectories are organizational: they have no interfaces,
policies, child modules, or separate injection scopes. List factories receive
the owning module's local dependencies, permitted facades, and external services.
Place helper factories outside the list directory if their results should not
be list entries. Only directly owned runtime files may provide porticoFacade.
Entries contain name (the camelCase filename without its extension),
relativePath (relative to the list directory, with / separators), and value
(the factory's synchronous return value). Runtime discovery includes .js,
.mjs, and .cjs files, sorted by relative path. Declaration files and other
assets are ignored. An empty directory provides an empty list.
The list and its entry wrappers are frozen; factory results are not automatically frozen. Factories run lazily when the list is first requested, and their results are cached within the container. Asynchronous container creation supports ESM loading, while the factories themselves must still return synchronously.
List members are only accessible through the list. They do not register
individual injection names, so both reading/get.ts and writing/get.ts may
have the metadata name get. Their paths distinguish them. The list dependency
itself must not collide with another registration, child module, or permitted
module dependency.
For example, a nested TypeScript facade can consume the returned values:
export const porticoFacade = ({ definitions }: {
definitions: ReadonlyArray<{
name: string;
relativePath: string;
value: { method: string; path: string };
}>;
}) => ({ definitions: definitions.map(({ value }) => value) });In the original flat CommonJS layout, the interface factory consumes the same
list as module.exports = ({ definitions }) => ({ definitions });.
portico check --project checks list factories' dependencies and compares the
actual entry types, including metadata and each factory's return type, with
the consumer's requested list type.
Architecture views
const { generateArchitecture } = require('@jakobm/portico');
await generateArchitecture({
modulesRoot: '/absolute/path/to/compiled/modules',
outputDirectory: '/absolute/path/to/architecture',
});The output directory contains depends-on.yaml, used-by.yaml, and
architecture.svg.
The same operation is available as a CLI:
portico architecture \
--modules dist/modules \
--output architecturePaths are resolved from the current working directory. The optional
ubiquitous list in dependencies.yaml changes diagram presentation only.
Run portico --help or portico <command> --help to see the generated command
and option documentation.
Module boundary and TypeScript contract checks
portico check statically verifies JavaScript or TypeScript module trees without
executing application code. JavaScript needs no TypeScript project:
portico check --modules scripts/modulesJavaScript analysis uses the module tree's sources without loading standard libraries, ambient type packages, or imported source trees. It still resolves import targets to enforce ownership and distinguishes local bindings from ambient runtime capabilities.
For TypeScript, supply the project whose configuration and compiler options
should be used. Portico also runs that project's diagnostics, checks each
porticoFacade return type against its module contract, and checks injected
requirements against provider contracts, local factory returns, and external.ts:
portico check --modules src/modules --project tsconfig.jsonPortico validates the project configuration, module structure, and dependency policy before running full TypeScript diagnostics. Fix structural errors first; once the module tree is valid, diagnostics cover the entire supplied project, including files outside the module root.
Runtime dependencies must be injected by default. Module-owned code therefore
cannot directly import or re-export local files, another module's private files,
Node built-ins, or packages. This applies to ESM imports and re-exports,
TypeScript import-equals, CommonJS require(), dynamic import(), and
require.resolve(). The root external.js or external.ts factory is the
composition root and is exempt so it can construct external services.
Programs can explicitly permit direct runtime imports of selected external
packages by adding allowed-imports to the root dependencies.yaml (in
interfaces/ for the split nested layout):
allowed-imports:
- zod
- zod/v4The list applies to every module, including interface files and nested modules,
and to every dependency form checked above. Entries match complete import
specifiers exactly: zod alone does not permit zod/v4. Scoped package names
and explicit package subpaths are supported; wildcards, relative paths, Node
built-ins, and imports across Portico module boundaries are not permitted by
this list. Nested policies cannot override it. Omitting the list or setting it
to [] preserves the default injection requirement.
For example, with zod allowed, module code can use
import { z } from 'zod' to build schemas directly. allowed-imports names
packages loaded by the source code; allowed-modules and allowed-external
continue to name injected module facades and external services. Allowed packages
are loaded normally by Node.js and must be installed by the consuming program.
TypeScript resolution and type checking still apply.
Module-owned code also cannot read ambient runtime capabilities such as
process, console, Buffer, fetch, timers, crypto, performance,
globalThis, or Math.random. Implicit clock reads through Date.now(),
new Date() without arguments, and calling Date() are also forbidden, while
explicit conversions such as new Date(value), Date.parse(), and Date.UTC()
are allowed. Provide runtime capabilities through the root external factory
instead. Locally declared values with the same names are allowed, as are
language intrinsics such as Object, Promise, JSON, and Error.
Projects that deliberately use private implementation imports inside one module can opt in explicitly:
portico check --modules scripts/modules --allow-local-imports
portico check --modules src/modules --project tsconfig.json --allow-local-importsThe flag permits only targets owned by exactly the importing module. Imports
across module boundaries and built-ins remain forbidden; packages still require
an explicit allowed-imports entry. Interface files remain self-contained with
respect to relative imports. A facade hook may
type-import its own interface; cross-module type imports remain forbidden.
Explicit erased TypeScript imports and exports are allowed within a module and from external packages. Type-only imports across Portico module boundaries are rejected so contracts remain local. JSDoc import types are not treated as runtime loads.
The check covers statically recognizable dependency forms and rejects
non-literal targets for those forms. It is an architecture check, not a security
sandbox: aliases to require, eval, custom loaders, and deliberately obscured
loading are outside its guarantee.
Testing
@jakobm/portico/testing creates a separate container with plain-value
overrides and access to internal registrations:
const { createTestRepositoryContainer } = require('@jakobm/portico/testing');
const container = createTestRepositoryContainer('/path/to/compiled/modules');
const greeting = container.resolveExternal('greeting');
container.overrideExternals({ greeting: 'test' });
container.overrideInternal('consumer', 'helper', { value: 'replacement' });
const helper = container.resolveInternal('consumer', 'helper');resolveExternal(name) returns the current external value, including any
override. Overrides clear constructed modules. Production containers expose only
resolve(moduleName).
Internal overrides require an existing registration. Replace a list as a whole
with overrideInternal('jobs', 'definitions', replacementEntries); its members
cannot be resolved or overridden individually. Code using the earlier flat-layout
member registrations must switch to consuming or replacing the list.
Development
Install Volta and ensure its shims are first in PATH.
package.json pins Node.js 22.14.0 and npm 11.21.0 for local development and CI.
npm ci
npm testnpm test runs lint, type checking, and the complete test suite without collecting
coverage.
It uses Portico's own test engine without calling Peacekeeper's test runner.
It includes a tarball test
that installs the packed package in a temporary consumer project and checks
runtime, CLI, ESM import, package exports, and TypeScript declarations. See the release process
for publication setup. Portico is licensed under MIT.
The test commands build once before running compiled tests. The tarball test
packs that build without rerunning lifecycle scripts and installs it once for
CommonJS and ESM consumers in separate package scopes. The installed CLI checks
the TypeScript module fixture and both consumers' declarations in one project;
an npm exec invocation also verifies the installed command registration.
The thin PR workflow calls Peacekeeper's shared Ubuntu job, which validates the
project independently and runs npm test. Optional system packages and Playwright
browsers belong in tests.aptPackages and tests.playwrightBrowsers in
peacekeeper.config.yaml; both lists are empty for Portico.
npm run test:coverage is a separate local command that writes HTML, LCOV, JSON,
and a text summary under coverage/ and requires at least 95% coverage for
statements, branches, functions, and lines. The repository-owned coverage.yml
workflow runs this command and uploads the coverage-report artifact for 14 days,
including when a coverage threshold fails. It has only workflow_dispatch and
must be started manually from GitHub Actions; PRs, pushes, tags and schedules do
not trigger it. Coverage configuration and reporting are owned entirely by Portico.
The Peacekeeper development dependency is pinned to npm version 0.29.0.
Workflow pins must match the approved revisions bundled with that version.
Type and dependency diagnostic tests put independent cases in separate files of a shared fixture and check them in one call. TypeScript fixtures explicitly select ES2022 libraries and disable ambient type packages, so they check the language types they use without loading DOM declarations. Assertions identify each case by its source file and reject unexpected diagnostics, including errors on valid cases. Keep separate fixtures for invalid structures, project configurations, and CLI or packed-package integration. See the checking design.
Asynchronous creation and ESM module trees
Use asynchronous creation to load CommonJS, ESM, or mixed compiled module trees, including modules with top-level await:
import portico from '@jakobm/portico';
const container = await portico.createRepositoryContainerAsync('/app', 'modules');
const service = container.resolve('service');import portico from '@jakobm/portico';
const container = await portico.createRepositoryContainerAsync('/app', 'modules');
const service = container.resolve<{ run(): Promise<void> }>('service');
await service.run();CommonJS consumers can call require('@jakobm/portico').createRepositoryContainerAsync
inside an async function. The testing entry point also exports
createTestRepositoryContainerAsync(...paths) with the existing synchronous test methods.
Ordinary factories use export default in ESM or module.exports in CommonJS;
nested facades use the named porticoFacade export. Factories must return
synchronously, though facade methods may be asynchronous. Async creation imports
and validates all .js, .mjs, and .cjs runtime files before returning.
Synchronous creation stays lazy between modules, but first resolution evaluates
all directly owned runtime files in that module to locate its hook.
Both variants reject Promise/thenable factory results. Async creation detects nested hook conflicts in unused modules; synchronous creation reports them when the owning module is first resolved. Additional extensions participate in discovery and collision checks. See the loading design for export rules, ordering, caching, error timing, architecture validation, and startup side-effect boundaries.
