@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.
Files changed (47) hide show
  1. package/README.md +4 -2
  2. package/dist/claude/skills/advanced-typescript-design/SKILL.md +60 -0
  3. package/dist/claude/skills/advanced-typescript-design/agents/openai.yaml +4 -0
  4. package/dist/claude/skills/advanced-typescript-design/references/advanced.md +219 -0
  5. package/dist/claude/skills/advanced-typescript-design/references/simple.md +149 -0
  6. package/dist/claude/skills/joktec-mongo-skill/SKILL.md +9 -2
  7. package/dist/claude/skills/joktec-mongo-skill/references/repository.md +14 -11
  8. package/dist/claude/skills/joktec-mongo-skill/references/schema-and-plugins.md +43 -7
  9. package/dist/claude/skills/joktec-mysql-skill/SKILL.md +6 -2
  10. package/dist/claude/skills/joktec-mysql-skill/references/entities.md +82 -53
  11. package/dist/claude/skills/joktec-mysql-skill/references/repository.md +15 -1
  12. package/dist/claude/skills/joktec-tool-skill/references/tools.md +1 -0
  13. package/dist/codex/skills/advanced-typescript-design/SKILL.md +60 -0
  14. package/dist/codex/skills/advanced-typescript-design/agents/openai.yaml +4 -0
  15. package/dist/codex/skills/advanced-typescript-design/references/advanced.md +219 -0
  16. package/dist/codex/skills/advanced-typescript-design/references/simple.md +149 -0
  17. package/dist/codex/skills/joktec-mongo-skill/SKILL.md +9 -2
  18. package/dist/codex/skills/joktec-mongo-skill/references/repository.md +14 -11
  19. package/dist/codex/skills/joktec-mongo-skill/references/schema-and-plugins.md +43 -7
  20. package/dist/codex/skills/joktec-mysql-skill/SKILL.md +6 -2
  21. package/dist/codex/skills/joktec-mysql-skill/references/entities.md +82 -53
  22. package/dist/codex/skills/joktec-mysql-skill/references/repository.md +15 -1
  23. package/dist/codex/skills/joktec-tool-skill/references/tools.md +1 -0
  24. package/dist/copilot/.github/copilot-instructions.md +601 -73
  25. package/dist/cursor/.cursor/rules/advanced-typescript-design.mdc +437 -0
  26. package/dist/cursor/.cursor/rules/joktec-mongo-skill.mdc +66 -20
  27. package/dist/cursor/.cursor/rules/joktec-mysql-skill.mdc +103 -56
  28. package/dist/cursor/.cursor/rules/joktec-tool-skill.mdc +1 -0
  29. package/dist/gemini/GEMINI.md +603 -73
  30. package/dist/windsurf/.windsurf/rules/advanced-typescript-design.md +433 -0
  31. package/dist/windsurf/.windsurf/rules/joktec-mongo-skill.md +66 -20
  32. package/dist/windsurf/.windsurf/rules/joktec-mysql-skill.md +103 -56
  33. package/dist/windsurf/.windsurf/rules/joktec-tool-skill.md +1 -0
  34. package/package.json +6 -3
  35. package/scripts/sync-pack-version.mjs +38 -0
  36. package/skill-pack.json +35 -1
  37. package/skills/advanced-typescript-design/SKILL.md +60 -0
  38. package/skills/advanced-typescript-design/agents/openai.yaml +4 -0
  39. package/skills/advanced-typescript-design/references/advanced.md +219 -0
  40. package/skills/advanced-typescript-design/references/simple.md +149 -0
  41. package/skills/joktec-mongo-skill/SKILL.md +9 -2
  42. package/skills/joktec-mongo-skill/references/repository.md +14 -11
  43. package/skills/joktec-mongo-skill/references/schema-and-plugins.md +43 -7
  44. package/skills/joktec-mysql-skill/SKILL.md +6 -2
  45. package/skills/joktec-mysql-skill/references/entities.md +82 -53
  46. package/skills/joktec-mysql-skill/references/repository.md +15 -1
  47. package/skills/joktec-tool-skill/references/tools.md +1 -0
@@ -12,8 +12,12 @@ Use this skill for relational resources backed by JokTec's TypeORM wrapper.
12
12
  - Treat `mysql`, `mariadb`, and `postgres` as the first-class dialects.
13
13
  - Keep `sync` explicit and normally enabled only by an owner process or development bootstrap.
14
14
  - Do not add new behavior to deprecated `MysqlFinder`; use `MysqlRepo.qb()` and `MysqlHelper` paths.
15
- - When migrating an entity to the new schema-first decorators, migrate the whole property decorator stack, not only the TypeORM primary key decorator.
16
- - If guidance is insufficient, read this skill's references and inspect `../joktec-framework` package source or GitHub fallback before assuming APIs.
15
+ - Use schema-first `@Column`, `@PrimaryColumn`, and `@TimestampColumn` wrappers when an entity also acts as DTO metadata.
16
+ - Use `@Column({ kind: 'virtual' })` for computed getters that need expose/Swagger metadata without persistence.
17
+ - Use `immutable` for API read-only metadata; TypeORM `update: false` remains storage write behavior and is also inferred as Swagger read-only when `immutable` is not set.
18
+ - Do not add `swagger.type` just because a column has a primitive, date, array, nested JSON class, or relation type. The wrapper infers Swagger metadata from TypeScript design type and JokTec options. Use `swagger` only to override an inferred shape.
19
+ - Do not use `@joktec/mysql` for Mongo/ObjectId columns, even though TypeORM has Mongo-related APIs.
20
+ - For real migrations, inspect the installed `@joktec/mysql` source in the consumer project's `node_modules` first. If that is insufficient, read GitHub package docs, then GitHub source. Use the local `../joktec-framework` checkout only when you are working inside the JokTec development workspace.
17
21
 
18
22
  ## References
19
23
 
@@ -28,13 +32,29 @@ Use this skill for relational resources backed by JokTec's TypeORM wrapper.
28
32
 
29
33
  ## Source Lookup
30
34
 
31
- When blocked, inspect:
35
+ When blocked in a consumer project, inspect the installed package first:
36
+
37
+ - `node_modules/@joktec/mysql/README.md`
38
+ - `node_modules/@joktec/mysql/AGENTS.md` when published with the package
39
+ - `node_modules/@joktec/mysql/dist/index.d.ts`
40
+ - `node_modules/@joktec/mysql/dist/decorators/column.decorator.d.ts`
41
+ - `node_modules/@joktec/mysql/dist/decorators/columns/column.type.d.ts`
42
+ - `node_modules/@joktec/mysql/dist/decorators/timestamp.decorator.d.ts`
43
+
44
+ If the installed package is missing enough detail, use the GitHub package docs next:
45
+
46
+ - `https://github.com/joktec/joktec-framework/tree/main/packages/databases/mysql`
47
+
48
+ Use GitHub source only after package docs and installed types are not enough:
32
49
 
33
50
  - `packages/databases/mysql/src/decorators/table.decorator.ts`
34
51
  - `packages/databases/mysql/src/decorators/column.decorator.ts`
35
52
  - `packages/databases/mysql/src/decorators/columns/column.type.ts`
36
53
  - `packages/databases/mysql/src/decorators/columns/column.factory.ts`
37
54
  - `packages/databases/mysql/src/decorators/columns/primary.column.ts`
55
+ - `packages/databases/mysql/src/decorators/columns/timestamp.column.ts`
56
+ - `packages/databases/mysql/src/decorators/columns/virtual.column.ts`
57
+ - `packages/databases/mysql/src/decorators/columns/object.column.ts`
38
58
  - `packages/databases/mysql/src/decorators/columns/string.column.ts`
39
59
  - `packages/databases/mysql/src/decorators/columns/number.column.ts`
40
60
  - `packages/databases/mysql/src/decorators/columns/transform.column.ts`
@@ -42,7 +62,7 @@ When blocked, inspect:
42
62
 
43
63
  ## Schema-First Entity Pattern
44
64
 
45
- Use `@Tables`, `@Column`, and `@PrimaryColumn` from `@joktec/mysql` when an entity should also act as the source class for mapped DTOs.
65
+ Use `@Tables`, `@Column`, `@PrimaryColumn`, and `@TimestampColumn` from `@joktec/mysql` when an entity should also act as the source class for mapped DTOs.
46
66
 
47
67
  The new decorators are not thin TypeORM aliases. They are schema-first wrappers that compose:
48
68
 
@@ -51,11 +71,19 @@ The new decorators are not thin TypeORM aliases. They are schema-first wrappers
51
71
  - `class-transformer` expose/exclude behavior.
52
72
  - Swagger property metadata.
53
73
 
54
- When migrating old entities, remove duplicate property decorators from `typeorm`, `class-validator`, `class-transformer`, and Swagger when the wrapper option can represent the same behavior.
74
+ The wrapper can also represent virtual computed getters and nested JSON/jsonb class payloads. Do not use this package for Mongo/ObjectId columns.
75
+
76
+ Wrapper philosophy:
77
+
78
+ - prefer one schema declaration that carries persistence, validation, transform, and Swagger metadata
79
+ - use wrapper options before duplicating `@ApiProperty`, `@Expose`, `@Type`, or common validators
80
+ - do not add `swagger.type` for normal scalar/date fields, arrays, nested JSON classes, or relations when the wrapper can infer the shape
81
+ - use raw TypeORM only for advanced cases that the wrapper does not model cleanly
82
+ - keep storage write behavior and API documentation behavior distinct when needed
55
83
 
56
- ## Legacy Decorator Migration
84
+ ## Current Decorator Capabilities
57
85
 
58
- Migrate a whole property at a time. Do not only replace `PrimaryGeneratedColumn`.
86
+ Use the package README and actual installed source for full migration details. This skill only keeps the common mappings that help an agent recognize old patterns.
59
87
 
60
88
  Common mappings:
61
89
 
@@ -64,11 +92,21 @@ Common mappings:
64
92
  | `@PrimaryGeneratedColumn()` | `@PrimaryColumn('increment')` |
65
93
  | `@PrimaryGeneratedColumn('uuid')` | `@PrimaryColumn('uuid')` |
66
94
  | app-generated ordered UUID id | `@PrimaryColumn('uuidv7')` |
95
+ | `@CreateDateColumn(...)` | `@TimestampColumn('create', ...)` |
96
+ | `@UpdateDateColumn(...)` | `@TimestampColumn('update', ...)` |
97
+ | `@DeleteDateColumn(...)` | `@TimestampColumn('delete', ...)` |
98
+ | TypeORM `@VersionColumn(...)` | `@Column({ kind: 'version', ... })` |
99
+ | TypeORM `@VirtualColumn(...)` | `@Column({ kind: 'virtual', mode: 'sql', query, ... })` |
100
+ | TypeORM `@ViewColumn(...)` | `@Column({ kind: 'view', ... })` |
67
101
  | `@Column(...)` | `@Column(...)` from `@joktec/mysql` |
102
+ | `@RelationId(...)` | `@Column({ kind: 'relation-id', relationId })` |
68
103
  | `@IsNotEmpty()` | `@Column({ required: true })` |
69
104
  | `@IsOptional()` | `@Column({ required: false })` or nullable TypeORM option when storage allows null |
70
105
  | `@IsEmail()` | `@Column({ isEmail: true })` |
71
106
  | `@IsMobilePhone()` | `@Column({ isPhone: true })` |
107
+ | `@IsInt()` | `@Column({ isInt: true })` or an integer column type |
108
+ | `@IsUUID()` | `@Column({ isUUID: true })` |
109
+ | `@IsObject()` | `@Column({ isObject: true })` or a JSON column |
72
110
  | `@IsHexColor()` | `@Column({ isHexColor: true })` |
73
111
  | `@IsUrl()` | `@Column({ isUrl: true })` |
74
112
  | `@MinLength(n)` | `@Column({ minLength: n })` |
@@ -78,54 +116,49 @@ Common mappings:
78
116
  | `@Expose()` | default behavior of `@Column(...)` |
79
117
  | `@Expose({ groups })` | `@Column({ groups })` |
80
118
  | `@Exclude({ toPlainOnly: true })` plus hidden Swagger | `@Column({ hidden: true })` |
81
- | `@ApiProperty(...)` | `@Column({ swagger: ... })`, or native options such as `example`, `comment`, `deprecated`, `min`, `max`, `minLength`, `maxLength` |
82
-
83
- Preserve decorators only when the wrapper cannot express them, by passing them through `decorators: [...]`.
84
-
85
- Migration checklist:
86
-
87
- - Replace TypeORM column decorators with wrappers from `@joktec/mysql`.
88
- - Remove duplicate `class-validator` decorators when equivalent wrapper options exist.
89
- - Remove duplicate `class-transformer` decorators when `hidden` or `groups` expresses the same behavior.
90
- - Move Swagger examples/descriptions/limits into wrapper options where possible.
91
- - Preserve custom validators/transforms only through `decorators: [...]`.
92
- - Keep database-specific options such as `type`, `length`, `nullable`, `unique`, `default`, `enum`, and `comment`.
93
- - Rebuild and run entity-related tests after migration because DTO metadata and TypeORM metadata both change.
94
-
95
- Example migration:
96
-
97
- ```ts
98
- // Before
99
- @Column({ type: 'varchar', length: 255 })
100
- @IsEmail()
101
- @IsNotEmpty()
102
- @Expose()
103
- @ApiProperty({ example: 'user@example.com' })
104
- email!: string;
105
-
106
- // After
107
- @Column('varchar', {
108
- length: 255,
109
- required: true,
110
- isEmail: true,
111
- example: 'user@example.com',
112
- })
113
- email!: string;
114
- ```
115
-
116
- For hidden fields:
117
-
118
- ```ts
119
- // Before
120
- @Column({ type: 'varchar', length: 255 })
121
- @Exclude({ toPlainOnly: true })
122
- @ApiHideProperty()
123
- password!: string;
124
-
125
- // After
126
- @Column('varchar', { length: 255, hidden: true })
127
- password!: string;
128
- ```
119
+ | `@ApiProperty(...)` | Prefer native options such as `example`, `comment`, `deprecated`, `min`, `max`, `minLength`, `maxLength`; use `swagger` only as an override |
120
+ | `@ValidateNested()` + `@Type(() => Preference)` | `@Column('jsonb', { nested: Preference })` |
121
+ | `@ValidateNested({ each: true })` + `@Type(() => Preference)` | `@Column('jsonb', { nested: Preference, each: true })` |
122
+ | `@Expose()` + `@ApiProperty(...)` on a getter | `@Column({ kind: 'virtual', ... })` |
123
+ | Swagger `readOnly: true` | `@Column({ immutable: true })` or TypeORM `update: false` when ORM updates must also be blocked |
124
+
125
+ ## Swagger Metadata Rules
126
+
127
+ The `@Column` wrapper already composes Swagger metadata. During migrations, keep entity code small and avoid redundant `swagger` declarations:
128
+
129
+ - Do not add `swagger: { type: String }` for string columns.
130
+ - Do not add `swagger: { type: Number }` for numeric columns.
131
+ - Do not add `swagger: { type: Boolean }` for boolean columns.
132
+ - Do not add `swagger: { type: Date }` for date, datetime, or timestamp columns.
133
+ - Do not add `swagger: { type: String, isArray: true }` for `simple-array` or reflected array fields unless the OpenAPI shape must differ from the entity field.
134
+ - Do not add `swagger: { type: NestedClass }` when `nested: NestedClass` is already present.
135
+ - Do not add `swagger: { type: () => Entity }` on `Column({ kind: 'relation', type: () => Entity })`; the relation wrapper keeps the Swagger type lazy to avoid circular schema evaluation.
136
+
137
+ Use `swagger` only for actual overrides, for example:
138
+
139
+ - an OpenAPI primitive differs from the TypeScript property type, such as a SQL decimal represented as `string`
140
+ - a property needs `oneOf`, `anyOf`, `allOf`, custom `items`, or a deliberately shortened example
141
+ - a generated schema needs an explicit read/write/deprecated override that cannot be represented by wrapper options
142
+
143
+ If a relation wrapper still triggers a circular Swagger error in a consumer project, inspect `node_modules/@joktec/mysql/dist/decorators/column.decorator.d.ts` and the installed implementation first. Do not paper over the issue by adding `swagger.type` to every relation; identify whether the installed package version has lazy relation Swagger support.
144
+
145
+ ## Read-Only Metadata
146
+
147
+ `immutable` is the API read-only hint used by the JokTec MySQL wrapper. TypeORM `update: false` is the ORM write behavior. The wrapper maps both to Swagger `readOnly` when appropriate:
148
+
149
+ - `immutable` has priority over `update: false`
150
+ - `update: false` implies Swagger `readOnly` only when `immutable` is not set
151
+ - `swagger.readOnly` remains the final explicit override
152
+
153
+ Some field kinds default to API read-only because they are system-managed or computed:
154
+
155
+ - primary keys
156
+ - timestamp columns
157
+ - version columns
158
+ - view columns
159
+ - virtual getter and SQL virtual columns
160
+ - relation-id columns
161
+ - tree level columns
129
162
 
130
163
  ## Primary Keys
131
164
 
@@ -146,7 +179,21 @@ The stable dialects are MySQL, MariaDB, and Postgres. Dialect capabilities own d
146
179
 
147
180
  ## Source Lookup
148
181
 
149
- When blocked, inspect:
182
+ When blocked in a consumer project, inspect installed package docs and types first:
183
+
184
+ - `node_modules/@joktec/mysql/README.md`
185
+ - `node_modules/@joktec/mysql/AGENTS.md` when published with the package
186
+ - `node_modules/@joktec/mysql/dist/index.d.ts`
187
+ - `node_modules/@joktec/mysql/dist/mysql.module.d.ts`
188
+ - `node_modules/@joktec/mysql/dist/mysql.service.d.ts`
189
+ - `node_modules/@joktec/mysql/dist/mysql.repo.d.ts`
190
+ - `node_modules/@joktec/mysql/dist/models/mysql.request.d.ts`
191
+
192
+ If the installed package is insufficient, read GitHub package docs next:
193
+
194
+ - `https://github.com/joktec/joktec-framework/tree/main/packages/databases/mysql`
195
+
196
+ Use GitHub source only after installed types and package docs are not enough:
150
197
 
151
198
  - `packages/databases/mysql/README.md`
152
199
  - `packages/databases/mysql/AGENTS.md`
@@ -47,6 +47,7 @@ Best practice:
47
47
  - Use the package service for outbound HTTP so retry/proxy/metrics behavior stays centralized.
48
48
  - Keep external endpoint URLs and credentials in runtime config.
49
49
  - Be careful with ESM/CommonJS import changes in HTTP/Axios ecosystem packages.
50
+ - `HttpService.buildAgent(proxy, opts)` expects proxy identity in `HttpProxyConfig` and agent tuning in Node `AgentOptions`; inspect the installed source before adapting to proxy-agent major-version changes.
50
51
  - Test request behavior with mocks unless the test is an explicit consumer integration scenario.
51
52
 
52
53
  ## File
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joktec/skills",
3
- "version": "0.1.4",
3
+ "version": "0.1.8",
4
4
  "private": false,
5
5
  "description": "Hybrid agent skill pack for using @joktec/* libraries in consumer projects.",
6
6
  "license": "MIT",
@@ -47,7 +47,10 @@
47
47
  "skills"
48
48
  ],
49
49
  "scripts": {
50
- "check": "node scripts/validate-skills.mjs && node scripts/sync-from-joktec-framework.mjs --check",
50
+ "sync:version": "node scripts/sync-pack-version.mjs",
51
+ "check:version": "node scripts/sync-pack-version.mjs --check",
52
+ "version": "node scripts/sync-pack-version.mjs --stage",
53
+ "check": "pnpm run check:version && node scripts/validate-skills.mjs && node scripts/sync-from-joktec-framework.mjs --check",
51
54
  "validate": "node scripts/validate-skills.mjs",
52
55
  "build": "node scripts/build-skill-folders.mjs && node scripts/build-cursor-rules.mjs && node scripts/build-gemini-md.mjs && node scripts/build-copilot-instructions.mjs && node scripts/build-windsurf-rules.mjs",
53
56
  "build:skills": "node scripts/build-skill-folders.mjs",
@@ -58,7 +61,7 @@
58
61
  "sync:check": "node scripts/sync-from-joktec-framework.mjs --check",
59
62
  "pack:check": "pnpm pack --dry-run",
60
63
  "prepublish:check": "pnpm run build && pnpm run check && pnpm pack --dry-run",
61
- "publish:dry-run": "pnpm run prepublish:check && pnpm publish --dry-run --no-git-checks --access public",
64
+ "publish:dry-run": "pnpm run prepublish:check && pnpm publish --dry-run --access public",
62
65
  "publish:registry": "pnpm run prepublish:check && pnpm publish --access public",
63
66
  "release:patch": "pnpm version patch && pnpm run publish:registry",
64
67
  "release:minor": "pnpm version minor && pnpm run publish:registry",
@@ -0,0 +1,38 @@
1
+ import path from 'node:path';
2
+ import { execFileSync } from 'node:child_process';
3
+ import { PACK_PATH, ROOT, readJson, writeFile } from './lib.mjs';
4
+
5
+ const args = new Set(process.argv.slice(2));
6
+ const checkOnly = args.has('--check');
7
+ const stage = args.has('--stage');
8
+ const packagePath = path.join(ROOT, 'package.json');
9
+
10
+ const pkg = readJson(packagePath);
11
+ const pack = readJson(PACK_PATH);
12
+ const version = pkg.version;
13
+
14
+ if (!/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(version || '')) {
15
+ console.error(`Invalid package.json version: ${version || '<missing>'}`);
16
+ process.exit(1);
17
+ }
18
+
19
+ function stagePackFile() {
20
+ execFileSync('git', ['add', PACK_PATH], { cwd: ROOT, stdio: 'inherit' });
21
+ console.log('Staged skill-pack.json');
22
+ }
23
+
24
+ if (pack.version === version) {
25
+ console.log(`skill-pack.json version is in sync: ${version}`);
26
+ if (stage) stagePackFile();
27
+ process.exit(0);
28
+ }
29
+
30
+ if (checkOnly) {
31
+ console.error(`Version mismatch: package.json=${version}, skill-pack.json=${pack.version || '<missing>'}`);
32
+ process.exit(1);
33
+ }
34
+
35
+ pack.version = version;
36
+ writeFile(PACK_PATH, JSON.stringify(pack, null, 2));
37
+ console.log(`Updated skill-pack.json version to ${version}`);
38
+ if (stage) stagePackFile();
package/skill-pack.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joktec/skills",
3
- "version": "0.1.2",
3
+ "version": "0.1.8",
4
4
  "sourceOfTruth": "../joktec-framework",
5
5
  "frameworkBaseline": {
6
6
  "repo": "https://github.com/joktec/joktec-framework",
@@ -350,6 +350,40 @@
350
350
  "copilot": true,
351
351
  "windsurf": true
352
352
  }
353
+ },
354
+ {
355
+ "id": "advanced-typescript-design",
356
+ "title": "Advanced TypeScript Design",
357
+ "role": "focused",
358
+ "requiredByDefault": false,
359
+ "dependencies": [],
360
+ "recommended": [],
361
+ "packages": [
362
+ "TypeScript",
363
+ "NestJS"
364
+ ],
365
+ "scope": {
366
+ "paths": [
367
+ "**/*.ts",
368
+ "**/*.tsx"
369
+ ]
370
+ },
371
+ "triggers": [
372
+ "typescript",
373
+ "generic public APIs",
374
+ "conditional types",
375
+ "decorator metadata",
376
+ "type-safe query DSL",
377
+ "design patterns"
378
+ ],
379
+ "outputs": {
380
+ "codex": true,
381
+ "claude": true,
382
+ "cursor": true,
383
+ "gemini": true,
384
+ "copilot": true,
385
+ "windsurf": true
386
+ }
353
387
  }
354
388
  ]
355
389
  }
@@ -0,0 +1,60 @@
1
+ ---
2
+ name: advanced-typescript-design
3
+ description: 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
+
6
+ # Advanced TypeScript Design
7
+
8
+ ## Overview
9
+
10
+ Act as a TypeScript architecture partner. Choose the simplest design that preserves clear boundaries, runtime correctness, and useful compile-time guarantees.
11
+
12
+ 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.
13
+
14
+ ## Architectural Mindset
15
+
16
+ - Start from the domain boundary: identify entity, request/response, service, repository, client, decorator, loader, and integration responsibilities.
17
+ - Keep public APIs narrow and stable. Make extension explicit through interfaces, abstract classes, generic constraints, or composition.
18
+ - Use classes when lifecycle, inheritance hooks, decorators, or framework reflection matter. Use plain functions/types when behavior is stateless or purely transformational.
19
+ - Let runtime validation and compile-time types reinforce each other. Do not pretend TypeScript types validate untrusted runtime data.
20
+ - Do not assume TypeScript generics, interfaces, unions, or array element types exist at runtime through `reflect-metadata`.
21
+ - Escalate type complexity only when it removes real duplication, prevents invalid states, or makes an API substantially safer.
22
+ - Check existing code before inventing a new pattern; mirror the repository's style when it already solves the same class of problem.
23
+
24
+ ## Public API Compatibility
25
+
26
+ - Treat exported types, classes, decorators, config objects, modules, and provider APIs as public contracts.
27
+ - Prefer additive changes over breaking renames, deleted fields, changed generic parameter order, or narrower accepted input shapes.
28
+ - Before changing exported generic types, check downstream inference from normal call sites and verify that common extension patterns still compile.
29
+ - If a breaking type or runtime contract change is unavoidable, report migration impact explicitly and include the smallest migration path.
30
+
31
+ ## Pattern Vocabulary
32
+
33
+ Use the classic catalog as shared language, including the TypeScript examples catalog from Refactoring.Guru.
34
+
35
+ - Creational Patterns: Abstract Factory, Builder, Factory Method, Prototype, Singleton.
36
+ - Structural Patterns: Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy.
37
+ - Behavioral Patterns: Chain of Responsibility, Iterator, Memento, State, Template Method, Command, Mediator, Observer, Strategy, Visitor.
38
+
39
+ 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.
40
+
41
+ ## Agent Workflow
42
+
43
+ 1. Inspect local code first when working inside a repository. Look for existing abstractions, decorators, DTO types, factory functions, lifecycle hooks, and tests.
44
+ 2. Classify the task:
45
+ - Use `references/simple.md` for everyday TypeScript, OOP, data modeling, classes, interfaces, types, records, maps, arrays, simple decorators, and pragmatic refactors.
46
+ - 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.
47
+ 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.
48
+ 4. Design the public surface before implementation: inputs, outputs, extension points, error behavior, lifecycle, and type inference experience.
49
+ 5. Implement incrementally. Keep runtime behavior testable, and add focused type-level checks when exported generic or decorator behavior is subtle.
50
+ 6. Review for overengineering: remove unused generic parameters, speculative base classes, unnecessary inheritance, and type utilities that do not protect a real API.
51
+
52
+ ## Repository Signals
53
+
54
+ In JokTec-style TypeScript, expect patterns such as:
55
+
56
+ - Generic request/query types with recursive conditions and sort/populate typing.
57
+ - Factory functions that return decorated NestJS classes.
58
+ - Abstract services and clients with template methods for lifecycle-specific behavior.
59
+ - Decorator factories that compose validation, Swagger, transformation, metrics, and integration metadata.
60
+ - Loader/registry patterns that collect decorator metadata and wire runtime behavior during module initialization.
@@ -0,0 +1,4 @@
1
+ interface:
2
+ display_name: "Advanced TypeScript Design"
3
+ short_description: "Design advanced TypeScript APIs"
4
+ default_prompt: "Use $advanced-typescript-design to design or refactor TypeScript framework code with an appropriate type-safety and pattern level."
@@ -0,0 +1,219 @@
1
+ # Advanced TypeScript Design Guidance
2
+
3
+ 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.
4
+
5
+ ## Escalation Criteria
6
+
7
+ Reach for advanced TypeScript only when at least one is true:
8
+
9
+ - The API is reused widely and type inference prevents real misuse.
10
+ - The runtime model is already generic, recursive, or metadata-driven.
11
+ - The abstraction eliminates repeated boilerplate across many entities, DTOs, repositories, services, clients, or transports.
12
+ - The type-level design mirrors a stable domain contract, not a speculative future.
13
+ - Tests or examples can prove both runtime behavior and developer ergonomics.
14
+
15
+ If the advanced type exists only to feel clever, delete it.
16
+
17
+ ## Infer, Conditional, and Deferred Types
18
+
19
+ - Use `infer` to extract return types, payloads, entity types, DTO shapes, tuple elements, and callback signatures from source contracts.
20
+ - Control distributive conditional types intentionally. Wrap operands in tuples, such as `[T] extends [U]`, when union distribution is not wanted.
21
+ - Prefer named intermediate aliases when nested conditionals exceed two branches.
22
+ - Use `never` as a filter, but verify that it cannot erase useful error information from public APIs.
23
+ - Treat deferred conditional types and generic inference as public UX: callers should get helpful autocomplete and errors without manual type arguments.
24
+
25
+ ## Recursive and Mapped Types
26
+
27
+ - Use recursive mapped types for query languages, nested sort/select/populate APIs, deep partials, and entity graph traversal.
28
+ - Add clear stop conditions for primitives, dates, arrays, functions, and branded values.
29
+ - 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.
30
+ - Avoid infinite or overly expensive type recursion. Keep recursion shallow enough for editor performance.
31
+ - Preserve optionality and readonly modifiers intentionally with `+?`, `-?`, `readonly`, and `-readonly`.
32
+ - Separate query operator typing from entity typing so the operator model remains testable and reusable.
33
+
34
+ ## Reflection and Decorators
35
+
36
+ - Use `reflect-metadata` only when runtime type information materially improves the API: schema generation, validation composition, serialization, dependency injection, or loader registration.
37
+ - Remember that reflected TypeScript types are lossy at runtime. Arrays, unions, generics, and interfaces need explicit options or factories.
38
+ - Prefer decorator factories that normalize options, resolve type factories, compose framework decorators, and define one clear metadata contract.
39
+ - 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.
40
+ - For method decorators, preserve `this`, return values, thrown errors, and async behavior unless the decorator explicitly changes them.
41
+ - 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.
42
+ - Test decorator behavior through a class that uses it, especially for metadata, wrapping behavior, and dependency injection.
43
+
44
+ ## Type-Level Verification
45
+
46
+ - Add type-level tests when changing exported generic utilities, query DSLs, decorators, builders, or public inference-heavy APIs.
47
+ - 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.
48
+ - Include positive inference examples from normal call sites, not only explicit generic arguments.
49
+ - Include negative examples with `@ts-expect-error` when an invalid state must stay rejected.
50
+ - Verify runtime tests separately when decorators, reflection metadata, validation, transformation, or loaders are involved.
51
+
52
+ ## Expert Pattern Selection
53
+
54
+ - Abstract Factory fits families of related clients, repositories, or transport adapters that must be created consistently.
55
+ - Builder fits fluent configuration with required-step guarantees; type-state builders can enforce completeness but should stay readable.
56
+ - Factory Method fits framework hooks that create DTOs, pagination wrappers, controllers, or provider instances.
57
+ - Prototype fits cloning configured objects when construction is expensive or stateful.
58
+ - Singleton should usually be delegated to the DI container; avoid hand-rolled global state.
59
+ - Adapter fits third-party client normalization and migration layers.
60
+ - Bridge fits separating abstraction from implementation, such as transport-agnostic messaging APIs over Rabbit, Kafka, or Redis.
61
+ - Composite fits tree-shaped filters, pipelines, menu/routes, or nested query conditions.
62
+ - Decorator fits metrics, retries, circuit breakers, serialization, validation, or publishing side effects around existing behavior.
63
+ - Facade fits a stable service hiding multiple low-level collaborators.
64
+ - Flyweight fits large repeated metadata or schema objects only after measuring memory pressure.
65
+ - Proxy fits lazy clients, caching, access control, retries, and remote boundaries.
66
+ - Chain of Responsibility fits validation, middleware, parsing, and request pipelines.
67
+ - Command fits queued work, replayable operations, and undoable actions.
68
+ - Iterator fits cursor pagination and collection traversal without exposing storage details.
69
+ - Mediator fits module coordination where direct dependencies would become tangled.
70
+ - Memento fits snapshots, rollbacks, and state restoration.
71
+ - Observer fits event streams and pub/sub, with explicit unsubscribe and error policy.
72
+ - State fits lifecycle-heavy clients, jobs, or connections with mode-specific behavior.
73
+ - Strategy fits interchangeable algorithms selected by config or runtime context.
74
+ - Template Method fits abstract base services/clients that own lifecycle while subclasses implement `init`, `start`, `stop`, `validate`, or `transform` steps.
75
+ - Visitor fits operations over stable object structures when adding new operations is more common than adding new node types.
76
+
77
+ ## Symbolic Examples
78
+
79
+ Use examples like these as compact templates for thinking. Keep production implementations smaller or larger depending on the actual force.
80
+
81
+ ### Type-Safe Event Map
82
+
83
+ ```typescript
84
+ type EventMap = {
85
+ "user.created": { id: string };
86
+ "invoice.paid": { invoiceId: string; amount: number };
87
+ };
88
+
89
+ class EventBus<TEvents extends Record<string, unknown>> {
90
+ on<K extends keyof TEvents>(event: K, handler: (payload: TEvents[K]) => void) {}
91
+ emit<K extends keyof TEvents>(event: K, payload: TEvents[K]) {}
92
+ }
93
+
94
+ const bus = new EventBus<EventMap>();
95
+ bus.emit("invoice.paid", { invoiceId: "inv_1", amount: 100 });
96
+ ```
97
+
98
+ Use this for Observer/Mediator-style APIs where event names and payloads must stay coupled.
99
+
100
+ ### API Contract Inference
101
+
102
+ ```typescript
103
+ type Endpoint = {
104
+ "/users/:id": {
105
+ GET: { params: { id: string }; response: User };
106
+ PATCH: { params: { id: string }; body: Partial<User>; response: User };
107
+ };
108
+ };
109
+
110
+ type ResponseOf<T> = T extends { response: infer R } ? R : never;
111
+
112
+ class ApiClient<TContract extends Record<string, any>> {
113
+ request<Path extends keyof TContract, Method extends keyof TContract[Path]>(
114
+ path: Path,
115
+ method: Method,
116
+ ): Promise<ResponseOf<TContract[Path][Method]>> {
117
+ return null as any;
118
+ }
119
+ }
120
+ ```
121
+
122
+ Use this when a contract object should drive call-site inference.
123
+
124
+ ### Type-State Builder
125
+
126
+ ```typescript
127
+ type With<K extends string> = Record<K, true>;
128
+
129
+ class JobBuilder<State = {}> {
130
+ queue(name: string): JobBuilder<State & With<"queue">> {
131
+ return this as any;
132
+ }
133
+
134
+ handler(fn: () => Promise<void>): JobBuilder<State & With<"handler">> {
135
+ return this as any;
136
+ }
137
+
138
+ build(this: State extends With<"queue"> & With<"handler"> ? JobBuilder<State> : never) {
139
+ return {};
140
+ }
141
+ }
142
+ ```
143
+
144
+ Use this when incomplete configuration is common and worth rejecting at compile time.
145
+
146
+ ### Recursive Query Shape
147
+
148
+ ```typescript
149
+ type Primitive = string | number | boolean | Date;
150
+ type FieldOp<T> = T | { $eq?: T; $in?: T[] };
151
+ type Brand<T, Name extends string> = T & { readonly __brand: Name };
152
+ type ObjectId = Brand<string, "ObjectId">;
153
+
154
+ type Query<T> = {
155
+ [K in keyof T]?: T[K] extends Primitive
156
+ ? FieldOp<T[K]>
157
+ : T[K] extends Array<infer U>
158
+ ? Query<U>
159
+ : Query<T[K]>;
160
+ } & {
161
+ $or?: Query<T>[];
162
+ };
163
+ ```
164
+
165
+ Use this for Composite-style nested filters, but add stop conditions before expanding it.
166
+
167
+ ### Opaque ID Boundary
168
+
169
+ ```typescript
170
+ type Brand<T, Name extends string> = T & { readonly __brand: Name };
171
+ type UserId = Brand<string, "UserId">;
172
+ type PostId = Brand<string, "PostId">;
173
+
174
+ function asUserId(value: string): UserId {
175
+ return value as UserId;
176
+ }
177
+
178
+ function findUser(id: UserId) {}
179
+
180
+ findUser(asUserId("u_1"));
181
+ // @ts-expect-error raw strings are not accepted here
182
+ findUser("u_1");
183
+ ```
184
+
185
+ Use this when a domain primitive crosses many generic/query layers and accidental mixing would be costly.
186
+
187
+ ### Decorator Wrapper with Preserved Method Contract
188
+
189
+ ```typescript
190
+ function Around(run: (next: () => unknown) => unknown): MethodDecorator {
191
+ return (_, __, descriptor) => {
192
+ const original = descriptor.value;
193
+
194
+ descriptor.value = function (...args: unknown[]) {
195
+ return run(() => original.apply(this, args));
196
+ };
197
+ };
198
+ }
199
+ ```
200
+
201
+ Use this for metrics, retry, logging, or publishing side effects; preserve `this`, args, return values, and thrown errors.
202
+
203
+ ## JokTec-Style Signals to Reuse
204
+
205
+ - Recursive query typing can combine entity properties with operator unions, nested entity traversal, and logical `$or`/`$and` shapes.
206
+ - Base services and clients commonly use Template Method: the base class owns lifecycle and shared behavior while subclasses provide specific implementation steps.
207
+ - Controller factories can return decorated classes to avoid repetitive NestJS endpoint scaffolding while preserving DTO-specific metadata.
208
+ - Decorator infrastructure often composes Swagger, validation, transformation, persistence, and metric behavior from one options object.
209
+ - Rabbit loaders show a metadata registry plus module-init loader pattern: decorators declare intent; loaders resolve providers and connect runtime consumers.
210
+
211
+ ## Advanced Review Checklist
212
+
213
+ - Does every generic parameter appear in the public contract or implementation?
214
+ - Can inference succeed from normal call-site arguments?
215
+ - Does the type-level model match runtime validation and transformation?
216
+ - Are metadata keys centralized and collision-resistant?
217
+ - Are decorator side effects documented by tests?
218
+ - Is editor performance acceptable after adding recursive or conditional types?
219
+ - Is there a simpler Strategy, Adapter, or function-based design that would provide the same value?