The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.
TypeScript b2b-marketplacecomposable-commerceecommerceenterpriseheadless-commercemarketplacemedusamedusajsmulti-vendortypescript
add docs
vholikdcf9cefe5982
diff --git a/README.md b/README.mdindex c23e95a24..9455bb070 100644--- a/README.md+++ b/README.md@@ -1,135 +1,144 @@-# Turborepo starter+++<div align="center">+ <h1>Mercur <br> Open Source Marketplace Platform</h1>+ <!-- Shields.io Badges -->+ <a href="https://github.com/mercurjs/mercur/tree/main?tab=MIT-1-ov-file">+ <img alt="License" src="https://img.shields.io/badge/license-MIT-blue.svg" />+ </a>+ <a href="#">+ <img alt="PRs Welcome" src="https://img.shields.io/badge/PRs-welcome-brightgreen.svg" />+ </a>+ <a href="https://rigbyjs.com/#contact">+ <img alt="Support" src="https://img.shields.io/badge/support-contact%20author-blueviolet.svg" />+ </a>+ <!-- Website Links -->+ <p>+ <a href="https://mercurjs.com/">Mercur</a> | <a href="https://docs.mercurjs.com/">Docs</a>+ </p>+</div>++# What is Mercur?++<a href="https://www.mercurjs.com/">Mercur</a> is the first+truly limitless open source marketplace platform that+combines the simplicity of SaaS with the freedom of open+source. Built on+[MedusaJS](https://github.com/medusajs/medusa), it empowers+businesses to create custom marketplaces without choosing+between ownership and ease of use.++Mercur is a platform to start, customize, manage, and scale+your marketplace for every business model with a modern+technology stack.++## Announcing Mercur 1.0++After months of development, testing, and close+collaboration with early adopters, we’re excited to announce+the official release of **Mercur 1.0** - the first truly+limitless marketplace platform. Version 1.0 is fully open+source and ready to be self-hosted, giving you **full+control over infrastructure, customizations, and data**.++With this version, **Mercur is production-ready for B2C+marketplaces**. The first complete version includes a vendor+system, admin panel, and a fully built B2C Storefront. Read+more in+**[official release announcement](https://www.mercurjs.com/updates/mercur-1-0-release)**++## Why Choose Mercur?++- Full Ownership: Unlike SaaS platforms, you own your+ marketplace with no transaction fees or vendor lock-in+- Modern Foundation: Built on MedusaJS, offering a modern+ tech stack that developers love+- Beautiful by Default: Create stunning storefronts without+ sacrificing customization++## Power Any Marketplace Model++- Custom B2B Marketplace: Build enterprise-grade platforms+ with specialized workflows+- Custom B2C Marketplace: Create engaging consumer+ marketplaces with modern UX+- eCommerce Extension: Transform your store into a+ marketplace (coming soon)+++ ++# Ready-to-go marketplace features++<b>Storefronts for Marketplace </b> <br> Customizable+storefronts designed for B2B and B2C with all elements+including browsing and buying products across multiple+vendors at once.++Discover+<a href="https://github.com/mercurjs/b2c-marketplace-storefront">B2C+Storefront Repository</a> -+<a href="https://b2c.mercurjs.com/">🛍️ Check demo </a>++<b>Admin Panel</b> <br> Control over whole marketplace:+setting product categories, vendors, commissions and rules++<b>Vendor Panel</b> <br> A powerful dashboard giving sellers+complete control over their products, orders, and store+management in one intuitive interface.++Discover+<a href="https://github.com/mercurjs/vendor-panel">Vendor+Panel</a> - <a href="https://www.mercurjs.com/contact">+Contact us to get demo </a>++<b>Integrations</b> <br> Built-in integration with Stripe+for payments and Resend for communication needs. More+integrations coming soon.++++ ++## Quickstart++**Step 1**: Create a new Mercur project and start the development server:++```bash+npx @mercurjs/cli create my-marketplace-This Turborepo starter is maintained by the Turborepo core team.--## Using this example--Run the following command:--```sh-npx create-turbo@latest-```--## What's inside?--This Turborepo includes the following packages/apps:--### Apps and Packages--- `docs`: a [Next.js](https://nextjs.org/) app-- `web`: another [Next.js](https://nextjs.org/) app-- `@repo/ui`: a stub React component library shared by both `web` and `docs` applications-- `@repo/eslint-config`: `eslint` configurations (includes `eslint-config-next` and `eslint-config-prettier`)-- `@repo/typescript-config`: `tsconfig.json`s used throughout the monorepo--Each package/app is 100% [TypeScript](https://www.typescriptlang.org/).--### Utilities--This Turborepo has some additional tools already setup for you:--- [TypeScript](https://www.typescriptlang.org/) for static type checking-- [ESLint](https://eslint.org/) for code linting-- [Prettier](https://prettier.io) for code formatting--### Build--To build all apps and packages, run the following command:--```-cd my-turborepo--# With [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation) installed (recommended)-turbo build--# Without [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation), use your package manager-npx turbo build-yarn dlx turbo build-pnpm exec turbo build-```--You can build a specific package by using a [filter](https://turborepo.dev/docs/crafting-your-repository/running-tasks#using-filters):--```-# With [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation) installed (recommended)-turbo build --filter=docs--# Without [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation), use your package manager-npx turbo build --filter=docs-yarn exec turbo build --filter=docs-pnpm exec turbo build --filter=docs-```--### Develop--To develop all apps and packages, run the following command:--```-cd my-turborepo--# With [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation) installed (recommended)-turbo dev--# Without [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation), use your package manager-npx turbo dev-yarn exec turbo dev-pnpm exec turbo dev```-You can develop a specific package by using a [filter](https://turborepo.dev/docs/crafting-your-repository/running-tasks#using-filters):+**Step 2**: Start the development server:+```bash+cd my-marketplace+npm run dev```-# With [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation) installed (recommended)-turbo dev --filter=web-# Without [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation), use your package manager-npx turbo dev --filter=web-yarn exec turbo dev --filter=web-pnpm exec turbo dev --filter=web-```--### Remote Caching--> [!TIP]-> Vercel Remote Cache is free for all plans. Get started today at [vercel.com](https://vercel.com/signup?/signup?utm_source=remote-cache-sdk&utm_campaign=free_remote_cache).--Turborepo can use a technique known as [Remote Caching](https://turborepo.dev/docs/core-concepts/remote-caching) to share cache artifacts across machines, enabling you to share build caches with your team and CI/CD pipelines.--By default, Turborepo will cache locally. To enable Remote Caching you will need an account with Vercel. If you don't have an account you can [create one](https://vercel.com/signup?utm_source=turborepo-examples), then enter the following commands:+**Step 3**: Access your marketplace:-```-cd my-turborepo+- Backend API: `http://localhost:9000`+- Admin Panel: `http://localhost:7000`+- Vendor Panel: `http://localhost:7001`-# With [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation) installed (recommended)-turbo login+ -# Without [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation), use your package manager-npx turbo login-yarn exec turbo login-pnpm exec turbo login-```+## Prerequisites-This will authenticate the Turborepo CLI with your [Vercel account](https://vercel.com/docs/concepts/personal-accounts/overview).+- [Node.js v20+](https://nodejs.org/en/download)+- [PostgreSQL](https://www.postgresql.org/download/)+- [Redis](https://redis.io/download/)+- [Git CLI](https://git-scm.com/downloads)-Next, you can link your Turborepo to your Remote Cache by running the following command from the root of your Turborepo:+# Resources-```-# With [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation) installed (recommended)-turbo link--# Without [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation), use your package manager-npx turbo link-yarn exec turbo link-pnpm exec turbo link-```+#### Learn more about Mercur-## Useful Links+- [Mercur Website](https://www.mercurjs.com/)+- [Mercur Docs](https://docs.mercurjs.com/introduction)-Learn more about the power of Turborepo:+#### Learn more about Medusa-- [Tasks](https://turborepo.dev/docs/crafting-your-repository/running-tasks)-- [Caching](https://turborepo.dev/docs/crafting-your-repository/caching)-- [Remote Caching](https://turborepo.dev/docs/core-concepts/remote-caching)-- [Filtering](https://turborepo.dev/docs/crafting-your-repository/running-tasks#using-filters)-- [Configuration Options](https://turborepo.dev/docs/reference/configuration)-- [CLI Usage](https://turborepo.dev/docs/reference/command-line-reference)+- [Medusa Website](https://www.medusajs.com/)+- [Medusa Docs](https://docs.medusajs.com/v2)\ No newline at end of filediff --git a/packages/cli/CLI_ANALYSIS.md b/packages/cli/CLI_ANALYSIS.mddeleted file mode 100644index 05e67d26e..000000000--- a/packages/cli/CLI_ANALYSIS.md+++ /dev/null@@ -1,409 +0,0 @@-# Mercur CLI--## Overview--The `@mercurjs/cli` is a TypeScript-based command-line tool built with Bun for managing code "blocks" across registries. It provides project scaffolding, component installation, and registry management capabilities.-------## Directory Structure--```-/src-├── index.ts # Main entry point (Commander.js setup)-├── commands/ # 8 CLI commands-│ ├── add.ts # Add blocks to project-│ ├── build.ts # Build registry from source-│ ├── create.ts # Scaffold new project-│ ├── diff.ts # Compare local vs registry versions-│ ├── info.ts # Display project information-│ ├── init.ts # Initialize blocks.json config-│ ├── search.ts # Search registry blocks-│ └── view.ts # View block details-├── preflights/ # Pre-execution validation-├── registry/ # Registry system (fetch, resolve, build)-├── schema/ # Zod validation schemas-└── utils/ # Utility functions and helpers-```-------## Commands--### `init` - Initialize Configuration--**File:** `src/commands/init.ts`--Creates and manages `blocks.json` configuration file for the project.--**Options:**-| Flag | Description |-|------|-------------|-| `-y, --yes` | Skip confirmation prompts |-| `-d, --defaults` | Use default configuration values |-| `-c, --cwd` | Set working directory |-| `-s, --silent` | Suppress output |--**Flow:**-1. Validates project directory exists-2. Detects existing config (update) or creates new-3. Prompts for import aliases (workflows, api, links, modules, vendor, admin, lib)-4. Resolves aliases using tsconfig-paths-5. Writes `blocks.json`-------### `add` - Add Blocks to Project--**File:** `src/commands/add.ts`--Installs blocks from registries into the project.--**Usage:** `mercur add <block-names...>`--**Options:**-| Flag | Description |-|------|-------------|-| `-y, --yes` | Skip confirmation |-| `-o, --overwrite` | Overwrite existing files |-| `-c, --cwd` | Working directory |-| `-s, --silent` | Suppress output |--**Flow:**-1. Validates config exists (prompts init if missing)-2. Resolves registry tree with dependencies-3. Performs topological sort for correct ordering-4. Transforms imports to match local config-5. Writes files (prompts on conflicts)-6. Installs npm dependencies-7. Displays block documentation-------### `create` - Create New Project--**File:** `src/commands/create.ts`--Scaffolds a new Mercur project with template, dependencies, and database.--**Usage:** `mercur create [project-name]`--**Options:**-| Flag | Description |-|------|-------------|-| `-t, --template` | Template choice (`basic` or `registry`) |-| `-y, --yes` | Skip prompts |-| `--no-deps` | Skip dependency installation |-| `--skip-db` | Skip database setup |-| `--db-connection-string` | Use existing database connection |--**Flow:**-1. Prompts for project name and template-2. Creates project directory-3. Downloads template from GitHub as tar.gz-4. Installs dependencies (auto-detects package manager)-5. Sets up PostgreSQL database with migrations/seeding-6. Manages `.env` files-7. Shows next steps-------### `build` - Build Registry--**File:** `src/commands/build.ts`--Builds a registry from source files into distributable JSON files.--**Usage:** `mercur build [registry-path]`--**Options:**-| Flag | Description |-|------|-------------|-| `-o, --output` | Output directory (default: `./registry`) |-| `-c, --cwd` | Working directory |-| `-v, --verbose` | Verbose output |--**Flow:**-1. Reads `registry.json` source-2. For each item, recursively resolves imports using ts-morph-3. Deduplicates files and dependencies-4. Validates against schema-5. Writes individual `{name}.json` files-------### `search` - Search Registry--**File:** `src/commands/search.ts`--Searches blocks in registries by name or description.--**Usage:** `mercur search -q <query>`--**Options:**-| Flag | Description |-|------|-------------|-| `-q, --query` | Search query string |-| `-r, --registry` | Registry to search (default: `@mercurjs`) |--**Output:** JSON array of matching items-------### `view` - View Block Details--**File:** `src/commands/view.ts`--Displays detailed information about specific blocks.--**Usage:** `mercur view <block-names...>`--**Output:** JSON with full block definitions-------### `diff` - Check for Updates--**File:** `src/commands/diff.ts`--Compares installed blocks with registry versions.--**Usage:** `mercur diff <block-names...>`--**Output:** Color-coded diff (green=added, red=removed)-------### `info` - Project Information--**File:** `src/commands/info.ts`--Displays project configuration and environment details.--**Output:** JSON with config and project info-------## Registry System Architecture--### Core Components--#### Fetcher (`src/registry/fetcher.ts`)-- Fetches registry items from URLs or local files-- Implements request caching-- Handles HTTP errors with context--#### Builder (`src/registry/builder.ts`)-- Constructs registry URLs with templating (`{name}` placeholder)-- Expands environment variables (`${VAR}` syntax)-- Manages headers and query parameters--#### Resolver (`src/registry/resolver.ts`)-- Main resolution logic with dependency handling-- **Topological sort** for correct dependency ordering-- **Circular dependency detection** using SHA256 hashing-- **Deduplication** with last-one-wins policy--#### Parser (`src/registry/parser.ts`)-- Parses `@registry/block-name` format-- Regex: `@[a-zA-Z0-9](?:[a-zA-Z0-9-_]*[a-zA-Z0-9])?/(.+)`--### Data Flow--```-User Input (block names)- ↓-Parse Registry Namespace- ↓-Build URLs (templating + env vars)- ↓-Fetch JSON (with caching)- ↓-Resolve Dependencies (recursive)- ↓-Topological Sort- ↓-Deduplicate Files- ↓-Return: { files, dependencies, docs }-```-------## Configuration Schema--### `blocks.json` Structure--```typescript-{- aliases: {- workflows: string, // e.g., "packages/api/src/workflows"- api: string, // e.g., "packages/api/src/api"- links: string, // e.g., "packages/api/src/links"- modules: string, // e.g., "packages/api/src/modules"- vendor: string, // e.g., "apps/vendor/src/pages"- admin: string, // e.g., "apps/admin/src/pages"- lib: string // e.g., "packages/api/src/lib"- },- registries: {- "@mercurjs": "https://...",- "@custom": {- url: "https://...",- params: { /* query params */ },- headers: { "Authorization": "Bearer ${API_TOKEN}" }- }- }-}-```--### Built-in Registry--- **Name:** `@mercurjs`-- **URL:** GitHub raw content from `mercurjs/mercur` repository-------## Registry Item Schema--```typescript-{- name: string,- type: "registry:workflow" | "registry:api" | "registry:link" |- "registry:module" | "registry:vendor" | "registry:admin" | "registry:lib",- title?: string,- author?: string,- description?: string,- dependencies?: string[], // npm packages- devDependencies?: string[],- registryDependencies?: string[], // other registry items- files: [{- path: string,- content: string,- type: string,- target?: string // explicit target path- }],- docs?: string,- meta?: Record<string, any>-}-```-------## Utility Functions--### Configuration (`src/utils/get-config.ts`)-- `getConfig()` - Load and validate `blocks.json`-- `resolveConfigPaths()` - Resolve aliases via tsconfig-paths-- `createConfig()` - Create config with defaults--### File Operations (`src/utils/update-files.ts`)-- `updateFiles()` - Create/update project files-- Handles conflicts with user prompts-- Returns arrays: created, updated, skipped, declined--### Import Transformation (`src/utils/transform-import.ts`)-- `transformImports()` - Transform imports using ts-morph-- Maps standard aliases to configured paths-- Only processes `.ts` and `.tsx` files--### Dependencies (`src/utils/update-dependencies.ts`)-- `updateDependencies()` - Install npm packages-- Supports: npm, yarn, pnpm, bun, deno-- Auto-detects package manager--### Database (`src/utils/create-db.ts`)-- `setupDatabase()` - Create PostgreSQL database-- `runMigrations()` - Execute migrations-- `seedDatabase()` - Run seed scripts-------## Key Dependencies--| Package | Purpose |-|---------|---------|-| `commander` | CLI framework |-| `zod` | Schema validation |-| `ts-morph` | TypeScript AST manipulation |-| `tsconfig-paths` | Path alias resolution |-| `cosmiconfig` | Configuration loading |-| `prompts` | Interactive CLI prompts |-| `ora` | Spinner/progress UI |-| `kleur` | Terminal colors |-| `execa` | Command execution |-| `pg` | PostgreSQL client |-| `tar` | Archive extraction |-| `diff` | File comparison |-| `@antfu/ni` | Package manager detection |-------## Error Handling--### Custom Error Classes (`src/registry/errors.ts`)--| Error Code | Description |-|------------|-------------|-| `NotFound` | Registry item not found (404) |-| `Unauthorized` | Authentication required (401) |-| `Forbidden` | Access denied (403) |-| `FetchError` | Network/HTTP error |-| `NotConfigured` | Registry not configured |-| `LocalFileError` | Local file read error |-| `ParseError` | JSON parse error |-| `MissingEnvironmentVariables` | Required env vars not set |-| `InvalidNamespace` | Invalid registry namespace |-| `ConfigMissingError` | blocks.json not found |-| `ConfigParseError` | Invalid blocks.json |--Each error includes:-- Error code and status-- Context information-- Actionable suggestion-------## Architecture Patterns--### Command Pattern-Each command is a standalone Commander command with:-- Input validation (Zod)-- Preflight checks-- Configuration loading-- Error handling with suggestions--### Configuration-Driven-- All behavior driven by `blocks.json`-- Support for multiple registries-- Environment variable expansion--### Recursive Resolution-- Files reference other files via imports-- Registry items reference other items-- Both resolved recursively with cycle detection--### Transformation Pipeline-```-Raw Registry Item → Transform Imports → Write to Disk-```-------## Development Notes--### Running Locally-```bash-bun src/index.ts --help-bun src/index.ts add <block-name>-bun src/index.ts create my-project-```--### Building Registry-```bash-bun src/index.ts build ./registry.json -o ./dist-```--### Type Checking-```bash-bun run typecheck-```\ No newline at end of filediff --git a/packages/cli/README.md b/packages/cli/README.mdindex 40501bd37..9b627745c 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -283,7 +283,7 @@ mercurjs build [registry] [options]| Option | Description | Default || --------------------- | ------------------------------------ | ----------------- |-| `-o, --output <path>` | Destination directory for JSON files | `./registry` |+| `-o, --output <path>` | Destination directory for JSON files | `./r` || `-c, --cwd <path>` | Working directory | Current directory || `-v, --verbose` | Verbose output | `false` |diff --git a/packages/cli/src/commands/create.ts b/packages/cli/src/commands/create.tsindex b4cf8bad6..66504fdab 100644--- a/packages/cli/src/commands/create.ts+++ b/packages/cli/src/commands/create.ts@@ -30,7 +30,7 @@ const CREATE_TEMPLATES = {export const create = new Command().name("create")- .description("create a new project with shadcn/ui")+ .description("create a new Mercur project").argument("[name]", "the name of your project").option("-t, --template <template>",diff --git a/templates/basic/README.md b/templates/basic/README.mdindex c23e95a24..55e3d5d82 100644--- a/templates/basic/README.md+++ b/templates/basic/README.md@@ -1,135 +1,139 @@-# Turborepo starter+# Mercur Basic Template-This Turborepo starter is maintained by the Turborepo core team.+This template comes configured with the bare minimum to get started building your marketplace with Mercur.-## Using this example+## Quick Start-Run the following command:+To spin up this template locally, follow these steps:-```sh-npx create-turbo@latest-```--## What's inside?+### Clone-This Turborepo includes the following packages/apps:+If you've already cloned this repo, skip to [Development](#development).-### Apps and Packages+### Development-- `docs`: a [Next.js](https://nextjs.org/) app-- `web`: another [Next.js](https://nextjs.org/) app-- `@repo/ui`: a stub React component library shared by both `web` and `docs` applications-- `@repo/eslint-config`: `eslint` configurations (includes `eslint-config-next` and `eslint-config-prettier`)-- `@repo/typescript-config`: `tsconfig.json`s used throughout the monorepo+1. First [clone the repo](#clone) if you have not done so already-Each package/app is 100% [TypeScript](https://www.typescriptlang.org/).+2. Copy the example environment variables:-### Utilities--This Turborepo has some additional tools already setup for you:+```bash+cd my-project+cp packages/api/.env.template packages/api/.env+```-- [TypeScript](https://www.typescriptlang.org/) for static type checking-- [ESLint](https://eslint.org/) for code linting-- [Prettier](https://prettier.io) for code formatting+3. Update the `.env` file with your database connection string and other required variables:-### Build+```+DATABASE_URL=postgres://user:password@localhost:5432/mercur+REDIS_URL=redis://localhost:6379+JWT_SECRET=your-super-secret-jwt-key+COOKIE_SECRET=your-super-secret-cookie-key+```-To build all apps and packages, run the following command:+4. Install dependencies and start the dev server:+```bash+npm install+npm run dev```-cd my-turborepo-# With [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation) installed (recommended)-turbo build+5. Open `http://localhost:9000` to access the Medusa backend+6. Open `http://localhost:7000` to access the admin dashboard+6. Open `http://localhost:7001` to access the vendor dashboard-# Without [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation), use your package manager-npx turbo build-yarn dlx turbo build-pnpm exec turbo build-```+That's it! Follow the on-screen instructions to login and create your first admin user.-You can build a specific package by using a [filter](https://turborepo.dev/docs/crafting-your-repository/running-tasks#using-filters):+## What's Inside-```-# With [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation) installed (recommended)-turbo build --filter=docs+This monorepo includes the following packages and apps:-# Without [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation), use your package manager-npx turbo build --filter=docs-yarn exec turbo build --filter=docs-pnpm exec turbo build --filter=docs-```+### Apps and Packages-### Develop+- `packages/api` - The Medusa backend with all marketplace functionality+- `apps/admin` - Admin dashboard customizations+- `apps/vendor` - Vendor portal customizations-To develop all apps and packages, run the following command:+### Project Structure```-cd my-turborepo+├── apps/+│ ├── admin/ # Admin dashboard extensions+│ └── vendor/ # Vendor portal extensions+├── packages/+│ └── api/ # Medusa backend+│ ├── src/+│ │ ├── admin/ # Admin UI extensions+│ │ ├── api/ # Custom API routes+│ │ ├── jobs/ # Background jobs+│ │ ├── links/ # Module links+│ │ ├── modules/ # Custom modules+│ │ ├── scripts/ # CLI scripts+│ │ ├── subscribers/ # Event subscribers+│ │ └── workflows/ # Business workflows+│ └── medusa-config.ts+├── blocks.json # Mercur blocks configuration+├── package.json+└── turbo.json+```-# With [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation) installed (recommended)-turbo dev+### Utilities-# Without [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation), use your package manager-npx turbo dev-yarn exec turbo dev-pnpm exec turbo dev-```+This project has some additional tools already setup for you:-You can develop a specific package by using a [filter](https://turborepo.dev/docs/crafting-your-repository/running-tasks#using-filters):+- [TypeScript](https://www.typescriptlang.org/) for static type checking+- [Turborepo](https://turborepo.dev/) for monorepo management+- [Prettier](https://prettier.io) for code formatting-```-# With [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation) installed (recommended)-turbo dev --filter=web+## How It Works-# Without [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation), use your package manager-npx turbo dev --filter=web-yarn exec turbo dev --filter=web-pnpm exec turbo dev --filter=web-```+The Mercur basic template is built on top of [Medusa](https://medusajs.com) and is pre-configured for marketplace functionality.-### Remote Caching+### Modules-> [!TIP]-> Vercel Remote Cache is free for all plans. Get started today at [vercel.com](https://vercel.com/signup?/signup?utm_source=remote-cache-sdk&utm_campaign=free_remote_cache).+Custom modules allow you to extend the core functionality. See the [Modules](https://docs.medusajs.com/learn/fundamentals/modules) docs for details.-Turborepo can use a technique known as [Remote Caching](https://turborepo.dev/docs/core-concepts/remote-caching) to share cache artifacts across machines, enabling you to share build caches with your team and CI/CD pipelines.+### Workflows-By default, Turborepo will cache locally. To enable Remote Caching you will need an account with Vercel. If you don't have an account you can [create one](https://vercel.com/signup?utm_source=turborepo-examples), then enter the following commands:+Workflows define multi-step business processes. See the [Workflows](https://docs.medusajs.com/learn/fundamentals/workflows) docs for details.-```-cd my-turborepo+### API Routes-# With [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation) installed (recommended)-turbo login+Custom API routes expose HTTP endpoints. See the [API Routes](https://docs.medusajs.com/learn/fundamentals/api-routes) docs for details.-# Without [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation), use your package manager-npx turbo login-yarn exec turbo login-pnpm exec turbo login-```+### Links++Links define relationships between modules. See the [Links](https://docs.medusajs.com/learn/fundamentals/links) docs for details.-This will authenticate the Turborepo CLI with your [Vercel account](https://vercel.com/docs/concepts/personal-accounts/overview).+## Adding Blocks-Next, you can link your Turborepo to your Remote Cache by running the following command from the root of your Turborepo:+You can extend your project with pre-built blocks using the Mercur CLI:+```bash+npx @mercurjs/cli add block-name```-# With [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation) installed (recommended)-turbo link-# Without [global `turbo`](https://turborepo.dev/docs/getting-started/installation#global-installation), use your package manager-npx turbo link-yarn exec turbo link-pnpm exec turbo link+Configure your block sources in `blocks.json`:++```json+{+ "aliases": {+ "workflows": "packages/api/src/workflows",+ "links": "packages/api/src/links",+ "api": "packages/api/src/api",+ "modules": "packages/api/src/modules"+ },+ "registries": {}+}```-## Useful Links+## Build++To build all apps and packages:++```bash+npm run build+```-Learn more about the power of Turborepo:+## Questions-- [Tasks](https://turborepo.dev/docs/crafting-your-repository/running-tasks)-- [Caching](https://turborepo.dev/docs/crafting-your-repository/caching)-- [Remote Caching](https://turborepo.dev/docs/core-concepts/remote-caching)-- [Filtering](https://turborepo.dev/docs/crafting-your-repository/running-tasks#using-filters)-- [Configuration Options](https://turborepo.dev/docs/reference/configuration)-- [CLI Usage](https://turborepo.dev/docs/reference/command-line-reference)+If you have any issues or questions start a [GitHub discussion](https://github.com/mercurjs/mercur/discussions).diff --git a/templates/registry/.gitignore b/templates/registry/.gitignorenew file mode 100644index 000000000..578fcf980--- /dev/null+++ b/templates/registry/.gitignore@@ -0,0 +1,3 @@+node_modules+dist+.turbodiff --git a/templates/registry/README.md b/templates/registry/README.mdnew file mode 100644index 000000000..2bcd0e7a7--- /dev/null+++ b/templates/registry/README.md@@ -0,0 +1,278 @@+# Mercur Registry Template++A template repo to create a [Mercur](https://mercurjs.com) registry with reusable blocks.++Mercur is built with a robust infrastructure intended to support Blocks with ease. This provides a simple, modular, and reusable way for developers to extend the core capabilities of Mercur.++To build your own Mercur blocks, all you need is:++- An understanding of the basic Medusa/Mercur concepts+- And some JavaScript/Typescript experience++## Background++Here is a short recap on how blocks work with Mercur, to learn more visit the [Mercur documentation](https://docs.mercurjs.com).++### How to install a block++To install any block, simply use the Mercur CLI:++```bash+npx @mercurjs/cli add block-name+```++### Block Types++Blocks can contain various types of resources:++- **Modules** - Custom business logic and data models+- **Links** - Relationships between modules+- **Workflows** - Multi-step business processes+- **API Routes** - Custom HTTP endpoints+- **Admin Extensions** - Dashboard customizations+- **Vendor Extensions** - Vendor portal customizations++## Building Blocks++When you build a block, you are purely building a feature for your project and then abstracting it outside of the project.++### Template Files++In this template, you will see a common file structure that is used across all registries:++1. root folder+2. /src folder++#### Root++In the root folder, you will see various files that relate to the configuration of the registry:++- **README.md**\* - This contains instructions on how to use the template. When you are ready, update this to contain instructions on how to use your blocks.+- **package.json**\* - Contains necessary scripts and dependencies. Overwrite the metadata in this file to describe your registry.+- **registry.json**\* - Defines all blocks, their files, dependencies, and documentation.+- **blocks.json** - Configures path aliases for block resources.+- **tsconfig.json** - Configures the compiler options for TypeScript.+- **.gitignore** - List specific untracked files to omit from Git.++**IMPORTANT\***: You will need to modify these files.++#### Src++The src folder contains your blocks. Each block should be in its own directory:++```+src/+├── block-1/+│ ├── modules/+│ ├── links/+│ ├── api/+│ └── workflows/+└── block-2/+ ├── modules/+ ├── links/+ ├── api/+ └── workflows/+```++##### Modules++Modules define your data models and business logic:++```ts+// modules/sample/models/sample.ts+import { model } from "@medusajs/framework/utils"++const Sample = model.define("sample", {+ id: model.id().primaryKey(),+ name: model.text(),+})++export default Sample+```++```ts+// modules/sample/service.ts+import { MedusaService } from "@medusajs/framework/utils"+import Sample from "./models/sample"++class SampleModuleService extends MedusaService({+ Sample,+}) {}++export default SampleModuleService+```++```ts+// modules/sample/index.ts+import { Module } from "@medusajs/framework/utils"+import SampleModuleService from "./service"++export const SAMPLE_MODULE = "sample"++export default Module(SAMPLE_MODULE, {+ service: SampleModuleService,+})+```++##### Links++Links define relationships between modules:++```ts+// links/product-sample.ts+import { defineLink } from "@medusajs/framework/utils"+import ProductModule from "@medusajs/medusa/product"+import SampleModule from "../modules/sample"++export default defineLink(+ ProductModule.linkable.product,+ SampleModule.linkable.sample+)+```++##### Workflows++Workflows define multi-step business processes:++```ts+// workflows/hello-world/hello-world.ts+import {+ createStep,+ createWorkflow,+ WorkflowResponse,+ StepResponse,+} from "@medusajs/framework/workflows-sdk"++const step1 = createStep("step-1", async () => {+ return new StepResponse(`Hello from step one!`)+})++type WorkflowInput = {+ name: string+}++const step2 = createStep(+ "step-2",+ async ({ name }: WorkflowInput) => {+ return new StepResponse(`Hello ${name} from step two!`)+ }+)++const helloWorldWorkflow = createWorkflow(+ "hello-world",+ (input: WorkflowInput) => {+ const greeting1 = step1()+ const greeting2 = step2(input)++ return new WorkflowResponse({+ message1: greeting1,+ message2: greeting2,+ })+ }+)++export default helloWorldWorkflow+```++##### API Routes++API routes expose HTTP endpoints:++```ts+// api/hello/workflow/route.ts+import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"+import helloWorldWorkflow from "../../../workflows/hello-world/hello-world"++export const GET = async (req: MedusaRequest, res: MedusaResponse) => {+ const { result } = await helloWorldWorkflow(req.scope).run({+ input: {+ name: (req.query.name as string) || "World",+ },+ })++ res.json(result)+}+```++### Registry Configuration++The `registry.json` file defines your blocks:++```json+{+ "$schema": "https://raw.githubusercontent.com/mercurjs/mercur/new/packages/registry/public/schema/registry.json",+ "name": "@your-org",+ "homepage": "https://your-site.com",+ "items": [+ {+ "name": "my-block",+ "description": "A description of what this block does.",+ "dependencies": [],+ "registryDependencies": [],+ "docs": "## Configuration\n\nAdd documentation here...",+ "files": [+ {+ "path": "my-block/modules/sample/index.ts",+ "type": "registry:module"+ }+ ],+ "categories": ["sample"]+ }+ ]+}+```++#### Block Properties++- **name** - Unique identifier for the block+- **description** - Brief description of the block's purpose+- **dependencies** - NPM packages required by the block+- **registryDependencies** - Other blocks this block depends on+- **docs** - Markdown documentation shown during installation+- **files** - List of files included in the block+- **categories** - Tags for categorizing the block++#### File Types++- `registry:module` - Module files+- `registry:link` - Link definitions+- `registry:workflow` - Workflow files+- `registry:api` - API route files+- `registry:admin` - Admin extensions+- `registry:vendor` - Vendor extensions++## Development++1. Install dependencies:++```bash+npm install+```++2. Build TypeScript:++```bash+npm run build+```++3. Build registry:++```bash+npm run build:registry+```++## Best Practices++Here are best practices we follow when building blocks:++- **Keep blocks focused**: Each block should serve a single, well-defined purpose. This makes them easier to understand and maintain.+- **Document thoroughly**: Include clear documentation in the `docs` field explaining configuration, environment variables, and usage.+- **Declare dependencies**: Always list required NPM packages in `dependencies` and other blocks in `registryDependencies`.+- **Use meaningful names**: Choose descriptive names for blocks, modules, and files that clearly indicate their purpose.+- **Test your blocks**: Ensure blocks work correctly before publishing by testing them in a real Mercur project.+- **Version compatibility**: Document which versions of Medusa/Mercur your blocks are compatible with.+- **Publish to NPM**: Share your registry by publishing it as an NPM package for others to use.++## Questions++Please contact [Mercur](mailto:[email protected]) with any questions about using this registry template.diff --git a/templates/registry/blocks.json b/templates/registry/blocks.jsonnew file mode 100644index 000000000..005fca7b0--- /dev/null+++ b/templates/registry/blocks.json@@ -0,0 +1,13 @@+{+ "$schema": "https://raw.githubusercontent.com/mercurjs/mercur/new/packages/registry/schema/registry.json",+ "aliases": {+ "workflows": "@/workflows",+ "api": "@/api",+ "links": "@/links",+ "modules": "@/modules",+ "vendor": "@/vendor",+ "admin": "@/admin",+ "lib": "@/lib"+ },+ "registries": {}+}diff --git a/templates/registry/package.json b/templates/registry/package.jsonnew file mode 100644index 000000000..5636b1e6c--- /dev/null+++ b/templates/registry/package.json@@ -0,0 +1,21 @@+{+ "name": "@mercurjs/registry",+ "version": "0.0.0",+ "private": true,+ "type": "module",+ "scripts": {+ "build": "tsc",+ "dev": "tsc --watch",+ "build:registry": "mercurjs build"+ },+ "dependencies": {},+ "devDependencies": {+ "@mercurjs/cli": "*",+ "@types/node": "^22",+ "@types/unzipper": "^0.10.10",+ "@medusajs/admin-sdk": "2.12.5",+ "@medusajs/cli": "2.12.5",+ "@medusajs/framework": "2.12.5",+ "@medusajs/medusa": "2.12.5"+ }+}diff --git a/templates/registry/registry.json b/templates/registry/registry.jsonnew file mode 100644index 000000000..a4106e4ef--- /dev/null+++ b/templates/registry/registry.json@@ -0,0 +1,39 @@+{+ "$schema": "https://raw.githubusercontent.com/mercurjs/mercur/new/packages/registry/public/schema/registry.json",+ "name": "@mercurjs",+ "homepage": "https://mercurjs.com",+ "items": [+ {+ "name": "block-1",+ "description": "A block with a test module, product-test link, and API route.",+ "dependencies": [],+ "registryDependencies": [],+ "docs": "## Test Block Configuration\n\nAdd the test module to your `medusa-config.ts`:\n\n```ts\nmodules: [\n {\n resolve: './modules/test',\n options: {\n apiKey: process.env.TEST_API_KEY,\n },\n },\n]\n```\n\n## Environment Variables\n\nAdd the following to your `.env` file:\n\n```\nTEST_API_KEY=your-api-key\n```",+ "files": [+ {+ "path": "block-1/modules/test/index.ts",+ "type": "registry:module"+ },+ {+ "path": "block-1/modules/test/service.ts",+ "type": "registry:module"+ },+ {+ "path": "block-1/modules/test/models/test.ts",+ "type": "registry:module"+ },+ {+ "path": "block-1/links/product-test.ts",+ "type": "registry:link"+ },+ {+ "path": "block-1/api/hello/test/route.ts",+ "type": "registry:api"+ }+ ],+ "categories": [+ "test"+ ]+ }+ ]+}diff --git a/templates/registry/src/README.md b/templates/registry/src/README.mdnew file mode 100644index 000000000..8b67377c8--- /dev/null+++ b/templates/registry/src/README.md@@ -0,0 +1,46 @@+# Registry Source Files++This directory contains the source files for your registry blocks. Each block should be organized in its own directory.++> Learn more about building blocks in the [Mercur documentation](https://docs.mercurjs.com).++## Block Structure++Each block directory should follow this structure:++```+src/+└── my-block/+ ├── modules/ # Custom modules with data models and services+ ├── links/ # Module link definitions+ ├── workflows/ # Business workflow definitions+ └── api/ # Custom API route handlers+```++## Creating a New Block++1. Create a new directory under `src/` with your block name+2. Add the necessary subdirectories for your block's functionality+3. Register your block in `registry.json`++## Block Components++### Modules++Modules contain your data models and business logic. Each module should have:++- `models/` - Data model definitions+- `service.ts` - Service class with business methods+- `index.ts` - Module export and registration++### Links++Links define relationships between modules from different packages.++### Workflows++Workflows define multi-step business processes with compensation logic.++### API Routes++API routes expose HTTP endpoints for your block's functionality.diff --git a/templates/registry/src/block-1/api/hello/test/route.ts b/templates/registry/src/block-1/api/hello/test/route.tsnew file mode 100644index 000000000..bae609f28--- /dev/null+++ b/templates/registry/src/block-1/api/hello/test/route.ts@@ -0,0 +1,8 @@+import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";++export const POST = async (req: MedusaRequest, res: MedusaResponse) => {+ res.json({+ test: true,+ test2: false,+ })+}\ No newline at end of filediff --git a/templates/registry/src/block-1/links/product-test.ts b/templates/registry/src/block-1/links/product-test.tsnew file mode 100644index 000000000..b7ffaff4e--- /dev/null+++ b/templates/registry/src/block-1/links/product-test.ts@@ -0,0 +1,8 @@+import { defineLink } from "@medusajs/framework/utils"+import ProductModule from "@medusajs/medusa/product"+import TestModule from "../modules/test"++export default defineLink(+ ProductModule.linkable.product,+ TestModule.linkable.test+)diff --git a/templates/registry/src/block-1/modules/test/index.ts b/templates/registry/src/block-1/modules/test/index.tsnew file mode 100644index 000000000..1ca696756--- /dev/null+++ b/templates/registry/src/block-1/modules/test/index.ts@@ -0,0 +1,10 @@+import { Module } from "@medusajs/framework/utils"+import TestModuleService from "./service"++export const TEST_MODULE = "test"++export default Module(TEST_MODULE, {+ service: TestModuleService,+})++diff --git a/templates/registry/src/block-1/modules/test/models/test.ts b/templates/registry/src/block-1/modules/test/models/test.tsnew file mode 100644index 000000000..3efe4f619--- /dev/null+++ b/templates/registry/src/block-1/modules/test/models/test.ts@@ -0,0 +1,8 @@+import { model } from "@medusajs/framework/utils"++const Test = model.define("test", {+ id: model.id().primaryKey(),+ name: model.text(),+})++export default Testdiff --git a/templates/registry/src/block-1/modules/test/service.ts b/templates/registry/src/block-1/modules/test/service.tsnew file mode 100644index 000000000..05f4ec5a9--- /dev/null+++ b/templates/registry/src/block-1/modules/test/service.ts@@ -0,0 +1,8 @@+import { MedusaService } from "@medusajs/framework/utils"+import Test from "./models/test"++class TestModuleService extends MedusaService({+ Test,+}) {}++export default TestModuleServicediff --git a/templates/registry/tsconfig.json b/templates/registry/tsconfig.jsonnew file mode 100644index 000000000..16803dc9c--- /dev/null+++ b/templates/registry/tsconfig.json@@ -0,0 +1,32 @@+{+ "compilerOptions": {+ "lib": ["ESNext"],+ "types": ["node"],+ "target": "ESNext",+ "module": "Preserve",+ "moduleDetection": "force",+ "moduleResolution": "bundler",+ "noEmit": false,+ "emitDeclarationOnly": false,+ "strict": true,+ "noFallthroughCasesInSwitch": true,+ "noUncheckedIndexedAccess": true,+ "noImplicitOverride": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "declaration": true,+ "outDir": "./dist",+ "preserveWatchOutput": true,+ "baseUrl": ".",+ "paths": {+ "@/workflows/*": ["./src/workflows/*"],+ "@/api/*": ["./src/api/*"],+ "@/links/*": ["./src/links/*"],+ "@/modules/*": ["./src/modules/*"],+ "@/vendor/*": ["./src/vendor/*"],+ "@/admin/*": ["./src/admin/*"],+ "@/lib/*": ["./src/lib/*"]+ }+ },+ "include": ["src/**/*"]+}