|
1
|
# Medusa Core |
|
2
|
|
|
3
|
Open-source commerce platform. TypeScript monorepo with 35+ modular commerce packages. |
|
4
|
|
|
5
|
> When working on the API reference documentation (`www/apps/api-reference`), read [`www/apps/api-reference/CLAUDE.md`](www/apps/api-reference/CLAUDE.md) for its path structure and the OAS → public docs flow. |
|
6
|
|
|
7
|
> When working on the resources documentation (`www/apps/resources`), read [`www/apps/resources/CLAUDE.md`](www/apps/resources/CLAUDE.md) for details on references and how they're generated and built |
|
8
|
|
|
9
|
> When working on the main documentation (`www/apps/book`), read [`www/apps/book/CLAUDE.md`](www/apps/book/CLAUDE.md) for the homepage structure and the What's New list that must be updated whenever a new feature, release, or notable guide ships. |
|
10
|
|
|
11
|
### 1. Codebase Structure |
|
12
|
|
|
13
|
**Monorepo Organization:** |
|
14
|
|
|
15
|
``` |
|
16
|
/packages/ |
|
17
|
├── medusa/ # Main Medusa package |
|
18
|
├── core/ # Core framework packages |
|
19
|
│ ├── framework/ # Core runtime |
|
20
|
│ ├── types/ # TypeScript definitions |
|
21
|
│ ├── utils/ # Utilities |
|
22
|
│ ├── workflows-sdk/ # Workflow composition |
|
23
|
│ ├── core-flows/ # Predefined workflows |
|
24
|
│ └── modules-sdk/ # Module development |
|
25
|
├── modules/ # 35+ commerce modules |
|
26
|
│ ├── product/, order/, cart/, payment/... |
|
27
|
│ └── providers/ # 16 provider implementations |
|
28
|
├── admin/ # Dashboard packages |
|
29
|
│ └── dashboard/ # React admin UI |
|
30
|
├── cli/ # CLI tools |
|
31
|
├── plugins/ # Official plugins |
|
32
|
└── design-system/ # UI components |
|
33
|
/integration-tests/ # Full-stack tests |
|
34
|
/www/ # Documentation site |
|
35
|
``` |
|
36
|
|
|
37
|
**Key Directories:** |
|
38
|
|
|
39
|
- `packages/core/framework/` - Core runtime, HTTP, database |
|
40
|
- `packages/medusa/src/api/` - API routes |
|
41
|
- `packages/modules/` - Commerce feature modules |
|
42
|
- `packages/admin/dashboard/` - Admin React app |
|
43
|
|
|
44
|
### 2. Build System & Commands |
|
45
|
|
|
46
|
**Package Manager**: Yarn 3.2.1 with node-modules linker |
|
47
|
|
|
48
|
**Essential Commands:** |
|
49
|
|
|
50
|
```bash |
|
51
|
# Install dependencies |
|
52
|
yarn install |
|
53
|
# Build all packages |
|
54
|
yarn build |
|
55
|
# Build specific package |
|
56
|
yarn workspace @medusajs/medusa build |
|
57
|
# Watch mode (in package directory) |
|
58
|
yarn watch |
|
59
|
``` |
|
60
|
|
|
61
|
**Testing Commands:** |
|
62
|
|
|
63
|
```bash |
|
64
|
# All unit tests |
|
65
|
yarn test |
|
66
|
# Package integration tests |
|
67
|
yarn test:integration:packages |
|
68
|
# HTTP integration tests |
|
69
|
yarn test:integration:http |
|
70
|
# Module integration tests |
|
71
|
yarn test:integration:modules |
|
72
|
``` |
|
73
|
|
|
74
|
**Migrations:** |
|
75
|
|
|
76
|
Whenever you create, modify, or delete a data model file inside a module (under `packages/modules`), generate the migration by running the module package's migration script from within that package — NEVER write migration files by hand: |
|
77
|
|
|
78
|
```bash |
|
79
|
cd packages/modules/<module> && yarn migration:create |
|
80
|
``` |
|
81
|
|
|
82
|
NEVER edit the migration file by hand. If new changes land in the model, re run the script. |
|
83
|
|
|
84
|
**Generated Files:** |
|
85
|
|
|
86
|
After adding or removing keys in `packages/admin/dashboard/src/i18n/translations/en.json`, regenerate the JSON schema that validates all translation files: |
|
87
|
|
|
88
|
```bash |
|
89
|
cd packages/admin/dashboard && yarn i18n:schema |
|
90
|
``` |
|
91
|
|
|
92
|
Skipping this leaves `Property <key> is not allowed` warnings on `en.json`, since `translations/$schema.json` is generated from `en.json` and lists every key in both `properties` and `required`. Commit the regenerated `$schema.json` with the translation change. |
|
93
|
|
|
94
|
**Changesets:** |
|
95
|
|
|
96
|
Every change to a published package needs a changeset. Generate it from the repo root with `yarn changeset`. If you can't answer the interactive prompts, write the equivalent file directly in `.changeset/<kebab-case-name>.md`: |
|
97
|
|
|
98
|
```md |
|
99
|
--- |
|
100
|
"@medusajs/workflow-engine-redis": patch |
|
101
|
--- |
|
102
|
|
|
103
|
fix(workflow-engine-redis): short description of the change |
|
104
|
``` |
|
105
|
|
|
106
|
- `patch`: non-breaking changes (fixes, features, refactors) |
|
107
|
- `minor`: breaking changes |
|
108
|
- NEVER use `major` |
|
109
|
|
|
110
|
### 3. Testing Conventions |
|
111
|
|
|
112
|
**Frameworks:** |
|
113
|
|
|
114
|
- Jest 29.7.0 (backend/core) |
|
115
|
- Vitest 4.1.10 (admin/frontend) |
|
116
|
|
|
117
|
**Test Locations:** |
|
118
|
|
|
119
|
- Unit tests: `__tests__/` directories alongside source |
|
120
|
- Package integration tests: `packages/*/integration-tests/__tests__/` |
|
121
|
- HTTP integration tests: `integration-tests/http/__tests__/` |
|
122
|
|
|
123
|
**Patterns:** |
|
124
|
|
|
125
|
- File extension: `.spec.ts` or `.test.ts` |
|
126
|
- Unit test structure: `describe/it` blocks |
|
127
|
- Integration tests: Use custom test runners with DB setup |
|
128
|
|
|
129
|
### 4. Code Style Conventions |
|
130
|
|
|
131
|
**Formatting (Prettier):** |
|
132
|
|
|
133
|
- No semicolons |
|
134
|
- Double quotes |
|
135
|
- 2 space indentation |
|
136
|
- ES5 trailing commas |
|
137
|
- Always use parens in arrow functions |
|
138
|
|
|
139
|
**TypeScript:** |
|
140
|
|
|
141
|
- Target: ES2021 |
|
142
|
- Module: Node16 |
|
143
|
- Strict null checks enabled |
|
144
|
- Decorators enabled (experimental) |
|
145
|
|
|
146
|
**Naming Conventions:** |
|
147
|
|
|
148
|
- Files: kebab-case (`define-config.ts`) |
|
149
|
- Types/Interfaces/Classes: PascalCase |
|
150
|
- Functions/Variables: camelCase |
|
151
|
- Constants: SCREAMING_SNAKE_CASE |
|
152
|
- DB fields: snake_case |
|
153
|
|
|
154
|
**Branch Naming:** |
|
155
|
Branch names must be prefixed by type, since the prefix drives the labels automatically applied to the PR: |
|
156
|
|
|
157
|
- `feat/readable-name`: new features |
|
158
|
- `fix/readable-name`: bug fixes |
|
159
|
- `chore/readable-name`: refactors, clean-ups, and similar work |
|
160
|
- `docs/readable-name`: docs-only PRs |
|
161
|
|
|
162
|
`readable-name` must describe the PR's changes (kebab-case). Do NOT use just the ticket number (e.g. use `fix/loyalty-admin-auth-type`, not `dx-2801`). |
|
163
|
|
|
164
|
**Export Patterns:** |
|
165
|
|
|
166
|
- Barrel exports via `export * from` |
|
167
|
- Named re-exports for specific items |
|
168
|
|
|
169
|
**General Conventions:** |
|
170
|
|
|
171
|
- NEVER use emojos. |
|
172
|
|
|
173
|
### 5. Architecture Patterns |
|
174
|
|
|
175
|
#### 5.1 Module Pattern - Services with Decorators |
|
176
|
|
|
177
|
**Service Structure:** |
|
178
|
|
|
179
|
- Extend `MedusaService<T>` with typed model definitions |
|
180
|
- Inject dependencies via constructor |
|
181
|
- Use decorators for cross-cutting concerns |
|
182
|
|
|
183
|
**Key Decorators:** |
|
184
|
|
|
185
|
- `@InjectManager()` - Inject entity manager (use on public methods) |
|
186
|
- `@InjectTransactionManager()` - Inject transaction manager (use on protected methods) |
|
187
|
- `@MedusaContext()` - Inject shared context as parameter |
|
188
|
- `@EmitEvents()` - Emit domain events after operation |
|
189
|
|
|
190
|
**Example:** |
|
191
|
|
|
192
|
```typescript |
|
193
|
export class OrderModuleService |
|
194
|
extends MedusaService<{ Order: { dto: OrderDTO } }>({ Order }) |
|
195
|
implements IOrderModuleService |
|
196
|
{ |
|
197
|
@InjectManager() |
|
198
|
@EmitEvents() |
|
199
|
async deleteOrders( |
|
200
|
ids: string[], |
|
201
|
@MedusaContext() sharedContext: Context = {} |
|
202
|
) { |
|
203
|
return await this.deleteOrders_(ids, sharedContext) |
|
204
|
} |
|
205
|
|
|
206
|
@InjectTransactionManager() |
|
207
|
protected async deleteOrders_( |
|
208
|
ids: string[], |
|
209
|
@MedusaContext() sharedContext: Context = {} |
|
210
|
) { |
|
211
|
await this.orderService_.softDelete(ids, sharedContext) |
|
212
|
} |
|
213
|
} |
|
214
|
``` |
|
215
|
|
|
216
|
**Reference Files:** |
|
217
|
|
|
218
|
- `packages/modules/order/src/services/order-module-service.ts` |
|
219
|
- `packages/modules/api-key/src/services/api-key-module-service.ts` |
|
220
|
|
|
221
|
#### 5.2 API Route Pattern |
|
222
|
|
|
223
|
**Route Structure:** |
|
224
|
|
|
225
|
- Named exports for HTTP methods: `GET`, `POST`, `PUT`, `DELETE`, `PATCH` |
|
226
|
- Type request: `AuthenticatedMedusaRequest<T>` or `MedusaRequest<T>` |
|
227
|
- Type response: `MedusaResponse<T>` |
|
228
|
- Access dependencies from `req.scope` |
|
229
|
- Use workflows from `@medusajs/core-flows` |
|
230
|
|
|
231
|
**Example:** |
|
232
|
|
|
233
|
```typescript |
|
234
|
import { deleteOrderWorkflow } from "@medusajs/core-flows" |
|
235
|
import { HttpTypes } from "@medusajs/framework/types" |
|
236
|
import { |
|
237
|
AuthenticatedMedusaRequest, |
|
238
|
MedusaResponse, |
|
239
|
} from "@medusajs/framework/http" |
|
240
|
|
|
241
|
export const DELETE = async ( |
|
242
|
req: AuthenticatedMedusaRequest, |
|
243
|
res: MedusaResponse<HttpTypes.AdminOrderDeleteResponse> |
|
244
|
) => { |
|
245
|
const { id } = req.params |
|
246
|
|
|
247
|
await deleteOrderWorkflow(req.scope).run({ |
|
248
|
input: { id }, |
|
249
|
}) |
|
250
|
|
|
251
|
res.status(200).json({ |
|
252
|
id, |
|
253
|
object: "order", |
|
254
|
deleted: true, |
|
255
|
}) |
|
256
|
} |
|
257
|
``` |
|
258
|
|
|
259
|
**Common Patterns:** |
|
260
|
|
|
261
|
- Filters: `req.filterableFields` |
|
262
|
- Pagination: `req.queryConfig.pagination` |
|
263
|
- Fields: `req.queryConfig.fields` |
|
264
|
- Resolve services: `req.scope.resolve(ContainerRegistrationKeys.QUERY)` |
|
265
|
|
|
266
|
**Store Routes - Allowed Fields:** |
|
267
|
|
|
268
|
Store routes are public, so every store route that returns data MUST define an explicit `allowed` list in its query config. Without it, a client can request any field or relation through `?fields=` and read data it shouldn't see. |
|
269
|
|
|
270
|
- Define `defaults` and `allowed` in the route's `query-config.ts` |
|
271
|
- Build `allowed` with `buildAllowedFields()` / `prefixAllowedFields()` from `packages/medusa/src/api/store/utils/allowed-fields.ts` |
|
272
|
- Only allow fields safe to expose publicly; list nested relation fields explicitly (e.g. `countries.iso_2`), not whole relations |
|
273
|
- Pass the config to `validateAndTransformQuery()` in the route's `middlewares.ts` |
|
274
|
|
|
275
|
```typescript |
|
276
|
export const retrieveTransformQueryConfig = { |
|
277
|
defaults: defaultStoreRegionFields, |
|
278
|
allowed: buildAllowedFields( |
|
279
|
defaultStoreRegionFields, |
|
280
|
nestedStoreRegionCountryFields |
|
281
|
), |
|
282
|
isList: false, |
|
283
|
} |
|
284
|
``` |
|
285
|
|
|
286
|
**Reference Files:** |
|
287
|
|
|
288
|
- `packages/medusa/src/api/admin/orders/route.ts` |
|
289
|
- `packages/medusa/src/api/admin/payment-collections/[id]/route.ts` |
|
290
|
- `packages/medusa/src/api/store/regions/query-config.ts` (store allowed fields) |
|
291
|
|
|
292
|
#### 5.3 Workflow Pattern |
|
293
|
|
|
294
|
**Step Definition:** |
|
295
|
|
|
296
|
- Create steps with `createStep(id, mainAction, compensationAction?)` |
|
297
|
- Return `StepResponse(result, compensationData)` |
|
298
|
- Compensation function handles rollback |
|
299
|
|
|
300
|
**Workflow Composition:** |
|
301
|
|
|
302
|
- Create workflows with `createWorkflow(id, function)` |
|
303
|
- Use `WorkflowData<T>` for typed input |
|
304
|
- Return `WorkflowResponse<T>` for typed output |
|
305
|
- Chain steps, use `transform()`, `when()`, `parallelize()` |
|
306
|
- Query data with `useQueryGraphStep()` |
|
307
|
- Emit events with `createHook()` |
|
308
|
|
|
309
|
**Example Step:** |
|
310
|
|
|
311
|
```typescript |
|
312
|
export const deletePromotionsStep = createStep( |
|
313
|
"delete-promotions", |
|
314
|
async (ids: string[], { container }) => { |
|
315
|
const promotionModule = container.resolve<IPromotionModuleService>( |
|
316
|
Modules.PROMOTION |
|
317
|
) |
|
318
|
await promotionModule.softDeletePromotions(ids) |
|
319
|
return new StepResponse(void 0, ids) |
|
320
|
}, |
|
321
|
async (idsToRestore, { container }) => { |
|
322
|
if (!idsToRestore?.length) return |
|
323
|
const promotionModule = container.resolve<IPromotionModuleService>( |
|
324
|
Modules.PROMOTION |
|
325
|
) |
|
326
|
await promotionModule.restorePromotions(idsToRestore) |
|
327
|
} |
|
328
|
) |
|
329
|
``` |
|
330
|
|
|
331
|
**Example Workflow:** |
|
332
|
|
|
333
|
```typescript |
|
334
|
export const deletePromotionsWorkflow = createWorkflow( |
|
335
|
"delete-promotions", |
|
336
|
(input: WorkflowData<{ ids: string[] }>) => { |
|
337
|
const deletedPromotions = deletePromotionsStep(input.ids) |
|
338
|
const promotionsDeleted = createHook("promotionsDeleted", { |
|
339
|
ids: input.ids, |
|
340
|
}) |
|
341
|
return new WorkflowResponse(deletedPromotions, { |
|
342
|
hooks: [promotionsDeleted], |
|
343
|
}) |
|
344
|
} |
|
345
|
) |
|
346
|
``` |
|
347
|
|
|
348
|
**Reference Files:** |
|
349
|
|
|
350
|
- `packages/core/core-flows/src/promotion/steps/delete-promotions.ts` |
|
351
|
- `packages/core/core-flows/src/promotion/workflows/delete-promotions.ts` |
|
352
|
- `packages/core/core-flows/src/order/workflows/update-order.ts` |
|
353
|
|
|
354
|
#### 5.4 Error Handling |
|
355
|
|
|
356
|
**MedusaError Pattern:** |
|
357
|
|
|
358
|
- Use `new MedusaError(type, message)` for all error throwing |
|
359
|
- Provide contextual, user-friendly error messages |
|
360
|
- Validate inputs early in services and workflow steps |
|
361
|
|
|
362
|
**Common Error Types:** |
|
363
|
|
|
364
|
- `MedusaError.Types.NOT_FOUND` - Resource not found |
|
365
|
- `MedusaError.Types.INVALID_DATA` - Invalid input or state |
|
366
|
- `MedusaError.Types.NOT_ALLOWED` - Operation not permitted |
|
367
|
|
|
368
|
**Example:** |
|
369
|
|
|
370
|
```typescript |
|
371
|
import { MedusaError, validateEmail } from "@medusajs/framework/utils" |
|
372
|
|
|
373
|
// In service |
|
374
|
if (!entity) { |
|
375
|
throw new MedusaError( |
|
376
|
MedusaError.Types.NOT_FOUND, |
|
377
|
`Order with id: ${id} was not found` |
|
378
|
) |
|
379
|
} |
|
380
|
|
|
381
|
// In workflow step |
|
382
|
if (input.email) { |
|
383
|
validateEmail(input.email) |
|
384
|
} |
|
385
|
|
|
386
|
if (order.status === "cancelled") { |
|
387
|
throw new MedusaError( |
|
388
|
MedusaError.Types.NOT_ALLOWED, |
|
389
|
"Cannot update a cancelled order" |
|
390
|
) |
|
391
|
} |
|
392
|
``` |
|
393
|
|
|
394
|
**Reference Files:** |
|
395
|
|
|
396
|
- `packages/core/utils/src/modules-sdk/medusa-internal-service.ts` |
|
397
|
- `packages/core/core-flows/src/order/workflows/update-order.ts` |
|
398
|
|
|
399
|
#### 5.5 Common Import Patterns |
|
400
|
|
|
401
|
**Path Aliases (configured in tsconfig.json):** |
|
402
|
|
|
403
|
- `@models` - Entity models |
|
404
|
- `@types` - DTO and type definitions |
|
405
|
- `@services` - Service dependencies |
|
406
|
- `@repositories` - Data access layer |
|
407
|
- `@utils` - Utility functions |
|
408
|
|
|
409
|
**Framework Imports:** |
|
410
|
|
|
411
|
```typescript |
|
412
|
// Utils and decorators |
|
413
|
import { |
|
414
|
InjectManager, |
|
415
|
InjectTransactionManager, |
|
416
|
MedusaContext, |
|
417
|
MedusaError, |
|
418
|
MedusaService, |
|
419
|
EmitEvents, |
|
420
|
Modules, |
|
421
|
} from "@medusajs/framework/utils" |
|
422
|
|
|
423
|
// Types |
|
424
|
import type { |
|
425
|
Context, |
|
426
|
DAL, |
|
427
|
IOrderModuleService, |
|
428
|
} from "@medusajs/framework/types" |
|
429
|
|
|
430
|
// Workflows |
|
431
|
import { |
|
432
|
WorkflowData, |
|
433
|
WorkflowResponse, |
|
434
|
createStep, |
|
435
|
createWorkflow, |
|
436
|
transform, |
|
437
|
} from "@medusajs/framework/workflows-sdk" |
|
438
|
|
|
439
|
// Core flows |
|
440
|
import { deleteOrderWorkflow } from "@medusajs/core-flows" |
|
441
|
|
|
442
|
// HTTP |
|
443
|
import { |
|
444
|
AuthenticatedMedusaRequest, |
|
445
|
MedusaResponse, |
|
446
|
} from "@medusajs/framework/http" |
|
447
|
``` |
|
448
|
|
|
449
|
### 6. GitHub Actions |
|
450
|
|
|
451
|
**Automation Token:** |
|
452
|
|
|
453
|
Any workflow that pushes branches, opens or updates PRs, comments, or labels MUST authenticate as the Medusa GitHub App. NEVER use a personal access token (e.g. `REFERENCE_PAT`) or the default `GITHUB_TOKEN` for these: the default token's pushes and PRs don't trigger CI. |
|
454
|
|
|
455
|
```yaml |
|
456
|
- name: Generate GitHub App token |
|
457
|
id: app-token |
|
458
|
uses: actions/create-github-app-token@v1 |
|
459
|
with: |
|
460
|
app-id: ${{ secrets.MEDUSA_APP_ID }} |
|
461
|
private-key: ${{ secrets.MEDUSA_APP_PRIVATE_KEY }} |
|
462
|
|
|
463
|
- uses: actions/checkout@v4 |
|
464
|
with: |
|
465
|
token: ${{ steps.app-token.outputs.token }} |
|
466
|
``` |
|
467
|
|
|
468
|
- Pass `${{ steps.app-token.outputs.token }}` as `GH_TOKEN` for `gh` calls and as `token` for `peter-evans/create-pull-request` |
|
469
|
- Reusable workflows take `MEDUSA_APP_ID` and `MEDUSA_APP_PRIVATE_KEY` as `workflow_call` secrets and generate the token themselves |
|
470
|
- In workflows that run Claude, keep the app token out of the job that runs the model: the model writes a result file, and a separate job validates it and pushes/opens the PR with the app token |
|
471
|
|
|
472
|
**Reference Files:** |
|
473
|
|
|
474
|
- `.github/workflows/fix-bug-action.yml` |
|
475
|
- `.github/workflows/triage-issue-action.yml` |