@joktec/skills 0.1.4 → 0.1.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/dist/claude/skills/advanced-typescript-design/SKILL.md +60 -0
- package/dist/claude/skills/advanced-typescript-design/agents/openai.yaml +4 -0
- package/dist/claude/skills/advanced-typescript-design/references/advanced.md +219 -0
- package/dist/claude/skills/advanced-typescript-design/references/simple.md +149 -0
- package/dist/claude/skills/joktec-mongo-skill/SKILL.md +9 -2
- package/dist/claude/skills/joktec-mongo-skill/references/repository.md +14 -11
- package/dist/claude/skills/joktec-mongo-skill/references/schema-and-plugins.md +43 -7
- package/dist/claude/skills/joktec-mysql-skill/SKILL.md +6 -2
- package/dist/claude/skills/joktec-mysql-skill/references/entities.md +82 -53
- package/dist/claude/skills/joktec-mysql-skill/references/repository.md +15 -1
- package/dist/claude/skills/joktec-tool-skill/references/tools.md +1 -0
- package/dist/codex/skills/advanced-typescript-design/SKILL.md +60 -0
- package/dist/codex/skills/advanced-typescript-design/agents/openai.yaml +4 -0
- package/dist/codex/skills/advanced-typescript-design/references/advanced.md +219 -0
- package/dist/codex/skills/advanced-typescript-design/references/simple.md +149 -0
- package/dist/codex/skills/joktec-mongo-skill/SKILL.md +9 -2
- package/dist/codex/skills/joktec-mongo-skill/references/repository.md +14 -11
- package/dist/codex/skills/joktec-mongo-skill/references/schema-and-plugins.md +43 -7
- package/dist/codex/skills/joktec-mysql-skill/SKILL.md +6 -2
- package/dist/codex/skills/joktec-mysql-skill/references/entities.md +82 -53
- package/dist/codex/skills/joktec-mysql-skill/references/repository.md +15 -1
- package/dist/codex/skills/joktec-tool-skill/references/tools.md +1 -0
- package/dist/copilot/.github/copilot-instructions.md +601 -73
- package/dist/cursor/.cursor/rules/advanced-typescript-design.mdc +437 -0
- package/dist/cursor/.cursor/rules/joktec-mongo-skill.mdc +66 -20
- package/dist/cursor/.cursor/rules/joktec-mysql-skill.mdc +103 -56
- package/dist/cursor/.cursor/rules/joktec-tool-skill.mdc +1 -0
- package/dist/gemini/GEMINI.md +603 -73
- package/dist/windsurf/.windsurf/rules/advanced-typescript-design.md +433 -0
- package/dist/windsurf/.windsurf/rules/joktec-mongo-skill.md +66 -20
- package/dist/windsurf/.windsurf/rules/joktec-mysql-skill.md +103 -56
- package/dist/windsurf/.windsurf/rules/joktec-tool-skill.md +1 -0
- package/package.json +6 -3
- package/scripts/sync-pack-version.mjs +38 -0
- package/skill-pack.json +35 -1
- package/skills/advanced-typescript-design/SKILL.md +60 -0
- package/skills/advanced-typescript-design/agents/openai.yaml +4 -0
- package/skills/advanced-typescript-design/references/advanced.md +219 -0
- package/skills/advanced-typescript-design/references/simple.md +149 -0
- package/skills/joktec-mongo-skill/SKILL.md +9 -2
- package/skills/joktec-mongo-skill/references/repository.md +14 -11
- package/skills/joktec-mongo-skill/references/schema-and-plugins.md +43 -7
- package/skills/joktec-mysql-skill/SKILL.md +6 -2
- package/skills/joktec-mysql-skill/references/entities.md +82 -53
- package/skills/joktec-mysql-skill/references/repository.md +15 -1
- package/skills/joktec-tool-skill/references/tools.md +1 -0
|
@@ -0,0 +1,433 @@
|
|
|
1
|
+
# Advanced TypeScript Design
|
|
2
|
+
|
|
3
|
+
Use this skill for TypeScript framework/library design, including generic public APIs, infer/conditional/recursive mapped types, decorator metadata, type-safe query DSLs, lifecycle abstractions, and design pattern selection. Use for TypeScript/NestJS packages, repositories, DTO/query types, clients, loaders, metrics, or when deciding whether simple TypeScript is enough or advanced type-system design is justified.
|
|
4
|
+
|
|
5
|
+
## Overview
|
|
6
|
+
|
|
7
|
+
Act as a TypeScript architecture partner. Choose the simplest design that preserves clear boundaries, runtime correctness, and useful compile-time guarantees.
|
|
8
|
+
|
|
9
|
+
Use design patterns as vocabulary and pressure tests, not as decoration. Prefer local project conventions, readable APIs, and low-friction extension points before adding type-level machinery.
|
|
10
|
+
|
|
11
|
+
## Architectural Mindset
|
|
12
|
+
|
|
13
|
+
- Start from the domain boundary: identify entity, request/response, service, repository, client, decorator, loader, and integration responsibilities.
|
|
14
|
+
- Keep public APIs narrow and stable. Make extension explicit through interfaces, abstract classes, generic constraints, or composition.
|
|
15
|
+
- Use classes when lifecycle, inheritance hooks, decorators, or framework reflection matter. Use plain functions/types when behavior is stateless or purely transformational.
|
|
16
|
+
- Let runtime validation and compile-time types reinforce each other. Do not pretend TypeScript types validate untrusted runtime data.
|
|
17
|
+
- Do not assume TypeScript generics, interfaces, unions, or array element types exist at runtime through `reflect-metadata`.
|
|
18
|
+
- Escalate type complexity only when it removes real duplication, prevents invalid states, or makes an API substantially safer.
|
|
19
|
+
- Check existing code before inventing a new pattern; mirror the repository's style when it already solves the same class of problem.
|
|
20
|
+
|
|
21
|
+
## Public API Compatibility
|
|
22
|
+
|
|
23
|
+
- Treat exported types, classes, decorators, config objects, modules, and provider APIs as public contracts.
|
|
24
|
+
- Prefer additive changes over breaking renames, deleted fields, changed generic parameter order, or narrower accepted input shapes.
|
|
25
|
+
- Before changing exported generic types, check downstream inference from normal call sites and verify that common extension patterns still compile.
|
|
26
|
+
- If a breaking type or runtime contract change is unavoidable, report migration impact explicitly and include the smallest migration path.
|
|
27
|
+
|
|
28
|
+
## Pattern Vocabulary
|
|
29
|
+
|
|
30
|
+
Use the classic catalog as shared language, including the TypeScript examples catalog from Refactoring.Guru.
|
|
31
|
+
|
|
32
|
+
- Creational Patterns: Abstract Factory, Builder, Factory Method, Prototype, Singleton.
|
|
33
|
+
- Structural Patterns: Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy.
|
|
34
|
+
- Behavioral Patterns: Chain of Responsibility, Iterator, Memento, State, Template Method, Command, Mediator, Observer, Strategy, Visitor.
|
|
35
|
+
|
|
36
|
+
Treat pattern names as a starting point for design discussion. Validate whether the implementation needs the pattern's tradeoffs, or whether a direct function, data object, or interface is enough.
|
|
37
|
+
|
|
38
|
+
## Agent Workflow
|
|
39
|
+
|
|
40
|
+
1. Inspect local code first when working inside a repository. Look for existing abstractions, decorators, DTO types, factory functions, lifecycle hooks, and tests.
|
|
41
|
+
2. Classify the task:
|
|
42
|
+
- Use `references/simple.md` for everyday TypeScript, OOP, data modeling, classes, interfaces, types, records, maps, arrays, simple decorators, and pragmatic refactors.
|
|
43
|
+
- Use `references/advanced.md` for generic framework code, recursive mapped types, `infer`, distributed/deferred conditional types, reflection metadata, advanced decorators, type-safe builders, plugin architectures, or expert pattern selection.
|
|
44
|
+
3. Choose the least complex pattern that solves the force in front of you. Record why a simpler alternative was not enough when choosing advanced machinery.
|
|
45
|
+
4. Design the public surface before implementation: inputs, outputs, extension points, error behavior, lifecycle, and type inference experience.
|
|
46
|
+
5. Implement incrementally. Keep runtime behavior testable, and add focused type-level checks when exported generic or decorator behavior is subtle.
|
|
47
|
+
6. Review for overengineering: remove unused generic parameters, speculative base classes, unnecessary inheritance, and type utilities that do not protect a real API.
|
|
48
|
+
|
|
49
|
+
## Repository Signals
|
|
50
|
+
|
|
51
|
+
In JokTec-style TypeScript, expect patterns such as:
|
|
52
|
+
|
|
53
|
+
- Generic request/query types with recursive conditions and sort/populate typing.
|
|
54
|
+
- Factory functions that return decorated NestJS classes.
|
|
55
|
+
- Abstract services and clients with template methods for lifecycle-specific behavior.
|
|
56
|
+
- Decorator factories that compose validation, Swagger, transformation, metrics, and integration metadata.
|
|
57
|
+
- Loader/registry patterns that collect decorator metadata and wire runtime behavior during module initialization.
|
|
58
|
+
|
|
59
|
+
## Bundled References
|
|
60
|
+
|
|
61
|
+
### references/advanced.md
|
|
62
|
+
|
|
63
|
+
# Advanced TypeScript Design Guidance
|
|
64
|
+
|
|
65
|
+
Use this reference for framework-level TypeScript, generic libraries, decorator infrastructure, metadata-driven loaders, and APIs where compile-time inference is part of the product experience.
|
|
66
|
+
|
|
67
|
+
## Escalation Criteria
|
|
68
|
+
|
|
69
|
+
Reach for advanced TypeScript only when at least one is true:
|
|
70
|
+
|
|
71
|
+
- The API is reused widely and type inference prevents real misuse.
|
|
72
|
+
- The runtime model is already generic, recursive, or metadata-driven.
|
|
73
|
+
- The abstraction eliminates repeated boilerplate across many entities, DTOs, repositories, services, clients, or transports.
|
|
74
|
+
- The type-level design mirrors a stable domain contract, not a speculative future.
|
|
75
|
+
- Tests or examples can prove both runtime behavior and developer ergonomics.
|
|
76
|
+
|
|
77
|
+
If the advanced type exists only to feel clever, delete it.
|
|
78
|
+
|
|
79
|
+
## Infer, Conditional, and Deferred Types
|
|
80
|
+
|
|
81
|
+
- Use `infer` to extract return types, payloads, entity types, DTO shapes, tuple elements, and callback signatures from source contracts.
|
|
82
|
+
- Control distributive conditional types intentionally. Wrap operands in tuples, such as `[T] extends [U]`, when union distribution is not wanted.
|
|
83
|
+
- Prefer named intermediate aliases when nested conditionals exceed two branches.
|
|
84
|
+
- Use `never` as a filter, but verify that it cannot erase useful error information from public APIs.
|
|
85
|
+
- Treat deferred conditional types and generic inference as public UX: callers should get helpful autocomplete and errors without manual type arguments.
|
|
86
|
+
|
|
87
|
+
## Recursive and Mapped Types
|
|
88
|
+
|
|
89
|
+
- Use recursive mapped types for query languages, nested sort/select/populate APIs, deep partials, and entity graph traversal.
|
|
90
|
+
- Add clear stop conditions for primitives, dates, arrays, functions, and branded values.
|
|
91
|
+
- Use branded or opaque types for special primitives such as `ObjectId`, `UserId`, tenant IDs, cursors, or external reference IDs when plain strings would blur domain boundaries.
|
|
92
|
+
- Avoid infinite or overly expensive type recursion. Keep recursion shallow enough for editor performance.
|
|
93
|
+
- Preserve optionality and readonly modifiers intentionally with `+?`, `-?`, `readonly`, and `-readonly`.
|
|
94
|
+
- Separate query operator typing from entity typing so the operator model remains testable and reusable.
|
|
95
|
+
|
|
96
|
+
## Reflection and Decorators
|
|
97
|
+
|
|
98
|
+
- Use `reflect-metadata` only when runtime type information materially improves the API: schema generation, validation composition, serialization, dependency injection, or loader registration.
|
|
99
|
+
- Remember that reflected TypeScript types are lossy at runtime. Arrays, unions, generics, and interfaces need explicit options or factories.
|
|
100
|
+
- Prefer decorator factories that normalize options, resolve type factories, compose framework decorators, and define one clear metadata contract.
|
|
101
|
+
- Keep advanced decorators thin at the call site and explicit internally: clone options, sanitize runtime-only fields, then compose validators, transformers, docs, and persistence metadata.
|
|
102
|
+
- For method decorators, preserve `this`, return values, thrown errors, and async behavior unless the decorator explicitly changes them.
|
|
103
|
+
- Use function source parsing only as a last-resort runtime technique for decorator infrastructure, such as mapping method argument names. Keep it isolated, deterministic, and covered by tests because minification, transpilation, defaults, destructuring, and comments can break it.
|
|
104
|
+
- Test decorator behavior through a class that uses it, especially for metadata, wrapping behavior, and dependency injection.
|
|
105
|
+
|
|
106
|
+
## Type-Level Verification
|
|
107
|
+
|
|
108
|
+
- Add type-level tests when changing exported generic utilities, query DSLs, decorators, builders, or public inference-heavy APIs.
|
|
109
|
+
- Prefer the project's existing compile/type test setup. If available, use `tsd`, `expect-type`, `vitest`/`jest` type helpers, or a dedicated `tsc --noEmit` fixture.
|
|
110
|
+
- Include positive inference examples from normal call sites, not only explicit generic arguments.
|
|
111
|
+
- Include negative examples with `@ts-expect-error` when an invalid state must stay rejected.
|
|
112
|
+
- Verify runtime tests separately when decorators, reflection metadata, validation, transformation, or loaders are involved.
|
|
113
|
+
|
|
114
|
+
## Expert Pattern Selection
|
|
115
|
+
|
|
116
|
+
- Abstract Factory fits families of related clients, repositories, or transport adapters that must be created consistently.
|
|
117
|
+
- Builder fits fluent configuration with required-step guarantees; type-state builders can enforce completeness but should stay readable.
|
|
118
|
+
- Factory Method fits framework hooks that create DTOs, pagination wrappers, controllers, or provider instances.
|
|
119
|
+
- Prototype fits cloning configured objects when construction is expensive or stateful.
|
|
120
|
+
- Singleton should usually be delegated to the DI container; avoid hand-rolled global state.
|
|
121
|
+
- Adapter fits third-party client normalization and migration layers.
|
|
122
|
+
- Bridge fits separating abstraction from implementation, such as transport-agnostic messaging APIs over Rabbit, Kafka, or Redis.
|
|
123
|
+
- Composite fits tree-shaped filters, pipelines, menu/routes, or nested query conditions.
|
|
124
|
+
- Decorator fits metrics, retries, circuit breakers, serialization, validation, or publishing side effects around existing behavior.
|
|
125
|
+
- Facade fits a stable service hiding multiple low-level collaborators.
|
|
126
|
+
- Flyweight fits large repeated metadata or schema objects only after measuring memory pressure.
|
|
127
|
+
- Proxy fits lazy clients, caching, access control, retries, and remote boundaries.
|
|
128
|
+
- Chain of Responsibility fits validation, middleware, parsing, and request pipelines.
|
|
129
|
+
- Command fits queued work, replayable operations, and undoable actions.
|
|
130
|
+
- Iterator fits cursor pagination and collection traversal without exposing storage details.
|
|
131
|
+
- Mediator fits module coordination where direct dependencies would become tangled.
|
|
132
|
+
- Memento fits snapshots, rollbacks, and state restoration.
|
|
133
|
+
- Observer fits event streams and pub/sub, with explicit unsubscribe and error policy.
|
|
134
|
+
- State fits lifecycle-heavy clients, jobs, or connections with mode-specific behavior.
|
|
135
|
+
- Strategy fits interchangeable algorithms selected by config or runtime context.
|
|
136
|
+
- Template Method fits abstract base services/clients that own lifecycle while subclasses implement `init`, `start`, `stop`, `validate`, or `transform` steps.
|
|
137
|
+
- Visitor fits operations over stable object structures when adding new operations is more common than adding new node types.
|
|
138
|
+
|
|
139
|
+
## Symbolic Examples
|
|
140
|
+
|
|
141
|
+
Use examples like these as compact templates for thinking. Keep production implementations smaller or larger depending on the actual force.
|
|
142
|
+
|
|
143
|
+
### Type-Safe Event Map
|
|
144
|
+
|
|
145
|
+
```typescript
|
|
146
|
+
type EventMap = {
|
|
147
|
+
"user.created": { id: string };
|
|
148
|
+
"invoice.paid": { invoiceId: string; amount: number };
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
class EventBus<TEvents extends Record<string, unknown>> {
|
|
152
|
+
on<K extends keyof TEvents>(event: K, handler: (payload: TEvents[K]) => void) {}
|
|
153
|
+
emit<K extends keyof TEvents>(event: K, payload: TEvents[K]) {}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const bus = new EventBus<EventMap>();
|
|
157
|
+
bus.emit("invoice.paid", { invoiceId: "inv_1", amount: 100 });
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
Use this for Observer/Mediator-style APIs where event names and payloads must stay coupled.
|
|
161
|
+
|
|
162
|
+
### API Contract Inference
|
|
163
|
+
|
|
164
|
+
```typescript
|
|
165
|
+
type Endpoint = {
|
|
166
|
+
"/users/:id": {
|
|
167
|
+
GET: { params: { id: string }; response: User };
|
|
168
|
+
PATCH: { params: { id: string }; body: Partial<User>; response: User };
|
|
169
|
+
};
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
type ResponseOf<T> = T extends { response: infer R } ? R : never;
|
|
173
|
+
|
|
174
|
+
class ApiClient<TContract extends Record<string, any>> {
|
|
175
|
+
request<Path extends keyof TContract, Method extends keyof TContract[Path]>(
|
|
176
|
+
path: Path,
|
|
177
|
+
method: Method,
|
|
178
|
+
): Promise<ResponseOf<TContract[Path][Method]>> {
|
|
179
|
+
return null as any;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
Use this when a contract object should drive call-site inference.
|
|
185
|
+
|
|
186
|
+
### Type-State Builder
|
|
187
|
+
|
|
188
|
+
```typescript
|
|
189
|
+
type With<K extends string> = Record<K, true>;
|
|
190
|
+
|
|
191
|
+
class JobBuilder<State = {}> {
|
|
192
|
+
queue(name: string): JobBuilder<State & With<"queue">> {
|
|
193
|
+
return this as any;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
handler(fn: () => Promise<void>): JobBuilder<State & With<"handler">> {
|
|
197
|
+
return this as any;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
build(this: State extends With<"queue"> & With<"handler"> ? JobBuilder<State> : never) {
|
|
201
|
+
return {};
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
Use this when incomplete configuration is common and worth rejecting at compile time.
|
|
207
|
+
|
|
208
|
+
### Recursive Query Shape
|
|
209
|
+
|
|
210
|
+
```typescript
|
|
211
|
+
type Primitive = string | number | boolean | Date;
|
|
212
|
+
type FieldOp<T> = T | { $eq?: T; $in?: T[] };
|
|
213
|
+
type Brand<T, Name extends string> = T & { readonly __brand: Name };
|
|
214
|
+
type ObjectId = Brand<string, "ObjectId">;
|
|
215
|
+
|
|
216
|
+
type Query<T> = {
|
|
217
|
+
[K in keyof T]?: T[K] extends Primitive
|
|
218
|
+
? FieldOp<T[K]>
|
|
219
|
+
: T[K] extends Array<infer U>
|
|
220
|
+
? Query<U>
|
|
221
|
+
: Query<T[K]>;
|
|
222
|
+
} & {
|
|
223
|
+
$or?: Query<T>[];
|
|
224
|
+
};
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
Use this for Composite-style nested filters, but add stop conditions before expanding it.
|
|
228
|
+
|
|
229
|
+
### Opaque ID Boundary
|
|
230
|
+
|
|
231
|
+
```typescript
|
|
232
|
+
type Brand<T, Name extends string> = T & { readonly __brand: Name };
|
|
233
|
+
type UserId = Brand<string, "UserId">;
|
|
234
|
+
type PostId = Brand<string, "PostId">;
|
|
235
|
+
|
|
236
|
+
function asUserId(value: string): UserId {
|
|
237
|
+
return value as UserId;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function findUser(id: UserId) {}
|
|
241
|
+
|
|
242
|
+
findUser(asUserId("u_1"));
|
|
243
|
+
// @ts-expect-error raw strings are not accepted here
|
|
244
|
+
findUser("u_1");
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
Use this when a domain primitive crosses many generic/query layers and accidental mixing would be costly.
|
|
248
|
+
|
|
249
|
+
### Decorator Wrapper with Preserved Method Contract
|
|
250
|
+
|
|
251
|
+
```typescript
|
|
252
|
+
function Around(run: (next: () => unknown) => unknown): MethodDecorator {
|
|
253
|
+
return (_, __, descriptor) => {
|
|
254
|
+
const original = descriptor.value;
|
|
255
|
+
|
|
256
|
+
descriptor.value = function (...args: unknown[]) {
|
|
257
|
+
return run(() => original.apply(this, args));
|
|
258
|
+
};
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
Use this for metrics, retry, logging, or publishing side effects; preserve `this`, args, return values, and thrown errors.
|
|
264
|
+
|
|
265
|
+
## JokTec-Style Signals to Reuse
|
|
266
|
+
|
|
267
|
+
- Recursive query typing can combine entity properties with operator unions, nested entity traversal, and logical `$or`/`$and` shapes.
|
|
268
|
+
- Base services and clients commonly use Template Method: the base class owns lifecycle and shared behavior while subclasses provide specific implementation steps.
|
|
269
|
+
- Controller factories can return decorated classes to avoid repetitive NestJS endpoint scaffolding while preserving DTO-specific metadata.
|
|
270
|
+
- Decorator infrastructure often composes Swagger, validation, transformation, persistence, and metric behavior from one options object.
|
|
271
|
+
- Rabbit loaders show a metadata registry plus module-init loader pattern: decorators declare intent; loaders resolve providers and connect runtime consumers.
|
|
272
|
+
|
|
273
|
+
## Advanced Review Checklist
|
|
274
|
+
|
|
275
|
+
- Does every generic parameter appear in the public contract or implementation?
|
|
276
|
+
- Can inference succeed from normal call-site arguments?
|
|
277
|
+
- Does the type-level model match runtime validation and transformation?
|
|
278
|
+
- Are metadata keys centralized and collision-resistant?
|
|
279
|
+
- Are decorator side effects documented by tests?
|
|
280
|
+
- Is editor performance acceptable after adding recursive or conditional types?
|
|
281
|
+
- Is there a simpler Strategy, Adapter, or function-based design that would provide the same value?
|
|
282
|
+
|
|
283
|
+
### references/simple.md
|
|
284
|
+
|
|
285
|
+
# Simple TypeScript Design Guidance
|
|
286
|
+
|
|
287
|
+
Use this reference for ordinary application and library work where readability, stable APIs, and maintainable TypeScript matter more than type-level cleverness.
|
|
288
|
+
|
|
289
|
+
## Default Practices
|
|
290
|
+
|
|
291
|
+
- Prefer explicit, small interfaces for public boundaries and concrete classes for runtime behavior with lifecycle, dependency injection, or decorators.
|
|
292
|
+
- Use `type` for unions, mapped shapes, conditional aliases, and composition. Use `interface` for object contracts intended to be implemented or extended.
|
|
293
|
+
- Keep primitive aliases meaningful. A `UserId` alias can clarify intent, but it does not add runtime safety unless paired with validation or branding.
|
|
294
|
+
- Model data with plain objects when behavior is absent. Add classes when construction, methods, inheritance hooks, decorators, or framework reflection are required.
|
|
295
|
+
- Keep DTOs, entities, requests, and responses separate when they have different validation, persistence, or transport concerns.
|
|
296
|
+
- Avoid `any` at public boundaries. Use `unknown` for untrusted data, then narrow or validate it.
|
|
297
|
+
- Prefer narrow generic constraints such as `T extends Entity` over unconstrained `T` when the implementation depends on object semantics.
|
|
298
|
+
|
|
299
|
+
## Classes, Interfaces, and OOP
|
|
300
|
+
|
|
301
|
+
- Use abstract classes for shared runtime behavior, protected hooks, and constructor-injected dependencies.
|
|
302
|
+
- Use interfaces for contracts that should not carry runtime behavior.
|
|
303
|
+
- Prefer composition over inheritance when variants differ by collaborator rather than lifecycle.
|
|
304
|
+
- Keep protected hooks purposeful: `afterInit`, `transform`, `validate`, and `map` are good when subclasses are expected to customize one stable step.
|
|
305
|
+
- Avoid deep inheritance chains. If a third level appears, consider Strategy, Adapter, or composition.
|
|
306
|
+
|
|
307
|
+
## Common Data Structures
|
|
308
|
+
|
|
309
|
+
- Use `Record<K, V>` when the key set is known or constrained.
|
|
310
|
+
- Use `{ [key: string]: V }` when the object is truly open-ended.
|
|
311
|
+
- Use `Map<K, V>` when keys are not strings, insertion order matters, or frequent add/remove operations are central.
|
|
312
|
+
- Use arrays for ordered collections and tuples for fixed positional contracts.
|
|
313
|
+
- Use discriminated unions for state or command variants instead of loose booleans.
|
|
314
|
+
- Keep hash-like caches private unless callers need iteration, eviction, or explicit lifecycle.
|
|
315
|
+
|
|
316
|
+
## Basic Types and Utilities
|
|
317
|
+
|
|
318
|
+
- Use union literals for finite options: status, mode, operation, direction.
|
|
319
|
+
- Use `Pick`, `Omit`, `Partial`, `Required`, `Readonly`, `Record`, `Extract`, and `Exclude` before writing custom utilities.
|
|
320
|
+
- Use `keyof` and indexed access types for property-safe APIs.
|
|
321
|
+
- Use overloads sparingly; prefer a single options object when overloads become hard to read.
|
|
322
|
+
- Keep mapped types shallow unless the data is truly nested and the API benefits from deep transformation.
|
|
323
|
+
|
|
324
|
+
## Simple Decorators
|
|
325
|
+
|
|
326
|
+
- Use decorator factories to attach framework metadata or compose existing decorators.
|
|
327
|
+
- Keep decorator options serializable and explicit where possible.
|
|
328
|
+
- Separate metadata collection from runtime execution. A decorator should usually register intent; a loader/service should execute it later.
|
|
329
|
+
- Avoid parsing function source in ordinary decorators. If runtime argument-name mapping truly requires it, escalate to `advanced.md` and isolate the parser behind tests.
|
|
330
|
+
- Test decorators at the behavior boundary, not only by checking metadata keys.
|
|
331
|
+
|
|
332
|
+
## Pattern Choices
|
|
333
|
+
|
|
334
|
+
- Use Factory Method or simple factory functions when object creation varies by type or config.
|
|
335
|
+
- Use Builder for stepwise configuration only when partially built objects are common or order matters.
|
|
336
|
+
- Use Adapter to normalize third-party APIs behind project interfaces.
|
|
337
|
+
- Use Facade to simplify a noisy subsystem for callers.
|
|
338
|
+
- Use Decorator when behavior should wrap a method/object without changing its public contract.
|
|
339
|
+
- Use Template Method when a base class owns an algorithm and subclasses fill in specific steps.
|
|
340
|
+
- Use Strategy when an algorithm family changes independently from the caller.
|
|
341
|
+
- Use Observer or Mediator for event-style communication, but keep ownership and error handling explicit.
|
|
342
|
+
|
|
343
|
+
## Symbolic Examples
|
|
344
|
+
|
|
345
|
+
Use examples like these to reason about shape and tradeoffs. Keep final code adapted to the repository style.
|
|
346
|
+
|
|
347
|
+
### Strategy with a Narrow Interface
|
|
348
|
+
|
|
349
|
+
```typescript
|
|
350
|
+
interface PriceStrategy {
|
|
351
|
+
total(items: CartItem[]): number;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
class RetailPrice implements PriceStrategy {
|
|
355
|
+
total(items: CartItem[]) {
|
|
356
|
+
return items.reduce((sum, item) => sum + item.price, 0);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
class WholesalePrice implements PriceStrategy {
|
|
361
|
+
total(items: CartItem[]) {
|
|
362
|
+
return items.reduce((sum, item) => sum + item.price * 0.9, 0);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
class CheckoutService {
|
|
367
|
+
constructor(private readonly strategy: PriceStrategy) {}
|
|
368
|
+
|
|
369
|
+
quote(items: CartItem[]) {
|
|
370
|
+
return this.strategy.total(items);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
Use this when the caller should not know which algorithm is active.
|
|
376
|
+
|
|
377
|
+
### Adapter for Third-Party Boundaries
|
|
378
|
+
|
|
379
|
+
```typescript
|
|
380
|
+
interface MessageBus {
|
|
381
|
+
publish(topic: string, payload: unknown): Promise<void>;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
class RabbitBusAdapter implements MessageBus {
|
|
385
|
+
constructor(private readonly rabbit: RabbitClient) {}
|
|
386
|
+
|
|
387
|
+
publish(topic: string, payload: unknown) {
|
|
388
|
+
return this.rabbit.sendToQueue(topic, JSON.stringify(payload));
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
Use this when external clients have noisy or unstable APIs.
|
|
394
|
+
|
|
395
|
+
### Template Method for Lifecycle Hooks
|
|
396
|
+
|
|
397
|
+
```typescript
|
|
398
|
+
abstract class ManagedClient<TConfig, TClient> {
|
|
399
|
+
async connect(config: TConfig) {
|
|
400
|
+
const client = await this.create(config);
|
|
401
|
+
await this.start(client);
|
|
402
|
+
return client;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
protected abstract create(config: TConfig): Promise<TClient>;
|
|
406
|
+
protected abstract start(client: TClient): Promise<void>;
|
|
407
|
+
}
|
|
408
|
+
```
|
|
409
|
+
|
|
410
|
+
Use this when the base class owns lifecycle order and subclasses fill the variable steps.
|
|
411
|
+
|
|
412
|
+
### Simple Decorator Metadata
|
|
413
|
+
|
|
414
|
+
```typescript
|
|
415
|
+
const HANDLER_KEY = "app:handler";
|
|
416
|
+
|
|
417
|
+
function Handler(name: string): MethodDecorator {
|
|
418
|
+
return (_, __, descriptor) => {
|
|
419
|
+
Reflect.defineMetadata(HANDLER_KEY, name, descriptor.value);
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
```
|
|
423
|
+
|
|
424
|
+
Use this when methods declare intent and another loader executes it later.
|
|
425
|
+
|
|
426
|
+
## Practical Review Checklist
|
|
427
|
+
|
|
428
|
+
- Can a teammate understand the public API without reading private helpers?
|
|
429
|
+
- Does the type design represent real runtime rules?
|
|
430
|
+
- Are names domain-specific enough to explain intent?
|
|
431
|
+
- Is the pattern solving current duplication or variability?
|
|
432
|
+
- Are validation, transformation, persistence, and transport concerns separated?
|
|
433
|
+
- Are tests focused on behavior that the abstraction promises to preserve?
|
|
@@ -10,9 +10,16 @@ Use this skill for MongoDB-backed resources that rely on JokTec's Mongoose/Typeg
|
|
|
10
10
|
- Keep schema classes, app repositories, and app-specific queries in the consumer app.
|
|
11
11
|
- Extend `MongoRepo<T, ID>` for app repositories.
|
|
12
12
|
- Preserve `conId` when the app has multiple Mongo connections.
|
|
13
|
-
- Use schema-first decorators when a schema class should be reused as a DTO source.
|
|
13
|
+
- Use schema-first decorators when a schema class should be reused as a DTO source; wrappers should reduce repeated Typegoose, validator, transformer, and Swagger stacks.
|
|
14
|
+
- Use `RefId<T>` for stored reference id fields and `PopulatedRef<T>` for populated virtual fields.
|
|
15
|
+
- Use `@Schema({ kind: 'embedded' })` for value objects without `_id` or timestamps.
|
|
16
|
+
- Use `@Schema({ kind: 'subdocument' })` for embedded documents that need their own `_id` and timestamps.
|
|
17
|
+
- Use `@Prop({ kind: 'virtual', mode: 'getter' })` for computed getters that need expose/Swagger metadata without persistence.
|
|
18
|
+
- Use `@Prop({ ref: () => Target, foreignField, localField })` for populate-one virtuals when inferred defaults are enough.
|
|
19
|
+
- Use `@Prop({ type: () => [Target], ref: () => Target, foreignField, localField })` for populate-array virtuals.
|
|
20
|
+
- Use `@Prop({ kind: 'map', type: Object })` for map/snapshot payloads that must keep their raw shape.
|
|
14
21
|
- Treat ObjectId casting and regex behavior as safety-sensitive.
|
|
15
|
-
-
|
|
22
|
+
- For real migrations, inspect `node_modules/@joktec/mongo` first, then installed README or GitHub package docs, then GitHub source before assuming APIs.
|
|
16
23
|
|
|
17
24
|
## References
|
|
18
25
|
|
|
@@ -29,16 +36,18 @@ Use this skill for MongoDB-backed resources that rely on JokTec's Mongoose/Typeg
|
|
|
29
36
|
|
|
30
37
|
When blocked, inspect:
|
|
31
38
|
|
|
32
|
-
- `
|
|
33
|
-
- `
|
|
34
|
-
- `packages/databases/mongo
|
|
35
|
-
-
|
|
36
|
-
- `packages/databases/mongo/src/
|
|
37
|
-
- `packages/databases/mongo/src/mongo.
|
|
38
|
-
- `packages/databases/mongo/src/
|
|
39
|
-
- `packages/databases/mongo/src/
|
|
40
|
-
- `packages/databases/mongo/src/helpers/mongo.
|
|
41
|
-
- `packages/databases/mongo/src/
|
|
39
|
+
- Consumer project first: `node_modules/@joktec/mongo`.
|
|
40
|
+
- Installed docs next: `node_modules/@joktec/mongo/README.md`.
|
|
41
|
+
- GitHub docs next: `https://github.com/joktec/joktec-framework/tree/main/packages/databases/mongo`.
|
|
42
|
+
- GitHub source fallback:
|
|
43
|
+
- `packages/databases/mongo/src/index.ts`
|
|
44
|
+
- `packages/databases/mongo/src/mongo.module.ts`
|
|
45
|
+
- `packages/databases/mongo/src/mongo.service.ts`
|
|
46
|
+
- `packages/databases/mongo/src/mongo.repo.ts`
|
|
47
|
+
- `packages/databases/mongo/src/helpers/mongo.helper.ts`
|
|
48
|
+
- `packages/databases/mongo/src/helpers/mongo.pipeline.ts`
|
|
49
|
+
- `packages/databases/mongo/src/helpers/mongo.utils.ts`
|
|
50
|
+
- `packages/databases/mongo/src/models/*`
|
|
42
51
|
|
|
43
52
|
## Module Setup
|
|
44
53
|
|
|
@@ -60,7 +69,8 @@ Repository checklist:
|
|
|
60
69
|
- Keep schema-specific query helpers in the app repository, not in controllers.
|
|
61
70
|
- Use repository methods for standard reads so query parsing, soft delete, populate, and pagination stay consistent.
|
|
62
71
|
- Pass transaction/session options through read-modify-write flows when the app uses transactions.
|
|
63
|
-
-
|
|
72
|
+
- Repository read paths should return schema class instances with normalized ObjectId/string values, including populated and deep-populated values.
|
|
73
|
+
- Code that needs raw Mongoose documents should use `MongoService.getModel(...)` or Typegoose/Mongoose APIs directly.
|
|
64
74
|
|
|
65
75
|
## Query Safety
|
|
66
76
|
|
|
@@ -95,13 +105,20 @@ Cursor checklist:
|
|
|
95
105
|
|
|
96
106
|
When blocked, inspect:
|
|
97
107
|
|
|
98
|
-
- `
|
|
99
|
-
- `
|
|
100
|
-
- `packages/databases/mongo
|
|
101
|
-
-
|
|
102
|
-
- `packages/databases/mongo/src/
|
|
103
|
-
- `packages/databases/mongo/src/
|
|
104
|
-
- `packages/databases/mongo/src/
|
|
108
|
+
- Consumer project first: `node_modules/@joktec/mongo`.
|
|
109
|
+
- Package docs next: `node_modules/@joktec/mongo/README.md`.
|
|
110
|
+
- GitHub docs next: `https://github.com/joktec/joktec-framework/tree/main/packages/databases/mongo`.
|
|
111
|
+
- GitHub source fallback:
|
|
112
|
+
- `packages/databases/mongo/src/decorators/schema.decorator.ts`
|
|
113
|
+
- `packages/databases/mongo/src/decorators/schema.options.ts`
|
|
114
|
+
- `packages/databases/mongo/src/decorators/prop.decorator.ts`
|
|
115
|
+
- `packages/databases/mongo/src/decorators/props/*`
|
|
116
|
+
- `packages/databases/mongo/src/models/mongo.ref.ts`
|
|
117
|
+
- `packages/databases/mongo/src/models/object-id.ts`
|
|
118
|
+
- `packages/databases/mongo/src/models/mongo.schema.ts`
|
|
119
|
+
- `packages/databases/mongo/src/plugins/paranoid.plugin.ts`
|
|
120
|
+
- `packages/databases/mongo/src/plugins/strict-reference.plugin.ts`
|
|
121
|
+
- `packages/databases/mongo/src/plugins/transform.plugin.ts`
|
|
105
122
|
|
|
106
123
|
## Schema Decorators
|
|
107
124
|
|
|
@@ -116,6 +133,35 @@ Best practice:
|
|
|
116
133
|
- Pass custom validators/transforms explicitly rather than adding hidden global behavior.
|
|
117
134
|
- Keep maps, snapshots, and dynamic objects explicit so helper conversion does not alter their shape.
|
|
118
135
|
- Keep app-level reference semantics visible; strict reference plugin checks existence, but the app still owns domain rules.
|
|
136
|
+
- Use `RefId<T>` for persisted id fields and `PopulatedRef<T>` for populated virtual instance fields.
|
|
137
|
+
- Use lazy `type` resolvers such as `type: () => User` or `type: () => [User]` when the wrapper cannot infer the runtime class.
|
|
138
|
+
- Use `@Schema({ kind: 'embedded' })` for value objects without `_id` or timestamps.
|
|
139
|
+
- Use `@Schema({ kind: 'subdocument' })` for embedded documents that need `_id` and timestamps but should not create a collection.
|
|
140
|
+
- Use `@Prop({ kind: 'virtual', mode: 'getter', comment, optional, hidden, expose, swagger })` for computed getters that only need class-transformer and Swagger metadata.
|
|
141
|
+
- Use `@Prop({ ref: () => User, foreignField, localField })` for populate-one virtuals when inferred defaults are enough.
|
|
142
|
+
- Use `@Prop({ type: () => [User], ref: () => User, foreignField, localField })` for populate-array virtuals.
|
|
143
|
+
- Use `@Prop({ kind: 'map', type: Object })` for raw maps/snapshots instead of passing `PropType.MAP` at the call site.
|
|
144
|
+
|
|
145
|
+
Common mappings:
|
|
146
|
+
|
|
147
|
+
| Use case | Preferred shape |
|
|
148
|
+
| --- | --- |
|
|
149
|
+
| Stored single reference id | `fieldId?: RefId<User>` with `@Prop({ type: ObjectId, ref: () => User })` |
|
|
150
|
+
| Stored reference id array | `fieldIds?: RefId<User>[]` with `@Prop({ type: [ObjectId], ref: () => User })` |
|
|
151
|
+
| Embedded value object | `@Schema({ kind: 'embedded' })` on the nested class |
|
|
152
|
+
| Embedded document | `@Schema({ kind: 'subdocument' })` on the nested class |
|
|
153
|
+
| Raw map/snapshot | `@Prop({ kind: 'map', type: Object })` |
|
|
154
|
+
| Populated single virtual | `field?: PopulatedRef<User>` with `@Prop({ ref: () => User, foreignField: '_id', localField: 'fieldId' })` |
|
|
155
|
+
| Populated virtual array | `fields?: PopulatedRef<User>[]` with `@Prop({ type: () => [User], ref: () => User, foreignField: '_id', localField: 'fieldIds' })` |
|
|
156
|
+
| Computed getter | `@Prop({ kind: 'virtual', mode: 'getter', comment: '...' }) get value() { ... }` |
|
|
157
|
+
|
|
158
|
+
Populate inference:
|
|
159
|
+
|
|
160
|
+
- `ref` + `localField` + `foreignField` marks the field as virtual populate.
|
|
161
|
+
- Populate-one can fallback to the same class from `ref`.
|
|
162
|
+
- Populate arrays still need `type: () => [Target]` because runtime reflection only sees `Array`.
|
|
163
|
+
- `justOne` defaults to `true` for non-array populate fields.
|
|
164
|
+
- Swagger examples default to `{}` or `[]` for populated fields unless explicitly overridden.
|
|
119
165
|
|
|
120
166
|
## Plugins
|
|
121
167
|
|