Skip to content

@memberjunction/cli

The official command-line interface for MemberJunction. Provides tools for installation, database migrations, code generation, metadata sync, AI operations, testing, database documentation, and query generation.

graph TD
    subgraph "@memberjunction/cli (mj)"
        A[CLI Entry Point] --> B[Commands]
        B --> C[install]
        B --> D[migrate]
        B --> E[codegen]
        B --> F[sync]
        B --> G[ai]
        B --> H[test]
        B --> I[dbdoc]
        B --> J[querygen]
        B --> K[bump]
        B --> L[clean]

        A --> M[Hooks]
        M --> N[init]
        M --> O[prerun]
    end

    subgraph "Underlying Engines"
        P["@memberjunction/codegen-lib"]
        Q["@memberjunction/metadata-sync"]
        R["@memberjunction/testing-cli"]
        S["@memberjunction/db-auto-doc"]
        T["@memberjunction/query-gen"]
        U["@memberjunction/ai-cli"]
    end

    E --> P
    F --> Q
    H --> R
    I --> S
    J --> T
    G --> U

    style A fill:#2d6a9f,stroke:#1a4971,color:#fff
    style C fill:#2d8659,stroke:#1a5c3a,color:#fff
    style D fill:#2d8659,stroke:#1a5c3a,color:#fff
    style E fill:#7c5295,stroke:#563a6b,color:#fff
    style F fill:#7c5295,stroke:#563a6b,color:#fff
    style G fill:#b8762f,stroke:#8a5722,color:#fff
    style H fill:#b8762f,stroke:#8a5722,color:#fff
    style I fill:#b8762f,stroke:#8a5722,color:#fff
    style J fill:#b8762f,stroke:#8a5722,color:#fff

The mj CLI is built on the oclif framework and acts as a unified entry point for all MemberJunction development tools. Each command group delegates to a specialized package.

Terminal window
# Global (recommended)
npm install -g @memberjunction/cli
# Local
npm install --save-dev @memberjunction/cli

Requires Node.js 20.0.0 or higher.

Uses cosmiconfig to find configuration:

  • mj.config.js / mj.config.cjs
  • .mjrc / .mjrc.json / .mjrc.yaml
  • package.json (in "mj" property)
VariableDefaultDescription
DB_HOSTlocalhostSQL Server hostname or IP
DB_PORT1433SQL Server port
DB_DATABASEDatabase name
CODEGEN_DB_USERNAMESQL Server login
CODEGEN_DB_PASSWORDSQL Server password
DB_ENCRYPTtrueEncrypt the connection (required for Azure SQL)
DB_TRUST_SERVER_CERTIFICATEfalseTrust self-signed certificates (set true for local dev)

These can also be set in mj.config.cjs as dbHost, dbPort, dbDatabase, codeGenLogin, codeGenPassword, dbEncrypt, and dbTrustServerCertificate.

Interactive installer for new MemberJunction environments.

Terminal window
mj install

Sets up the database schema, applies migrations, and generates initial code.

Run database migrations (powered by Skyway).

Terminal window
mj migrate
mj migrate [--verbose] [--tag <version>] [--schema <name>] [--dir <path>]

Options:

  • -v, --verbose: Enable detailed logging
  • -t, --tag <version>: Specify a version tag for migrations (e.g., ‘v2.10.0’)
  • -s, --schema <name>: Target schema (overrides coreSchema from config)
  • --dir <path>: Migration source directory (overrides migrationsLocation from config)

Schema Handling:

  • When using --schema, the specified schema will be automatically created if it doesn’t exist
  • This enables migrating to new schemas without manual DDL setup
  • The schema creation uses Flyway’s createSchemas feature

Examples:

Terminal window
# Basic migration
mj migrate
# Migrate to a specific version tag
mj migrate --tag v2.10.0
# Migrate a custom schema with custom migrations directory
mj migrate --schema __BCSaaS --dir ./migrations/v1
# Verbose output for debugging
mj migrate --verbose

Run MemberJunction code generation.

Terminal window
# Run full code generation
mj codegen
# Generate class registration manifests only
mj codegen manifest
mj codegen manifest --exclude-packages @memberjunction --output ./src/generated/manifest.ts

Starting in MemberJunction v5.0, all 272 core entity names are being normalized with the "MJ: " prefix to prevent naming collisions on client systems (e.g., "Actions" becomes "MJ: Actions"). The database migration handles the rename automatically, but hardcoded entity name strings in your TypeScript source, Angular HTML templates, and metadata JSON files also need updating. These three commands automate that process.

All three commands share the same workflow:

  1. Dry-run first (default) — scans and reports what would change, without modifying any files.
  2. Fix mode (--fix) — applies the changes in place.
  3. Rename map — built dynamically by parsing @RegisterClass(BaseEntity, 'MJ: XYZ') decorators from entity_subclasses.ts. No hardcoded list to maintain.

These commands will be kept for 1-2 years to support the v5.0 upgrade window, then removed.

Scans TypeScript source files (.ts) using the TypeScript compiler AST to find hardcoded entity names that need the "MJ: " prefix. This is the most comprehensive scanner — it understands code context, not just string matching.

Detected patterns:

PatternExample
GetEntityObject callsmd.GetEntityObject<T>('Actions')
OpenEntityRecord callsthis.OpenEntityRecord('Entities', id)
navigateToEntity callsnavigateToEntity('Templates')
BuildRelationshipViewParamsByEntityName callsBuildRelationshipViewParamsByEntityName('Roles')
NewRecordValues callsNewRecordValues('Users')
IsCurrentTab callsIsCurrentTab('Queries')
EntityName: property assignmentsEntityName: 'AI Agent Examples'
.Name === / .Entity === comparisonsentity.Name === 'Actions'
@RegisterClass decorator (BaseEntity)@RegisterClass(BaseEntity, 'Actions')

Default exclusions: node_modules, dist, build, .git, __tests__, *.d.ts, *.spec.ts, *.test.ts, generated/, Demos/

Terminal window
# Dry-run: scan entire packages/ directory
mj codegen 5-0-fix-entity-names --path packages/
# Dry-run: scan a single file
mj codegen 5-0-fix-entity-names --path packages/Angular/Explorer/dashboards/src/Actions/components/actions-overview.component.ts
# Apply fixes
mj codegen 5-0-fix-entity-names --path packages/ --fix
# Custom entity_subclasses.ts location
mj codegen 5-0-fix-entity-names --path packages/ --entity-subclasses ./path/to/entity_subclasses.ts
# Quiet mode (summary only)
mj codegen 5-0-fix-entity-names --path packages/ -q

Scans Angular HTML template files (.html) using targeted regex patterns for entity name references in template expressions and attribute values.

Detected patterns:

PatternExample
Method calls in event/property bindings(click)="navigateToEntity('Actions')"
OpenEntityRecord / openEntityRecord(click)="OpenEntityRecord('Entities', id)"
BuildRelationshipViewParamsByEntityName[Params]="BuildRelationshipViewParamsByEntityName('Roles')"
RowsEntityName attributeRowsEntityName="Users"
JoinEntityName attributeJoinEntityName="Roles"

Default exclusions: node_modules, dist, build, .git, generated/, Demos/

Terminal window
# Dry-run: scan Angular templates
mj codegen 5-0-fix-html-entity-names --path packages/Angular/
# Apply fixes
mj codegen 5-0-fix-html-entity-names --path packages/Angular/ --fix
# Verbose output showing individual file progress
mj codegen 5-0-fix-html-entity-names --path packages/ -v

Scans metadata JSON files (including dotfiles like .mj-sync.json) for entity name references that need the "MJ: " prefix. Targets the metadata/ directory used by mj sync.

Detected patterns:

PatternExample
@lookup: entity name@lookup:Entities.Name=Dashboards
@lookup: value (in Entities lookups)@lookup:MJ: Entities.Name=Actions
Folder config entity/entityName.mj-sync.json with "entity": "Dashboards"
relatedEntities object keys"relatedEntities": { "Actions": [...] }
fields.Name in Entities foldersEntity record data files where Name is the entity name
Terminal window
# Dry-run: scan metadata directory
mj codegen 5-0-fix-metadata-names --path metadata/
# Apply fixes
mj codegen 5-0-fix-metadata-names --path metadata/ --fix
# Scan a specific subdirectory
mj codegen 5-0-fix-metadata-names --path metadata/resource-types
# Scan and fix a single file
mj codegen 5-0-fix-metadata-names --path metadata/entities/.audit-related-entities.json --fix
FlagShortDescription
--path <dir|file>-pFile or directory to scan. Defaults to current directory.
--fixApply fixes in place. Without this flag, runs in dry-run mode.
--entity-subclasses <path>Path to entity_subclasses.ts. Auto-detected if omitted.
--quiet-qSuppress detailed output, show summary only.
--verbose-vShow detailed progress for each file scanned.
Terminal window
# 1. Scan everything first (dry-run)
mj codegen 5-0-fix-entity-names --path packages/
mj codegen 5-0-fix-html-entity-names --path packages/
mj codegen 5-0-fix-metadata-names --path metadata/
# 2. Review the output, then apply
mj codegen 5-0-fix-entity-names --path packages/ --fix
mj codegen 5-0-fix-html-entity-names --path packages/ --fix
mj codegen 5-0-fix-metadata-names --path metadata/ --fix
# 3. Build and test
npm run build

Metadata synchronization between JSON files and the database.

Terminal window
# Initialize metadata directory
mj sync init
# Check sync status
mj sync status
# Pull metadata from database to files
mj sync pull
# Push metadata from files to database
mj sync push
# Validate metadata files
mj sync validate
# Watch for file changes
mj sync watch
# Reset file state
mj sync file-reset

AI-powered operations.

Terminal window
mj ai

Testing framework operations (delegates to @memberjunction/testing-cli).

Terminal window
# Run a test
mj test run --name "My Test"
# Run a suite
mj test suite --name "My Suite"
# List tests
mj test list
# View history
mj test history --name "My Test"
# Compare runs
mj test compare --run1 id1 --run2 id2
# Validate test config
mj test validate --name "My Test"

Database documentation generation.

Terminal window
# Initialize documentation
mj dbdoc init
# Analyze database schema
mj dbdoc analyze
# Export documentation
mj dbdoc export
# Check status
mj dbdoc status
# Reset documentation
mj dbdoc reset
# Generate sample queries
mj dbdoc generate-queries
mj dbdoc export-sample-queries

Query generation tools.

Terminal window
mj querygen generate
mj querygen export
mj querygen validate

Version management for packages.

Terminal window
mj bump

Clean build artifacts.

Terminal window
mj clean

Install, upgrade, and manage MJ Open Apps (packaged via @memberjunction/open-app-engine).

Terminal window
# List installed apps
mj app list
# Show detailed info for one app
mj app info <name>
# Install from a GitHub repository
mj app install https://github.com/acme/mj-crm
mj app install https://github.com/acme/mj-crm --version 1.2.0
# Upgrade to a newer version (latest if --version omitted)
mj app upgrade acme-crm
mj app upgrade acme-crm --version 1.3.0
# Enable / disable without removing
mj app enable <name>
mj app disable <name>
# Remove (add --keep-data to preserve the schema)
mj app remove <name>
mj app remove <name> --keep-data
# See which installed apps have newer versions available
mj app check-updates

Intentionally omitted from --help. Only for MJ-internal apps that own a reserved-looking schema (e.g. __bcsaas). Do not use on third-party apps.

  • --dangerously-ignore-dbl-underscore-schema-rule — available on mj app install and mj app upgrade. Bypasses the rule that blocks schema names starting with __ (reserved for MJ internals). Exact-match reserved names (__mj, dbo, sys, guest, INFORMATION_SCHEMA) remain hard-blocked regardless.
Terminal window
mj app install https://github.com/BlueCypress/SaaS \
--dangerously-ignore-dbl-underscore-schema-rule

Build, compare, and round-trip baseline migrations — a single SQL script that captures the end-state of an entire V-stack (schema + every row of every table) into one deterministic B-prefixed file that Flyway/Skyway can apply to a fresh database in place of the long migration chain.

Niche command — only needed when collapsing a V-stack into a new baseline (within-major rebaseline) or cutting a new major version (e.g. v5 → v6). Day-to-day MJ development never touches this; use mj migrate for routine schema changes.

Three subcommands:

  • mj baseline build — connect to a live MSSQL database, introspect everything, dump every row of every table, and emit a canonical T-SQL script.
  • mj baseline compare — diff two live databases object-by-object and row-by-row.
  • mj baseline roundtripbuild + apply to a fresh DB + compare in one shot. Proves the new baseline is byte-equivalent to the V-stack it replaces.
ModeTriggerVersion sourceTimestampOutput folder
AUTO — within-major rebaseline (default)--baseline-version omittedMajor.Minor parsed from the latest V-file in --source-dirlatest V-file’s timestamp + 1 minutethe same migrations/v{N}/ it scanned
EXPLICIT — major-boundary baseline--baseline-version M.N providedthe flag valueDate.now() UTCmigrations/v{N+1}/ (new)

AUTO mode is the right choice 99% of the time. EXPLICIT is for starting a new major version (e.g. v6.0).

Filename format: B{YYYYMMDDHHMM}__v{Major}.{Minor}.x__Baseline.sql (literal lowercase x matches the V-file patch convention — patches don’t carry migrations).

Terminal window
# AUTO — within-major rebaseline (writes back into ./migrations/v5/)
mj baseline build --out ./migrations/v5/
# EXPLICIT — start a new major version (writes into ./migrations/v6/)
mj baseline build --baseline-version 6.0 --out ./migrations/v6/
# Schema-only, no data inserts
mj baseline build --no-data --out ./baselines/

Key flags: --baseline-version, --source-dir, --database, --out, --exclude-data <csv>, --batch-size, --no-data, --dry-run, --verbose. Run mj baseline build --help for the full list with defaults.

Database host/user/password come from the MJ config (mj.config.cjs / .env); --database overrides only the database name.

Terminal window
# Full row-by-row diff (default)
mj baseline compare --left MJ_BL_Stack --right MJ_BL_New
# Counts-only (fastest)
mj baseline compare --left A --right B --row-compare counts
# CI use — fail the build on any diff, write reports
mj baseline compare --left A --right B --fail-on-diff --out ./diffs/

Row-compare modes: full | hash | counts | none. Hash mode supports --row-hash-algo sha256|md5|checksum_agg. --dialect mssql|postgres (both sides must match).

Terminal window
# AUTO — verify the current v5.x V-stack collapses cleanly
mj baseline roundtrip --source MJ_BL_Stack --target MJ_BL_New
# EXPLICIT — verify a v6.0 baseline
mj baseline roundtrip --baseline-version 6.0 --source MJ_BL_Stack --target MJ_BL_New

--source is the gold-standard DB with the V-stack already applied; --target is an empty DB the new baseline will be applied to and compared against. Add --keep-target to inspect the post-apply DB after a failed diff. --apply-cmd lets you override the default sqlcmd apply step (tokens: {file}, {database}).

  • Slash command/create-new-baseline-migration drives the workbench end-to-end from a local Claude Code session (spins up the workbench, runs the roundtrip, stages the file in migrations/ only if byte-equivalent).
  • Workbench scriptdocker/workbench/baseline-roundtrip.sh (aliases mjbaseline, mjbaseline-mssql, mjbaseline-pg inside the workbench container) is the 7-phase end-to-end runner the slash command invokes.
  • Design recordpackages/MJCLI/src/commands/baseline/PLAN.md documents the architecture, decisions, and component layout.
  • PostgreSQL — the T-SQL baseline is converted via mj migrate convert (see /pg-migrate skill) before being applied to a PG target.
HookTimingPurpose
initBefore any commandLoads configuration, initializes environment
prerunBefore command executionValidates configuration, connects to database

The CLI includes these oclif plugins:

  • @oclif/plugin-help — Auto-generated help text
  • @oclif/plugin-version — Version display
  • @oclif/plugin-warn-if-update-available — Update notifications (checks daily)
PackagePurpose
@memberjunction/codegen-libCode generation engine
@memberjunction/metadata-syncMetadata synchronization
@memberjunction/testing-cliTesting framework CLI
@memberjunction/db-auto-docDatabase documentation
@memberjunction/query-genQuery generation
@memberjunction/ai-cliAI operations
@memberjunction/configConfiguration management
@memberjunction/server-bootstrap-liteLightweight server initialization
@memberjunction/sqlserver-dataproviderDatabase connectivity
@oclif/coreCLI framework
cosmiconfigConfiguration file loading
@memberjunction/skyway-coreDatabase migration execution
simple-gitGit operations
figletASCII art for banners

ISC