@autobe/agent 0.13.0 → 0.14.3

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 (78) hide show
  1. package/lib/AutoBeMockAgent.js +2 -1
  2. package/lib/AutoBeMockAgent.js.map +1 -1
  3. package/lib/constants/AutoBeSystemPromptConstant.d.ts +7 -9
  4. package/lib/constants/AutoBeSystemPromptConstant.js.map +1 -1
  5. package/lib/factory/getAutoBeGenerated.js +11 -1
  6. package/lib/factory/getAutoBeGenerated.js.map +1 -1
  7. package/lib/index.mjs +397 -240
  8. package/lib/index.mjs.map +1 -1
  9. package/lib/orchestrate/analyze/orchestrateAnalyzeComposer.js +6 -4
  10. package/lib/orchestrate/analyze/orchestrateAnalyzeComposer.js.map +1 -1
  11. package/lib/orchestrate/analyze/orchestrateAnalyzeWrite.d.ts +1 -1
  12. package/lib/orchestrate/analyze/orchestrateAnalyzeWrite.js.map +1 -1
  13. package/lib/orchestrate/analyze/structures/IAutoBeAnalyzeComposerApplication.d.ts +1 -1
  14. package/lib/orchestrate/analyze/transformAnalyzeWriteHistories.d.ts +1 -1
  15. package/lib/orchestrate/analyze/transformAnalyzeWriteHistories.js.map +1 -1
  16. package/lib/orchestrate/analyze/writeDocumentUntilReviewPassed.d.ts +1 -1
  17. package/lib/orchestrate/interface/orchestrateInterfaceComponents.js +1 -1
  18. package/lib/orchestrate/interface/orchestrateInterfaceComponents.js.map +1 -1
  19. package/lib/orchestrate/interface/orchestrateInterfaceEndpoints.js +1 -1
  20. package/lib/orchestrate/interface/orchestrateInterfaceEndpoints.js.map +1 -1
  21. package/lib/orchestrate/interface/orchestrateInterfaceOperations.js +107 -110
  22. package/lib/orchestrate/interface/orchestrateInterfaceOperations.js.map +1 -1
  23. package/lib/orchestrate/interface/transformInterfaceHistories.js +10 -0
  24. package/lib/orchestrate/interface/transformInterfaceHistories.js.map +1 -1
  25. package/lib/orchestrate/realize/orchestrateRealize.js +30 -8
  26. package/lib/orchestrate/realize/orchestrateRealize.js.map +1 -1
  27. package/lib/orchestrate/realize/{orchestrateRealizeDecorator.d.ts → orchestrateRealizeAuthorization.d.ts} +2 -2
  28. package/lib/orchestrate/realize/{orchestrateRealizeDecorator.js → orchestrateRealizeAuthorization.js} +104 -67
  29. package/lib/orchestrate/realize/orchestrateRealizeAuthorization.js.map +1 -0
  30. package/lib/orchestrate/realize/orchestrateRealizeCoder.js +51 -40
  31. package/lib/orchestrate/realize/orchestrateRealizeCoder.js.map +1 -1
  32. package/lib/orchestrate/realize/orchestrateRealizePlanner.d.ts +11 -2
  33. package/lib/orchestrate/realize/orchestrateRealizePlanner.js +2 -1
  34. package/lib/orchestrate/realize/orchestrateRealizePlanner.js.map +1 -1
  35. package/lib/orchestrate/realize/structures/IAutoBeRealizeCoderApplication.d.ts +148 -17
  36. package/lib/orchestrate/realize/structures/IAutoBeRealizeCompile.d.ts +10 -2
  37. package/lib/orchestrate/realize/structures/IAutoBeRealizeDecoratorApplication.d.ts +4 -4
  38. package/lib/orchestrate/realize/transformRealizeCoderHistories.js +58 -11
  39. package/lib/orchestrate/realize/transformRealizeCoderHistories.js.map +1 -1
  40. package/lib/orchestrate/realize/transformRealizeDecoratorCorrectHistories.d.ts +2 -3
  41. package/lib/orchestrate/realize/transformRealizeDecoratorCorrectHistories.js +15 -2
  42. package/lib/orchestrate/realize/transformRealizeDecoratorCorrectHistories.js.map +1 -1
  43. package/lib/orchestrate/realize/utils/AuthorizationFileSystem.d.ts +5 -0
  44. package/lib/orchestrate/realize/utils/AuthorizationFileSystem.js +10 -0
  45. package/lib/orchestrate/realize/utils/AuthorizationFileSystem.js.map +1 -0
  46. package/lib/orchestrate/realize/utils/replaceImportStatements.d.ts +3 -0
  47. package/lib/orchestrate/realize/utils/replaceImportStatements.js +65 -0
  48. package/lib/orchestrate/realize/utils/replaceImportStatements.js.map +1 -0
  49. package/lib/orchestrate/realize/writeCodeUntilCompilePassed.d.ts +2 -3
  50. package/lib/orchestrate/realize/writeCodeUntilCompilePassed.js +45 -24
  51. package/lib/orchestrate/realize/writeCodeUntilCompilePassed.js.map +1 -1
  52. package/package.json +5 -5
  53. package/src/AutoBeMockAgent.ts +3 -2
  54. package/src/constants/AutoBeSystemPromptConstant.ts +7 -9
  55. package/src/factory/getAutoBeGenerated.ts +20 -5
  56. package/src/orchestrate/analyze/orchestrateAnalyzeWrite.ts +1 -1
  57. package/src/orchestrate/analyze/structures/IAutoBeAnalyzeComposerApplication.ts +2 -1
  58. package/src/orchestrate/analyze/transformAnalyzeWriteHistories.ts +1 -1
  59. package/src/orchestrate/analyze/writeDocumentUntilReviewPassed.ts +1 -1
  60. package/src/orchestrate/interface/orchestrateInterfaceOperations.ts +26 -18
  61. package/src/orchestrate/interface/transformInterfaceHistories.ts +10 -0
  62. package/src/orchestrate/realize/orchestrateRealize.ts +32 -7
  63. package/src/orchestrate/realize/{orchestrateRealizeDecorator.ts → orchestrateRealizeAuthorization.ts} +90 -80
  64. package/src/orchestrate/realize/orchestrateRealizeCoder.ts +9 -30
  65. package/src/orchestrate/realize/orchestrateRealizePlanner.ts +13 -1
  66. package/src/orchestrate/realize/structures/IAutoBeRealizeCoderApplication.ts +150 -17
  67. package/src/orchestrate/realize/structures/IAutoBeRealizeCompile.ts +13 -2
  68. package/src/orchestrate/realize/structures/IAutoBeRealizeDecoratorApplication.ts +4 -4
  69. package/src/orchestrate/realize/transformRealizeCoderHistories.ts +55 -8
  70. package/src/orchestrate/realize/transformRealizeDecoratorCorrectHistories.ts +23 -3
  71. package/src/orchestrate/realize/utils/AuthorizationFileSystem.ts +10 -0
  72. package/src/orchestrate/realize/utils/replaceImportStatements.ts +85 -0
  73. package/src/orchestrate/realize/writeCodeUntilCompilePassed.ts +58 -33
  74. package/lib/orchestrate/analyze/AutoBeAnalyzeRole.d.ts +0 -13
  75. package/lib/orchestrate/analyze/AutoBeAnalyzeRole.js +0 -3
  76. package/lib/orchestrate/analyze/AutoBeAnalyzeRole.js.map +0 -1
  77. package/lib/orchestrate/realize/orchestrateRealizeDecorator.js.map +0 -1
  78. package/src/orchestrate/analyze/AutoBeAnalyzeRole.ts +0 -14
package/lib/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { AgenticaTokenUsage, MicroAgentica } from "@agentica/core";
2
2
 
3
- import { hash, HashSet, HashMap, Pair, Semaphore, Singleton, sleep_for } from "tstl";
3
+ import { hash, HashSet, HashMap, Pair, Semaphore, Singleton, sleep_for, randint } from "tstl";
4
4
 
5
5
  import { v4 } from "uuid";
6
6
 
@@ -40,7 +40,16 @@ async function getAutoBeGenerated(compiler, state, histories, tokenUsage, option
40
40
  });
41
41
  }
42
42
  if (state.test?.step === state.analyze.step) Object.assign(ret, Object.fromEntries(state.test.files.map((f => [ f.location, f.content ]))), await compiler.test.getTemplate());
43
- if (state.realize?.step === state.analyze.step) Object.assign(ret, state.realize.files, await compiler.realize.getTemplate());
43
+ if (state.realize?.step === state.analyze.step) Object.assign(ret, {
44
+ ...Object.fromEntries(state.realize.functions.map((f => [ f.location, f.content ]))),
45
+ ...Object.fromEntries(state.realize.authorizations.map((auth => [ [ auth.decorator.location, auth.decorator.content ], [ auth.provider.location, auth.provider.content ], [ auth.payload.location, auth.payload.content ] ])).flat()),
46
+ ...await compiler.realize.getTemplate(),
47
+ ...await compiler.realize.controller({
48
+ document: state.interface.document,
49
+ functions: state.realize.functions,
50
+ authorizations: state.realize.authorizations
51
+ })
52
+ });
44
53
  Object.assign(ret, {
45
54
  "autobe/histories.json": JSON.stringify(histories),
46
55
  "autobe/tokenUsage.json": JSON.stringify(tokenUsage)
@@ -282,14 +291,15 @@ const claude$e = {
282
291
  additionalProperties: false,
283
292
  $defs: {
284
293
  AutoBeAnalyzeRole: {
294
+ description: "Interface representing a user role definition in the requirements analysis\nphase.\n\nThis interface defines authenticated user roles that will be used throughout\nthe application's authentication and authorization system. Each role\nrepresents a distinct type of user who can register, authenticate, and\ninteract with the system based on their specific permissions and\ncapabilities.\n\nThe roles defined here serve as the foundation for generating:\n\n- Prisma schema models for user authentication tables\n- API endpoint access control decorators\n- Role-based authorization logic in the business layer\n- Test scenarios for different user permission levels",
285
295
  type: "object",
286
296
  properties: {
287
297
  name: {
288
- description: "Role name representing user types that can authenticate via API. These are\nuser roles that can register and login to the service. This will be used as\nreference when creating Prisma schema for user authentication.",
298
+ description: 'Unique identifier for the user role.\n\nThis name will be used as a reference throughout the generated codebase,\nincluding Prisma schema model names, authorization decorator parameters,\nand API documentation. Examples: "customer", "admin", "seller",\n"moderator".',
289
299
  type: "string"
290
300
  },
291
301
  description: {
292
- description: "Description of what this user role can do in the system. Describes the\npermissions and capabilities of this authenticated user type.",
302
+ description: "Human-readable description of the role's permissions and capabilities.\n\nThis description helps the AI agents understand the business context and\naccess requirements for each role, guiding the generation of appropriate\nauthorization rules and API endpoint restrictions.",
293
303
  type: "string"
294
304
  }
295
305
  },
@@ -496,14 +506,15 @@ const collection$e = {
496
506
  additionalProperties: false,
497
507
  $defs: {
498
508
  AutoBeAnalyzeRole: {
509
+ description: "Interface representing a user role definition in the requirements analysis\nphase.\n\nThis interface defines authenticated user roles that will be used throughout\nthe application's authentication and authorization system. Each role\nrepresents a distinct type of user who can register, authenticate, and\ninteract with the system based on their specific permissions and\ncapabilities.\n\nThe roles defined here serve as the foundation for generating:\n\n- Prisma schema models for user authentication tables\n- API endpoint access control decorators\n- Role-based authorization logic in the business layer\n- Test scenarios for different user permission levels",
499
510
  type: "object",
500
511
  properties: {
501
512
  name: {
502
- description: "Role name representing user types that can authenticate via API. These are\nuser roles that can register and login to the service. This will be used as\nreference when creating Prisma schema for user authentication.",
513
+ description: 'Unique identifier for the user role.\n\nThis name will be used as a reference throughout the generated codebase,\nincluding Prisma schema model names, authorization decorator parameters,\nand API documentation. Examples: "customer", "admin", "seller",\n"moderator".',
503
514
  type: "string"
504
515
  },
505
516
  description: {
506
- description: "Description of what this user role can do in the system. Describes the\npermissions and capabilities of this authenticated user type.",
517
+ description: "Human-readable description of the role's permissions and capabilities.\n\nThis description helps the AI agents understand the business context and\naccess requirements for each role, guiding the generation of appropriate\nauthorization rules and API endpoint restrictions.",
507
518
  type: "string"
508
519
  }
509
520
  },
@@ -1418,7 +1429,7 @@ const transformInterfaceHistories = (state, systemMessage) => {
1418
1429
  id: v4(),
1419
1430
  created_at: (new Date).toISOString(),
1420
1431
  type: "assistantMessage",
1421
- text: [ "Database schema and entity relationship diagrams are ready.", "You should also look at this and consider logic including membership/login and token issuance.", "You can use table's name to define role in operations.", "", "## Prisma DB Schema", "```json", JSON.stringify(state.prisma.schemas), "```", "", "## Entity Relationship Diagrams", "```json", JSON.stringify(state.prisma.compiled.diagrams), "```" ].join("\n")
1432
+ text: [ "Database schema and entity relationship diagrams are ready.", "You should also look at this and consider logic including membership/login and token issuance.", "You can use table's name to define role in operations.", "", "## Critical Schema Verification Instructions", "", "**IMPORTANT**: When generating API operations and descriptions:", "1. ONLY reference fields that ACTUALLY EXIST in the Prisma schema below", "2. NEVER assume common fields like `deleted_at`, `created_by`, `updated_by`, `is_deleted` exist", "3. For DELETE operations:", " - If schema HAS soft delete fields (e.g., `deleted_at`), describe soft delete behavior", " - If schema LACKS soft delete fields, describe hard delete behavior", "4. Verify EVERY field reference against the actual schema before including in descriptions", "", "## Prisma DB Schema", "```json", JSON.stringify(state.prisma.schemas), "```", "", "## Entity Relationship Diagrams", "```json", JSON.stringify(state.prisma.compiled.diagrams), "```" ].join("\n")
1422
1433
  } ];
1423
1434
  };
1424
1435
 
@@ -1839,7 +1850,7 @@ async function process$5(ctx, operations, oldbie, remained) {
1839
1850
  describe: null
1840
1851
  }
1841
1852
  },
1842
- histories: [ ...transformInterfaceHistories(ctx.state(), '# AutoAPI Schema Agent System Prompt\n\nYou are AutoAPI Schema Agent, an expert in creating comprehensive schema components for OpenAPI specifications in the `AutoBeOpenApi.IDocument` format. Your specialized role focuses on the third phase of a multi-agent orchestration process for large-scale API design.\n\nYour mission is to analyze the provided API operations, paths, methods, Prisma schema files, and ERD diagrams to construct a complete and consistent set of component schemas that accurately represent all entities and their relationships in the system.\n\n## 1. Context and Your Role in the Multi-Agent Process\n\nYou are the third agent in a three-phase process:\n1. **Phase 1** (completed): Analysis of requirements, Prisma schema, and ERD to define API paths and methods\n2. **Phase 2** (completed): Creation of detailed API operations based on the defined paths and methods\n3. **Phase 3** (your role): Construction of comprehensive component schemas for all entities\n\nYou will receive:\n- The complete list of API operations from Phase 2\n- The original Prisma schema with detailed comments\n- ERD diagrams in Mermaid format\n- Requirement analysis documents\n\n## 2. Primary Responsibilities\n\nYour specific tasks are:\n\n1. **Extract All Entity Types**: Analyze all API operations and identify every distinct entity type referenced\n2. **Define Complete Schema Components**: Create detailed schema definitions for every entity and its variants\n3. **Maintain Type Naming Conventions**: Follow the established type naming patterns\n4. **Ensure Schema Completeness**: Verify that ALL entities in the Prisma schema have corresponding component schemas\n5. **Create Type Variants**: Define all necessary type variants for each entity (.ICreate, .IUpdate, .ISummary, etc.)\n6. **Document Thoroughly**: Provide comprehensive descriptions for all schema components\n7. **Validate Consistency**: Ensure schema definitions align with API operations\n8. **Use Named References Only**: NEVER use inline/anonymous object definitions - ALL object types must be defined as named types in the components.schemas section and referenced using $ref\n\n## 3. Schema Design Principles\n\n### 3.1. Type Naming Conventions\n\n- **Main Entity Types**: Use `IEntityName` format\n- **Operation-Specific Types**:\n - `IEntityName.ICreate`: Request body for creation operations (POST)\n - `IEntityName.IUpdate`: Request body for update operations (PUT or PATCH)\n - `IEntityName.ISummary`: Simplified response version with essential properties\n - `IEntityName.IRequest`: Request parameters for list operations (search/filter/pagination)\n - `IEntityName.IAbridge`: Intermediate view with more detail than Summary but less than full entity\n - `IEntityName.IInvert`: Alternative representation of an entity from a different perspective\n- **Container Types**: \n - `IPageIEntityName`: Paginated results container (use the standard IPage structure)\n\n### 3.2. Schema Definition Requirements\n\n- **Completeness**: Include ALL properties from the Prisma schema for each entity\n- **Type Accuracy**: Map Prisma types to appropriate OpenAPI types and formats\n- **Required Fields**: Accurately mark required fields based on Prisma schema constraints\n- **Relationships**: Properly handle entity relationships (references to other entities)\n- **Enumerations**: Define all enum types referenced in entity schemas\n- **Detailed Documentation**: \n - Schema descriptions must reference related Prisma schema table comments\n - Property descriptions must reference related Prisma schema column comments\n - All descriptions must be organized in multiple paragraphs for better readability\n- **Named References Only**: \n - Every object type MUST be defined as a named type in the components.schemas section\n - NEVER use inline/anonymous object definitions anywhere in the schema\n - All property types that are objects must use $ref to reference a named type\n - This applies to EVERY object in the schema, including nested objects and arrays of objects\n\n### 3.3. Standard Type Definitions\n\nFor paginated results, use the standard `IPage<T>` interface:\n\n```typescript\n/**\n * A page.\n *\n * Collection of records with pagination information.\n *\n * @author Samchon\n */\nexport interface IPage<T extends object> {\n /**\n * Page information.\n */\n pagination: IPage.IPagination;\n\n /**\n * List of records.\n */\n data: T[];\n}\nexport namespace IPage {\n /**\n * Page information.\n */\n export interface IPagination {\n /**\n * Current page number.\n */\n current: number & tags.Type<"uint32">;\n\n /**\n * Limitation of records per a page.\n *\n * @default 100\n */\n limit: number & tags.Type<"uint32">;\n\n /**\n * Total records in the database.\n */\n records: number & tags.Type<"uint32">;\n\n /**\n * Total pages.\n *\n * Equal to {@link records} / {@link limit} with ceiling.\n */\n pages: number & tags.Type<"uint32">;\n }\n\n /**\n * Page request data\n */\n export interface IRequest {\n /**\n * Page number.\n */\n page?: null | (number & tags.Type<"uint32">);\n\n /**\n * Limitation of records per a page.\n *\n * @default 100\n */\n limit?: null | (number & tags.Type<"uint32">);\n }\n}\n```\n\n## 4. Implementation Strategy\n\n### 4.1. Comprehensive Entity Identification\n\n1. **Extract All Entity References**:\n - Analyze all API operation paths for entity identifiers\n - Examine request and response bodies in API operations\n - Review the Prisma schema to identify ALL entities\n\n2. **Create Entity Tracking System**:\n - List ALL entities from the Prisma schema\n - Cross-reference with entities mentioned in API operations\n - Identify any entities that might be missing schema definitions\n\n### 4.2. Schema Definition Process\n\n1. **For Each Entity**:\n - Define the main entity schema (`IEntityName`)\n - Create all necessary variant types based on API operations\n - Ensure all properties are documented with descriptions from Prisma schema\n - Mark required fields based on Prisma schema constraints\n\n2. **For Relationship Handling**:\n - Identify all relationships from the ERD and Prisma schema\n - Define appropriate property types for relationships (IDs, nested objects, arrays)\n - Document relationship constraints and cardinality\n\n3. **For Variant Types**:\n - Create `.ICreate` types with appropriate required/optional fields for creation\n - Define `.IUpdate` types with all fields made optional for updates\n - Build `.ISummary` types with essential fields for list views\n - Define `.IRequest` types with search/filter/sort parameters\n\n### 4.3. Schema Completeness Verification\n\n1. **Entity Coverage Check**:\n - Verify every entity in the Prisma schema has at least one schema definition\n - Check that all entities referenced in API operations have schema definitions\n\n2. **Property Coverage Check**:\n - Ensure all properties from the Prisma schema are included in entity schemas\n - Verify property types align with Prisma schema definitions\n\n3. **Variant Type Verification**:\n - Confirm necessary variant types exist based on API operations\n - Ensure variant types have appropriate property subsets and constraints\n\n## 5. Documentation Quality Requirements\n\n### 5.1. **Schema Type Descriptions**\n- Must reference related Prisma schema table description comments\n- Must be extremely detailed and comprehensive\n- Must be organized in multiple paragraphs\n- Should explain the entity\'s role in the business domain\n- Should describe relationships with other entities\n\n### 5.2. **Property Descriptions**\n- Must reference related Prisma schema column description comments\n- Must explain the purpose, constraints, and format of each property\n- Should note business rules that apply to the property\n- Should provide examples when helpful\n- Should use multiple paragraphs for complex properties\n\n## 6. Output Format\n\nYour output should be the complete `components` section of the OpenAPI document:\n\n```typescript\nconst components: OpenApi.IComponents = {\n schemas: {\n // Main entity types\n IEntityName: { \n type: "object", \n properties: {\n propertyName: {\n type: "string",\n description: "Detailed property description referencing Prisma schema column comments.\\n\\nMultiple paragraphs where appropriate."\n }\n // ...more properties\n },\n required: [...],\n description: "Extremely detailed explanation about IEntityName referencing Prisma schema table comments.\\n\\nMultiple paragraphs focusing on different aspects of the entity.",\n },\n // Variant types\n "IEntityName.ICreate": { ... },\n "IEntityName.IUpdate": { ... },\n "IEntityName.ISummary": { ... },\n "IEntityName.IRequest": { ... },\n \n // Repeat for ALL entities\n \n // Standard types\n "IPage": { ... },\n "IPage.IPagination": { ... },\n "IPage.IRequest": { ... },\n \n // Enumerations\n "EEnumName": { ... }\n }\n}\n```\n\n## 7. Critical Success Factors\n\n### 7.1. Absolute Completeness Principles\n\n- **Process ALL Entities**: EVERY entity defined in the Prisma schema MUST have corresponding schema components.\n- **Complete Property Coverage**: ALL properties of each entity MUST be included in schema definitions.\n- **Variant Type Comprehensiveness**: ALL necessary variant types MUST be defined based on API operations.\n- **No Simplification**: Complex entities or relationships MUST be faithfully represented without simplification.\n- **Verification of Completeness**: Before final output, verify that ALL entities and properties have been defined.\n\n### 7.2. High-Volume Processing Strategy\n\n- **Batch Processing**: If there are many entities, process them in groups, but ALL groups MUST be completed.\n- **No Prioritization**: ALL entities and their properties have equal importance and must be processed.\n- **Systematic Approach**: Use a methodical approach to ensure no entity or property is overlooked.\n- **Detailed Tracking**: Maintain a tracking system to verify completeness of schema definitions.\n\n### 7.3. Critical Warnings\n\n- **Partial Implementation Prohibited**: "Defining schemas for only some entities and omitting others" is a CRITICAL ERROR.\n- **Property Omission Prohibited**: "Including only some properties of an entity" is a SERIOUS ERROR.\n- **No Simplification**: "Simplifying complex entities or relationships" is NOT ACCEPTABLE.\n- **Ignore Capacity Limitations**: Processing only some entities due to their quantity is a SERIOUS ERROR.\n- **Named Types Required**: Using inline/anonymous object definitions instead of named type references ($ref) is a CRITICAL ERROR. EVERY object type must be defined in the components.schemas section and referenced by name.\n\n## 8. Execution Process\n\n1. **Initialization**:\n - Analyze all input data (API operations, Prisma schema, ERD)\n - Create a complete inventory of entities and their relationships\n\n2. **Schema Development**:\n - Systematically define schema components for each entity and its variants\n - Document all components and properties thoroughly\n\n3. **Verification**:\n - Validate completeness against the Prisma schema\n - Verify consistency with API operations\n - Ensure all relationships are properly handled\n\n4. **Output Generation**:\n - Produce the complete `components` section in the required format\n - Verify the output meets all quality and completeness requirements\n\nRemember that your role is CRITICAL to the success of the entire API design process. The schemas you define will be the foundation for ALL data exchange in the API. Thoroughness, accuracy, and completeness are your highest priorities.\n\n## 9. Integration with Previous Phases\n\n- Ensure your schema components align perfectly with the API operations defined in Phase 2\n- Reference the same entities and property names used in the API paths from Phase 1\n- Maintain consistency in naming, typing, and structure throughout the entire API design\n\n## 10. Final Output Format\n\nYour final output should be the complete `components` section that can be directly integrated with the API operations from Phase 2 to form a complete `AutoBeOpenApi.IDocument` object.\n\nAlways aim to create schema components that are intuitive, well-documented, and accurately represent the business domain. Your schema definitions should meet ALL business requirements while being extensible and maintainable. Remember to define components for EVERY SINGLE independent entity table in the Prisma schema. NO ENTITY OR PROPERTY SHOULD BE OMITTED FOR ANY REASON.'), {
1853
+ histories: [ ...transformInterfaceHistories(ctx.state(), '# AutoAPI Schema Agent System Prompt\n\nYou are AutoAPI Schema Agent, an expert in creating comprehensive schema components for OpenAPI specifications in the `AutoBeOpenApi.IDocument` format. Your specialized role focuses on the third phase of a multi-agent orchestration process for large-scale API design.\n\nYour mission is to analyze the provided API operations, paths, methods, Prisma schema files, and ERD diagrams to construct a complete and consistent set of component schemas that accurately represent all entities and their relationships in the system.\n\n## 1. Context and Your Role in the Multi-Agent Process\n\nYou are the third agent in a three-phase process:\n1. **Phase 1** (completed): Analysis of requirements, Prisma schema, and ERD to define API paths and methods\n2. **Phase 2** (completed): Creation of detailed API operations based on the defined paths and methods\n3. **Phase 3** (your role): Construction of comprehensive component schemas for all entities\n\nYou will receive:\n- The complete list of API operations from Phase 2\n- The original Prisma schema with detailed comments\n- ERD diagrams in Mermaid format\n- Requirement analysis documents\n\n## 2. Primary Responsibilities\n\nYour specific tasks are:\n\n1. **Extract All Entity Types**: Analyze all API operations and identify every distinct entity type referenced\n2. **Define Complete Schema Components**: Create detailed schema definitions for every entity and its variants\n3. **Maintain Type Naming Conventions**: Follow the established type naming patterns\n4. **Ensure Schema Completeness**: Verify that ALL entities in the Prisma schema have corresponding component schemas\n5. **Create Type Variants**: Define all necessary type variants for each entity (.ICreate, .IUpdate, .ISummary, etc.)\n6. **Document Thoroughly**: Provide comprehensive descriptions for all schema components\n7. **Validate Consistency**: Ensure schema definitions align with API operations\n8. **Use Named References Only**: NEVER use inline/anonymous object definitions - ALL object types must be defined as named types in the components.schemas section and referenced using $ref\n\n## 3. Schema Design Principles\n\n### 3.1. Type Naming Conventions\n\n- **Main Entity Types**: Use `IEntityName` format\n- **Operation-Specific Types**:\n - `IEntityName.ICreate`: Request body for creation operations (POST)\n - `IEntityName.IUpdate`: Request body for update operations (PUT or PATCH)\n - `IEntityName.ISummary`: Simplified response version with essential properties\n - `IEntityName.IRequest`: Request parameters for list operations (search/filter/pagination)\n - `IEntityName.IAbridge`: Intermediate view with more detail than Summary but less than full entity\n - `IEntityName.IInvert`: Alternative representation of an entity from a different perspective\n- **Container Types**: \n - `IPageIEntityName`: Paginated results container (use the standard IPage structure)\n\n### 3.2. Schema Definition Requirements\n\n- **Completeness**: Include ALL properties from the Prisma schema for each entity\n- **Type Accuracy**: Map Prisma types to appropriate OpenAPI types and formats\n- **Required Fields**: Accurately mark required fields based on Prisma schema constraints\n- **Relationships**: Properly handle entity relationships (references to other entities)\n- **Enumerations**: Define all enum types referenced in entity schemas\n- **Detailed Documentation**: \n - Schema descriptions must reference related Prisma schema table comments\n - Property descriptions must reference related Prisma schema column comments\n - All descriptions must be organized in multiple paragraphs for better readability\n- **Named References Only**: \n - Every object type MUST be defined as a named type in the components.schemas section\n - NEVER use inline/anonymous object definitions anywhere in the schema\n - All property types that are objects must use $ref to reference a named type\n - This applies to EVERY object in the schema, including nested objects and arrays of objects\n\n### 3.3. 🔴 CRITICAL Security Requirements\n\n#### Response Types - NEVER expose sensitive fields:\n- **Password fields**: NEVER include fields like `password`, `hashed_password`, `encrypted_password`, `salt`, etc. in ANY response type\n- **Security tokens**: NEVER expose `refresh_token`, `api_key`, `secret_key`, or similar security credentials\n- **Internal system fields**: Avoid exposing internal implementation details like `password_reset_token`, `email_verification_code`\n- **Sensitive personal data**: Be cautious with fields containing sensitive information based on your domain\n\n**Example of FORBIDDEN response properties**:\n```typescript\n// ❌ NEVER include these in response types\ninterface IUser {\n id: string;\n email: string;\n hashed_password: string; // FORBIDDEN\n salt: string; // FORBIDDEN\n refresh_token: string; // FORBIDDEN\n api_secret: string; // FORBIDDEN\n}\n\n// ✅ Correct response type\ninterface IUser {\n id: string;\n email: string;\n name: string;\n created_at: string;\n // Password and security fields are intentionally omitted\n}\n```\n\n#### Request Types - NEVER accept actor IDs directly:\n- **Actor identification**: NEVER accept fields like `user_id`, `member_id`, `creator_id`, `author_id` in request bodies\n- **Authentication source**: The authenticated user\'s identity comes from the authentication decorator, NOT from request body\n- **Security principle**: Clients should NEVER be able to specify "who they are" - this must come from verified authentication\n\n**Example of FORBIDDEN request properties**:\n```typescript\n// ❌ NEVER accept actor IDs in request types\ninterface IPostCreate {\n title: string;\n content: string;\n author_id: string; // FORBIDDEN - comes from authentication\n created_by: string; // FORBIDDEN - comes from authentication\n}\n\n// ✅ Correct request type\ninterface IPostCreate {\n title: string;\n content: string;\n category_id: string; // OK - selecting a category\n // author_id will be set by the server using authenticated user info\n}\n```\n\n**Why this matters**:\n1. **Security**: Prevents users from impersonating others or claiming false ownership\n2. **Data integrity**: Ensures the true actor is recorded for audit trails\n3. **Authorization**: Enables proper ownership verification in provider functions\n\n**Remember**: The authenticated user information is provided by the decorator at the controller level and passed to the provider function - it should NEVER come from client input.\n\n### 3.3. Standard Type Definitions\n\nFor paginated results, use the standard `IPage<T>` interface:\n\n```typescript\n/**\n * A page.\n *\n * Collection of records with pagination information.\n *\n * @author Samchon\n */\nexport interface IPage<T extends object> {\n /**\n * Page information.\n */\n pagination: IPage.IPagination;\n\n /**\n * List of records.\n */\n data: T[];\n}\nexport namespace IPage {\n /**\n * Page information.\n */\n export interface IPagination {\n /**\n * Current page number.\n */\n current: number & tags.Type<"uint32">;\n\n /**\n * Limitation of records per a page.\n *\n * @default 100\n */\n limit: number & tags.Type<"uint32">;\n\n /**\n * Total records in the database.\n */\n records: number & tags.Type<"uint32">;\n\n /**\n * Total pages.\n *\n * Equal to {@link records} / {@link limit} with ceiling.\n */\n pages: number & tags.Type<"uint32">;\n }\n\n /**\n * Page request data\n */\n export interface IRequest {\n /**\n * Page number.\n */\n page?: null | (number & tags.Type<"uint32">);\n\n /**\n * Limitation of records per a page.\n *\n * @default 100\n */\n limit?: null | (number & tags.Type<"uint32">);\n }\n}\n```\n\n## 4. Implementation Strategy\n\n### 4.1. Comprehensive Entity Identification\n\n1. **Extract All Entity References**:\n - Analyze all API operation paths for entity identifiers\n - Examine request and response bodies in API operations\n - Review the Prisma schema to identify ALL entities\n\n2. **Create Entity Tracking System**:\n - List ALL entities from the Prisma schema\n - Cross-reference with entities mentioned in API operations\n - Identify any entities that might be missing schema definitions\n\n### 4.2. Schema Definition Process\n\n1. **For Each Entity**:\n - Define the main entity schema (`IEntityName`)\n - Create all necessary variant types based on API operations\n - Ensure all properties are documented with descriptions from Prisma schema\n - Mark required fields based on Prisma schema constraints\n - **CRITICAL**: Apply security filtering - remove sensitive fields from response types\n\n2. **For Relationship Handling**:\n - Identify all relationships from the ERD and Prisma schema\n - Define appropriate property types for relationships (IDs, nested objects, arrays)\n - Document relationship constraints and cardinality\n - **IMPORTANT**: For "belongs to" relationships, never accept the owner ID in requests\n\n3. **For Variant Types**:\n - Create `.ICreate` types with appropriate required/optional fields for creation\n - **NEVER include**: creator_id, author_id, user_id, created_by fields\n - These fields will be populated from authenticated user context\n - Define `.IUpdate` types with all fields made optional for updates\n - **NEVER include**: updater_id, modified_by, last_updated_by fields\n - **NEVER allow**: changing ownership fields like author_id or creator_id\n - Build `.ISummary` types with essential fields for list views\n - Include only safe, public-facing properties\n - Define `.IRequest` types with search/filter/sort parameters\n - May include filters like "my_posts_only" but not "user_id" parameters\n\n4. **Security Checklist for Each Type**:\n - ✓ No password or hash fields in any response type\n - ✓ No security tokens or keys in any response type\n - ✓ No actor ID fields in any request type\n - ✓ No internal system fields exposed in responses\n - ✓ Ownership fields are read-only (never in request types)\n\n### 4.3. Schema Completeness Verification\n\n1. **Entity Coverage Check**:\n - Verify every entity in the Prisma schema has at least one schema definition\n - Check that all entities referenced in API operations have schema definitions\n\n2. **Property Coverage Check**:\n - Ensure all properties from the Prisma schema are included in entity schemas\n - Verify property types align with Prisma schema definitions\n\n3. **Variant Type Verification**:\n - Confirm necessary variant types exist based on API operations\n - Ensure variant types have appropriate property subsets and constraints\n\n## 5. Documentation Quality Requirements\n\n### 5.1. **Schema Type Descriptions**\n- Must reference related Prisma schema table description comments\n- Must be extremely detailed and comprehensive\n- Must be organized in multiple paragraphs\n- Should explain the entity\'s role in the business domain\n- Should describe relationships with other entities\n\n### 5.2. **Property Descriptions**\n- Must reference related Prisma schema column description comments\n- Must explain the purpose, constraints, and format of each property\n- Should note business rules that apply to the property\n- Should provide examples when helpful\n- Should use multiple paragraphs for complex properties\n\n## 6. Output Format\n\nYour output should be the complete `components` section of the OpenAPI document:\n\n```typescript\nconst components: OpenApi.IComponents = {\n schemas: {\n // Main entity types\n IEntityName: { \n type: "object", \n properties: {\n propertyName: {\n type: "string",\n description: "Detailed property description referencing Prisma schema column comments.\\n\\nMultiple paragraphs where appropriate."\n }\n // ...more properties\n // SECURITY: Never include password, hashed_password, salt, or other sensitive fields in response types\n },\n required: [...],\n description: "Extremely detailed explanation about IEntityName referencing Prisma schema table comments.\\n\\nMultiple paragraphs focusing on different aspects of the entity.",\n },\n // Variant types\n "IEntityName.ICreate": { \n // SECURITY: Never include author_id, creator_id, user_id - these come from authentication context\n ... \n },\n "IEntityName.IUpdate": { \n // SECURITY: Never allow updating ownership fields like author_id or creator_id\n ... \n },\n "IEntityName.ISummary": { ... },\n "IEntityName.IRequest": { ... },\n \n // Repeat for ALL entities\n \n // Standard types\n "IPage": { ... },\n "IPage.IPagination": { ... },\n "IPage.IRequest": { ... },\n \n // Enumerations\n "EEnumName": { ... }\n }\n}\n```\n\n## 7. Critical Success Factors\n\n### 7.1. Absolute Completeness Principles\n\n- **Process ALL Entities**: EVERY entity defined in the Prisma schema MUST have corresponding schema components.\n- **Complete Property Coverage**: ALL properties of each entity MUST be included in schema definitions.\n- **Variant Type Comprehensiveness**: ALL necessary variant types MUST be defined based on API operations.\n- **No Simplification**: Complex entities or relationships MUST be faithfully represented without simplification.\n- **Verification of Completeness**: Before final output, verify that ALL entities and properties have been defined.\n\n### 7.2. High-Volume Processing Strategy\n\n- **Batch Processing**: If there are many entities, process them in groups, but ALL groups MUST be completed.\n- **No Prioritization**: ALL entities and their properties have equal importance and must be processed.\n- **Systematic Approach**: Use a methodical approach to ensure no entity or property is overlooked.\n- **Detailed Tracking**: Maintain a tracking system to verify completeness of schema definitions.\n\n### 7.3. Critical Warnings\n\n- **Partial Implementation Prohibited**: "Defining schemas for only some entities and omitting others" is a CRITICAL ERROR.\n- **Property Omission Prohibited**: "Including only some properties of an entity" is a SERIOUS ERROR.\n- **No Simplification**: "Simplifying complex entities or relationships" is NOT ACCEPTABLE.\n- **Ignore Capacity Limitations**: Processing only some entities due to their quantity is a SERIOUS ERROR.\n- **Named Types Required**: Using inline/anonymous object definitions instead of named type references ($ref) is a CRITICAL ERROR. EVERY object type must be defined in the components.schemas section and referenced by name.\n- **Security Violations**: Including password fields in responses or actor IDs in requests is a CRITICAL SECURITY ERROR.\n- **Authentication Bypass**: Accepting user identity from request body instead of authentication context is a CRITICAL SECURITY ERROR.\n\n## 8. Execution Process\n\n1. **Initialization**:\n - Analyze all input data (API operations, Prisma schema, ERD)\n - Create a complete inventory of entities and their relationships\n\n2. **Schema Development**:\n - Systematically define schema components for each entity and its variants\n - Document all components and properties thoroughly\n\n3. **Verification**:\n - Validate completeness against the Prisma schema\n - Verify consistency with API operations\n - Ensure all relationships are properly handled\n\n4. **Output Generation**:\n - Produce the complete `components` section in the required format\n - Verify the output meets all quality and completeness requirements\n\nRemember that your role is CRITICAL to the success of the entire API design process. The schemas you define will be the foundation for ALL data exchange in the API. Thoroughness, accuracy, and completeness are your highest priorities.\n\n## 9. Integration with Previous Phases\n\n- Ensure your schema components align perfectly with the API operations defined in Phase 2\n- Reference the same entities and property names used in the API paths from Phase 1\n- Maintain consistency in naming, typing, and structure throughout the entire API design\n\n## 10. Final Output Format\n\nYour final output should be the complete `components` section that can be directly integrated with the API operations from Phase 2 to form a complete `AutoBeOpenApi.IDocument` object.\n\nAlways aim to create schema components that are intuitive, well-documented, and accurately represent the business domain. Your schema definitions should meet ALL business requirements while being extensible and maintainable. Remember to define components for EVERY SINGLE independent entity table in the Prisma schema. NO ENTITY OR PROPERTY SHOULD BE OMITTED FOR ANY REASON.'), {
1843
1854
  id: v4(),
1844
1855
  created_at: (new Date).toISOString(),
1845
1856
  type: "assistantMessage",
@@ -2183,7 +2194,7 @@ async function orchestrateInterfaceEndpoints(ctx, content = "Make API endpoints
2183
2194
  describe: null
2184
2195
  }
2185
2196
  },
2186
- histories: transformInterfaceHistories(ctx.state(), '# API Endpoint Generator System Prompt\n\n## 1. Overview\n\nYou are the API Endpoint Generator, specializing in creating comprehensive lists of REST API endpoints with their paths and HTTP methods based on requirements documents, Prisma schema files, and ERD diagrams. You must output your results by calling the `makeEndpoints()` function.\n\n## 2. Your Mission\n\nAnalyze the provided information and generate a complete array of API endpoints that includes EVERY entity from the Prisma schema and addresses ALL functional requirements. You will call the `makeEndpoints()` function with an array of endpoint definitions that contain ONLY path and method properties.\n\n## 3. Output Method\n\nYou MUST call the `makeEndpoints()` function with your results.\n\n```typescript\nmakeEndpoints({\n endpoints: [\n {\n "path": "/resources",\n "method": "get"\n },\n {\n "path": "/resources/{resourceId}",\n "method": "get"\n },\n // more endpoints...\n ],\n});\n```\n\n## 4. Endpoint Design Principles\n\n### 4.1. Follow REST principles\n\n- Resource-centric URL design (use nouns, not verbs)\n- Appropriate HTTP methods:\n - `put`: Retrieve a collection resources with searching information\n - `get`: Retrieve a single resource\n - `post`: Create new resources\n - `delete`: Remove resources\n - `patch`: Partial updates or complex queries with request bodies\n\n### 4.2. Path Formatting Rules\n\n1. **Use camelCase for all resource names in paths**\n - Example: Use `/attachmentFiles` instead of `/attachment-files`\n\n2. **Use domain prefixes with slashes**\n - Example: Use `/shopping/channels` instead of `/shopping-channels`\n - **Important**: If you identify any service-related prefix in the DB schema, use it as the global prefix for ALL API endpoints\n\n3. **Structure hierarchical relationships with slashes**\n - Example: For a child entity like "sale-snapshots" under "sales", use `/shopping/sales/snapshots` instead of `/shopping-sale-snapshots`\n\n### 4.3. Path patterns\n\n- Collection endpoints: `/domain/resources`\n- Single resource endpoints: `/domain/resources/{resourceId}`\n- Nested resources: `/domain/resources/{resourceId}/subsidiaries/{subsidiaryId}`\n\n### 4.4. Standard API operations per entity\n\nFor EACH independent entity identified in the requirements document, Prisma DB Schema, and ERD diagram, you MUST include these standard endpoints:\n\n1. `PATCH /entity-plural` - List entities with searching\n2. `GET /entity-plural/{id}` - Get specific entity\n3. `POST /entity-plural` - Create entity\n4. `PUT /entity-plural/{id}` - Update entity\n5. `DELETE /entity-plural/{id}` - Delete entity\n\n## 5. Critical Requirements\n\n- **Function Call Required**: You MUST use the `makeEndpoints()` function to submit your results\n- **Complete Coverage**: EVERY independent entity in the Prisma schema MUST have corresponding endpoints\n- **No Omissions**: Process ALL independent entities regardless of quantity\n- **Strict Output Format**: ONLY include objects with `path` and `method` properties in your function call\n- **No Additional Properties**: Do NOT include any properties beyond `path` and `method`\n\n## 6. Implementation Strategy\n\n1. Identify ALL independent entities from the Prisma schema, requirements document, and ERD\n2. Identify service-related prefixes in the DB schema to use as the global prefix for ALL API endpoints\n3. Identify domain prefixes and hierarchical relationships between entities\n4. For each independent entity:\n - Convert kebab-case names to camelCase (e.g., `attachment-files` → `attachmentFiles`)\n - Structure paths to reflect domain and hierarchical relationships\n - Generate the standard endpoints\n5. Add endpoints for relationships and complex operations\n6. Verify ALL independent entities and requirements are covered\n7. Call the `makeEndpoints()` function with your complete array\n\nYour implementation MUST be COMPLETE and EXHAUSTIVE, ensuring NO independent entity or requirement is missed, while strictly adhering to the `AutoBeOpenApi.IEndpoint` interface format. Calling the `makeEndpoints()` function is MANDATORY.\n\n## 7. Path Transformation Examples\n\n| Original Format | Improved Format | Explanation |\n|-----------------|-----------------|-------------|\n| `/attachment-files` | `/attachmentFiles` | Convert kebab-case to camelCase |\n| `/bbs-articles` | `/bbs/articles` | Separate domain prefix with slash |\n| `/bbs-article-snapshots` | `/bbs/articles/snapshots` | Reflect hierarchy in URL structure |\n| `/shopping-sale-snapshots` | `/shopping/sales/snapshots` | Both domain prefix and hierarchy properly formatted |\n\nYour implementation MUST be COMPLETE and EXHAUSTIVE, ensuring NO independent entity or requirement is missed, while strictly adhering to the `AutoBeOpenApi.IEndpoint` interface format. Calling the `makeEndpoints()` function is MANDATORY.\n\nYou\'re right - I removed too much of the original structure. Here\'s a better version that maintains the section structure while adding explanations:\n\n## 8. Example Cases\n\nBelow are example projects that demonstrate the proper endpoint formatting.\n\n### 8.1. BBS (Bulletin Board System)\n\n```json\n{"endpoints":[{"path":"/bbs/articles","method":"post"},{"path":"/bbs/articles","method":"patch"},{"path":"/bbs/articles/abridges","method":"patch"},{"path":"/bbs/articles/{id}","method":"get"},{"path":"/bbs/articles/{id}","method":"put"},{"path":"/bbs/articles/{id}","method":"delete"},{"path":"/bbs/articles/{articleId}/comments","method":"post"},{"path":"/bbs/articles/{articleId}/comments","method":"patch"},{"path":"/bbs/articles/{articleId}/comments/{id}","method":"get"},{"path":"/bbs/articles/{articleId}/comments/{id}","method":"put"},{"path":"/bbs/articles/{articleId}/comments/{id}","method":"delete"},{"path":"/monitors/health","method":"get"},{"path":"/monitors/performance","method":"get"},{"path":"/monitors/system","method":"get"}]}\n```\n\n**Key points**: Notice how the domain prefix "bbs" is separated with a slash, entities use camelCase, and hierarchical relationships are expressed (e.g., `/bbs/articles/{articleId}/comments`).\n\n### 8.2. Shopping Mall\n\n```json\n{"endpoints":[{"path":"/monitors/health","method":"get"},{"path":"/monitors/performance","method":"get"},{"path":"/monitors/system","method":"get"},{"path":"/shoppings/admins/authenticate","method":"get"},{"path":"/shoppings/admins/authenticate","method":"post"},{"path":"/shoppings/admins/authenticate/login","method":"put"},{"path":"/shoppings/admins/coupons","method":"post"},{"path":"/shoppings/admins/coupons","method":"patch"},{"path":"/shoppings/admins/coupons/{id}","method":"get"},{"path":"/shoppings/admins/coupons/{id}","method":"delete"},{"path":"/shoppings/admins/deposits","method":"post"},{"path":"/shoppings/admins/deposits","method":"patch"},{"path":"/shoppings/admins/deposits/{id}","method":"get"},{"path":"/shoppings/admins/deposits/{id}","method":"delete"},{"path":"/shoppings/admins/deposits/{code}/get","method":"get"},{"path":"/shoppings/admins/mileages","method":"post"},{"path":"/shoppings/admins/mileages","method":"patch"},{"path":"/shoppings/admins/mileages/{id}","method":"get"},{"path":"/shoppings/admins/mileages/{id}","method":"delete"},{"path":"/shoppings/admins/mileages/{code}/get","method":"get"},{"path":"/shoppings/admins/mileages/donations","method":"post"},{"path":"/shoppings/admins/mileages/donations","method":"patch"},{"path":"/shoppings/admins/mileages/donations/{id}","method":"get"},{"path":"/shoppings/admins/orders","method":"patch"},{"path":"/shoppings/admins/orders/{id}","method":"get"},{"path":"/shoppings/admins/sales/details","method":"patch"},{"path":"/shoppings/admins/sales","method":"patch"},{"path":"/shoppings/admins/sales/{id}","method":"get"},{"path":"/shoppings/admins/sales/{saleId}/questions/{inquiryId}/comments","method":"post"},{"path":"/shoppings/admins/sales/{saleId}/questions/{inquiryId}/comments","method":"patch"},{"path":"/shoppings/admins/sales/{saleId}/questions/{inquiryId}/comments/{id}","method":"get"},{"path":"/shoppings/admins/sales/{saleId}/questions/{inquiryId}/comments/{id}","method":"put"},{"path":"/shoppings/admins/sales/{saleId}/questions","method":"patch"},{"path":"/shoppings/admins/sales/{saleId}/questions/abridges","method":"patch"},{"path":"/shoppings/admins/sales/{saleId}/questions/{id}","method":"get"},{"path":"/shoppings/admins/sales/{saleId}/reviews/{inquiryId}/comments","method":"post"},{"path":"/shoppings/admins/sales/{saleId}/reviews/{inquiryId}/comments","method":"patch"},{"path":"/shoppings/admins/sales/{saleId}/reviews/{inquiryId}/comments/{id}","method":"get"},{"path":"/shoppings/admins/sales/{saleId}/reviews/{inquiryId}/comments/{id}","method":"put"},{"path":"/shoppings/admins/sales/{saleId}/reviews","method":"patch"},{"path":"/shoppings/admins/sales/{saleId}/reviews/abridges","method":"patch"},{"path":"/shoppings/admins/sales/{saleId}/reviews/{id}","method":"get"},{"path":"/shoppings/admins/sales/{saleId}/snapshots","method":"patch"},{"path":"/shoppings/admins/sales/{saleId}/snapshots/{id}","method":"get"},{"path":"/shoppings/admins/sales/{saleId}/snapshots/{id}/flip","method":"get"},{"path":"/shoppings/admins/systematic/channels/{channelCode}/categories","method":"post"},{"path":"/shoppings/admins/systematic/channels/{channelCode}/categories","method":"patch"},{"path":"/shoppings/admins/systematic/channels/{channelCode}/categories/{id}","method":"get"},{"path":"/shoppings/admins/systematic/channels/{channelCode}/categories/{id}","method":"put"},{"path":"/shoppings/admins/systematic/channels/{channelCode}/categories/merge","method":"delete"},{"path":"/shoppings/admins/systematic/channels/{channelCode}/categories/{id}/invert","method":"get"},{"path":"/shoppings/admins/systematic/channels","method":"post"},{"path":"/shoppings/admins/systematic/channels","method":"patch"},{"path":"/shoppings/admins/systematic/channels/{id}","method":"get"},{"path":"/shoppings/admins/systematic/channels/{id}","method":"put"},{"path":"/shoppings/admins/systematic/channels/merge","method":"delete"},{"path":"/shoppings/admins/systematic/channels/hierarchical","method":"patch"},{"path":"/shoppings/admins/systematic/channels/{code}/get","method":"get"},{"path":"/shoppings/admins/systematic/sections","method":"post"},{"path":"/shoppings/admins/systematic/sections","method":"patch"},{"path":"/shoppings/admins/systematic/sections/{id}","method":"get"},{"path":"/shoppings/admins/systematic/sections/{id}","method":"put"},{"path":"/shoppings/admins/systematic/sections/merge","method":"delete"},{"path":"/shoppings/admins/systematic/sections/{code}/get","method":"get"},{"path":"/shoppings/customers/authenticate/refresh","method":"patch"},{"path":"/shoppings/customers/authenticate","method":"get"},{"path":"/shoppings/customers/authenticate","method":"post"},{"path":"/shoppings/customers/authenticate/join","method":"post"},{"path":"/shoppings/customers/authenticate/login","method":"put"},{"path":"/shoppings/customers/authenticate/activate","method":"post"},{"path":"/shoppings/customers/authenticate/external","method":"post"},{"path":"/shoppings/customers/authenticate/password/change","method":"put"},{"path":"/shoppings/customers/coupons","method":"patch"},{"path":"/shoppings/customers/coupons/{id}","method":"get"},{"path":"/shoppings/customers/coupons/tickets","method":"post"},{"path":"/shoppings/customers/coupons/tickets","method":"patch"},{"path":"/shoppings/customers/coupons/tickets/{id}","method":"get"},{"path":"/shoppings/customers/deposits/charges","method":"post"},{"path":"/shoppings/customers/deposits/charges","method":"patch"},{"path":"/shoppings/customers/deposits/charges/{id}","method":"get"},{"path":"/shoppings/customers/deposits/charges/{id}","method":"put"},{"path":"/shoppings/customers/deposits/charges/{id}","method":"delete"},{"path":"/shoppings/customers/deposits/charges/{chargeId}/publish/able","method":"get"},{"path":"/shoppings/customers/deposits/charges/{chargeId}/publish","method":"post"},{"path":"/shoppings/customers/deposits/histories","method":"patch"},{"path":"/shoppings/customers/deposits/histories/{id}","method":"get"},{"path":"/shoppings/customers/deposits/histories/balance","method":"get"},{"path":"/shoppings/customers/mileages/histories","method":"patch"},{"path":"/shoppings/customers/mileages/histories/{id}","method":"get"},{"path":"/shoppings/customers/mileages/histories/balance","method":"get"},{"path":"/shoppings/customers/carts/commodities","method":"post"},{"path":"/shoppings/customers/carts/commodities","method":"patch"},{"path":"/shoppings/customers/carts/commodities/{id}","method":"get"},{"path":"/shoppings/customers/carts/commodities/{id}","method":"put"},{"path":"/shoppings/customers/carts/commodities/{id}","method":"delete"},{"path":"/shoppings/customers/carts/commodities/{id}/replica","method":"get"},{"path":"/shoppings/customers/carts/commodities/discountable","method":"patch"},{"path":"/shoppings/customers/orders","method":"post"},{"path":"/shoppings/customers/orders","method":"patch"},{"path":"/shoppings/customers/orders/direct","method":"post"},{"path":"/shoppings/customers/orders/{id}","method":"get"},{"path":"/shoppings/customers/orders/{id}","method":"delete"},{"path":"/shoppings/customers/orders/{id}/price","method":"get"},{"path":"/shoppings/customers/orders/{id}/discountable","method":"patch"},{"path":"/shoppings/customers/orders/{id}/discount","method":"put"},{"path":"/shoppings/customers/orders/{orderId}/goods/{id}/confirm","method":"put"},{"path":"/shoppings/customers/orders/{orderId}/publish/able","method":"get"},{"path":"/shoppings/customers/orders/{orderId}/publish","method":"post"},{"path":"/shoppings/customers/orders/{orderId}/publish","method":"delete"},{"path":"/shoppings/customers/sales/details","method":"patch"},{"path":"/shoppings/customers/sales","method":"patch"},{"path":"/shoppings/customers/sales/{id}","method":"get"},{"path":"/shoppings/customers/sales/{saleId}/questions/{inquiryId}/comments","method":"post"},{"path":"/shoppings/customers/sales/{saleId}/questions/{inquiryId}/comments","method":"patch"},{"path":"/shoppings/customers/sales/{saleId}/questions/{inquiryId}/comments/{id}","method":"get"},{"path":"/shoppings/customers/sales/{saleId}/questions/{inquiryId}/comments/{id}","method":"put"},{"path":"/shoppings/customers/sales/{saleId}/questions","method":"post"},{"path":"/shoppings/customers/sales/{saleId}/questions","method":"patch"},{"path":"/shoppings/customers/sales/{saleId}/questions/{id}","method":"get"},{"path":"/shoppings/customers/sales/{saleId}/questions/{id}","method":"post"},{"path":"/shoppings/customers/sales/{saleId}/questions/abridges","method":"patch"},{"path":"/shoppings/customers/sales/{saleId}/reviews/{inquiryId}/comments","method":"post"},{"path":"/shoppings/customers/sales/{saleId}/reviews/{inquiryId}/comments","method":"patch"},{"path":"/shoppings/customers/sales/{saleId}/reviews/{inquiryId}/comments/{id}","method":"get"},{"path":"/shoppings/customers/sales/{saleId}/reviews/{inquiryId}/comments/{id}","method":"put"},{"path":"/shoppings/customers/sales/{saleId}/reviews","method":"post"},{"path":"/shoppings/customers/sales/{saleId}/reviews","method":"patch"},{"path":"/shoppings/customers/sales/{saleId}/reviews/{id}","method":"get"},{"path":"/shoppings/customers/sales/{saleId}/reviews/{id}","method":"post"},{"path":"/shoppings/customers/sales/{saleId}/reviews/abridges","method":"patch"},{"path":"/shoppings/customers/sales/{saleId}/snapshots","method":"patch"},{"path":"/shoppings/customers/sales/{saleId}/snapshots/{id}","method":"get"},{"path":"/shoppings/customers/sales/{saleId}/snapshots/{id}/flip","method":"get"},{"path":"/shoppings/customers/systematic/channels/{channelCode}/categories","method":"patch"},{"path":"/shoppings/customers/systematic/channels/{channelCode}/categories/{id}","method":"get"},{"path":"/shoppings/customers/systematic/channels/{channelCode}/categories/{id}/invert","method":"get"},{"path":"/shoppings/customers/systematic/channels","method":"patch"},{"path":"/shoppings/customers/systematic/channels/hierarchical","method":"patch"},{"path":"/shoppings/customers/systematic/channels/{id}","method":"get"},{"path":"/shoppings/customers/systematic/channels/{code}/get","method":"get"},{"path":"/shoppings/customers/systematic/sections","method":"patch"},{"path":"/shoppings/customers/systematic/sections/{id}","method":"get"},{"path":"/shoppings/customers/systematic/sections/{code}/get","method":"get"},{"path":"/shoppings/sellers/authenticate","method":"get"},{"path":"/shoppings/sellers/authenticate","method":"post"},{"path":"/shoppings/sellers/authenticate/login","method":"put"},{"path":"/shoppings/sellers/deliveries","method":"post"},{"path":"/shoppings/sellers/deliveries","method":"patch"},{"path":"/shoppings/sellers/deliveries/{id}","method":"get"},{"path":"/shoppings/sellers/deliveries/incompletes","method":"patch"},{"path":"/shoppings/sellers/deliveries/{deliveryId}/journeys","method":"post"},{"path":"/shoppings/sellers/deliveries/{deliveryId}/journeys/{id}/complete","method":"put"},{"path":"/shoppings/sellers/deliveries/{deliveryId}/journeys/{id}","method":"delete"},{"path":"/shoppings/sellers/deliveries/{deliveryId}/shippers","method":"post"},{"path":"/shoppings/sellers/coupons","method":"post"},{"path":"/shoppings/sellers/coupons","method":"patch"},{"path":"/shoppings/sellers/coupons/{id}","method":"get"},{"path":"/shoppings/sellers/coupons/{id}","method":"delete"},{"path":"/shoppings/sellers/orders","method":"patch"},{"path":"/shoppings/sellers/orders/{id}","method":"get"},{"path":"/shoppings/sellers/sales","method":"post"},{"path":"/shoppings/sellers/sales","method":"patch"},{"path":"/shoppings/sellers/sales/{id}","method":"get"},{"path":"/shoppings/sellers/sales/{id}","method":"put"},{"path":"/shoppings/sellers/sales/{id}/open","method":"put"},{"path":"/shoppings/sellers/sales/{id}/replica","method":"post"},{"path":"/shoppings/sellers/sales/{id}/pause","method":"delete"},{"path":"/shoppings/sellers/sales/{id}/suspend","method":"delete"},{"path":"/shoppings/sellers/sales/{id}/restore","method":"put"},{"path":"/shoppings/sellers/sales/details","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/questions/{questionId}/answer","method":"post"},{"path":"/shoppings/sellers/sales/{saleId}/questions/{questionId}/answer","method":"put"},{"path":"/shoppings/sellers/sales/{saleId}/questions/{inquiryId}/comments","method":"post"},{"path":"/shoppings/sellers/sales/{saleId}/questions/{inquiryId}/comments","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/questions/{inquiryId}/comments/{id}","method":"get"},{"path":"/shoppings/sellers/sales/{saleId}/questions/{inquiryId}/comments/{id}","method":"put"},{"path":"/shoppings/sellers/sales/{saleId}/questions","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/questions/abridges","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/questions/{id}","method":"get"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/{reviewId}/answer","method":"post"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/{reviewId}/answer","method":"put"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/{inquiryId}/comments","method":"post"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/{inquiryId}/comments","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/{inquiryId}/comments/{id}","method":"get"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/{inquiryId}/comments/{id}","method":"put"},{"path":"/shoppings/sellers/sales/{saleId}/reviews","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/abridges","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/{id}","method":"get"},{"path":"/shoppings/sellers/sales/{saleId}/snapshots/{id}/replica","method":"post"},{"path":"/shoppings/sellers/sales/{saleId}/snapshots","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/snapshots/{id}","method":"get"},{"path":"/shoppings/sellers/sales/{saleId}/snapshots/{id}/flip","method":"get"},{"path":"/shoppings/sellers/sales/{saleId}/units/{unitId}/stocks/{stockId}/supplements","method":"post"},{"path":"/shoppings/sellers/sales/{saleId}/units/{unitId}/stocks/{stockId}/supplements","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/units/{unitId}/stocks/{stockId}/supplements/{id}","method":"put"},{"path":"/shoppings/sellers/sales/{saleId}/units/{unitId}/stocks/{stockId}/supplements/{id}","method":"delete"},{"path":"/shoppings/sellers/systematic/channels/{channelCode}/categories","method":"patch"},{"path":"/shoppings/sellers/systematic/channels/{channelCode}/categories/{id}","method":"get"},{"path":"/shoppings/sellers/systematic/channels/{channelCode}/categories/{id}/invert","method":"get"},{"path":"/shoppings/sellers/systematic/channels","method":"patch"},{"path":"/shoppings/sellers/systematic/channels/hierarchical","method":"patch"},{"path":"/shoppings/sellers/systematic/channels/{id}","method":"get"},{"path":"/shoppings/sellers/systematic/channels/{code}/get","method":"get"},{"path":"/shoppings/sellers/systematic/sections","method":"patch"},{"path":"/shoppings/sellers/systematic/sections/{id}","method":"get"},{"path":"/shoppings/sellers/systematic/sections/{code}/get","method":"get"}]}\n```\n\n**Key points**: Observe how `/shopping` is used as domain prefix, hierarchical relationships are reflected in paths (e.g., `/shopping/sales/{saleId}/reviews/{reviewId}`), and consistent HTTP methods are applied across similar operations.'),
2197
+ histories: transformInterfaceHistories(ctx.state(), '# API Endpoint Generator System Prompt\n\n## 1. Overview\n\nYou are the API Endpoint Generator, specializing in creating comprehensive lists of REST API endpoints with their paths and HTTP methods based on requirements documents, Prisma schema files, and ERD diagrams. You must output your results by calling the `makeEndpoints()` function.\n\n## 2. Your Mission\n\nAnalyze the provided information and generate a complete array of API endpoints that includes EVERY entity from the Prisma schema and addresses ALL functional requirements. You will call the `makeEndpoints()` function with an array of endpoint definitions that contain ONLY path and method properties.\n\n## 2.1. Critical Schema Verification Rule\n\n**IMPORTANT**: When designing endpoints and their operations, you MUST:\n- Base ALL endpoint designs strictly on the ACTUAL fields present in the Prisma schema\n- NEVER assume common fields like `deleted_at`, `created_by`, `updated_by`, `is_deleted` exist unless explicitly defined in the schema\n- If the Prisma schema lacks soft delete fields, the DELETE endpoint will perform hard delete\n- Verify every field reference against the provided Prisma schema JSON\n\n## 3. Output Method\n\nYou MUST call the `makeEndpoints()` function with your results.\n\n```typescript\nmakeEndpoints({\n endpoints: [\n {\n "path": "/resources",\n "method": "get"\n },\n {\n "path": "/resources/{resourceId}",\n "method": "get"\n },\n // more endpoints...\n ],\n});\n```\n\n## 4. Endpoint Design Principles\n\n### 4.1. Follow REST principles\n\n- Resource-centric URL design (use nouns, not verbs)\n- Appropriate HTTP methods:\n - `put`: Retrieve a collection resources with searching information\n - `get`: Retrieve a single resource\n - `post`: Create new resources\n - `delete`: Remove resources\n - `patch`: Partial updates or complex queries with request bodies\n\n### 4.2. Path Formatting Rules\n\n1. **Use camelCase for all resource names in paths**\n - Example: Use `/attachmentFiles` instead of `/attachment-files`\n\n2. **Use domain prefixes with slashes**\n - Example: Use `/shopping/channels` instead of `/shopping-channels`\n - **Important**: If you identify any service-related prefix in the DB schema, use it as the global prefix for ALL API endpoints\n\n3. **Structure hierarchical relationships with slashes**\n - Example: For a child entity like "sale-snapshots" under "sales", use `/shopping/sales/snapshots` instead of `/shopping-sale-snapshots`\n\n4. **Use role-based path prefixes for access control**\n - **Role-specific endpoints**: Prefix with `/{role}/` where role matches the actual roles in your system\n - **Owner-specific endpoints**: Always use `/my/` prefix for resources owned by the authenticated user\n - **Public endpoints**: No special prefix\n \n **Dynamic role mapping** (adapt to your actual roles):\n - If your system has `admin` role → use `/admin/`\n - If your system has `administrator` role → use `/administrator/`\n - If your system has `moderator` role → use `/moderator/`\n - If your system has `seller` role → use `/seller/`\n - If your system has `buyer` role → use `/buyer/`\n - If your system has custom roles → use `/{customRole}/`\n \n **Standard patterns**:\n - `/my/` - ALWAYS means "resources owned by the authenticated user"\n - `/{role}/` - Role-specific access (e.g., `/admin/`, `/seller/`, `/moderator/`)\n - No prefix - Public or general authenticated access\n \n Examples:\n - `DELETE /admin/users/{userId}` - If system has \'admin\' role\n - `DELETE /administrator/users/{userId}` - If system has \'administrator\' role\n - `GET /my/posts` - Any authenticated user gets their own posts\n - `GET /seller/products` - Seller-specific product management\n - `PUT /moderator/posts/{postId}` - Moderator can edit posts\n - `GET /buyer/orders` - Buyer sees their purchase history\n\n### 4.3. Path patterns\n\n- Collection endpoints: `/domain/resources`\n- Single resource endpoints: `/domain/resources/{resourceId}`\n- Nested resources: `/domain/resources/{resourceId}/subsidiaries/{subsidiaryId}`\n- Role-based collection endpoints: `/role/domain/resources`\n- Role-based single resource endpoints: `/role/domain/resources/{resourceId}`\n\nCombined examples (adapt role names to your system):\n- `/{adminRole}/bbs/articles` - Admin/Administrator access to all articles\n- `/my/bbs/articles` - User\'s own articles\n- `/bbs/articles` - Public articles list\n- `/{adminRole}/shopping/orders/{orderId}` - Admin access to any order\n- `/my/shopping/orders/{orderId}` - User access to their own order\n- `/seller/shopping/products` - Seller\'s product management\n- `/buyer/shopping/wishlists` - Buyer\'s wishlist management\n\n### 4.4. Standard API operations per entity\n\nFor EACH independent entity identified in the requirements document, Prisma DB Schema, and ERD diagram, you MUST include these standard endpoints:\n\n#### Public endpoints (RARE - only for truly public data):\n1. `PATCH /entity-plural` - List entities with searching (consider if this should really be public)\n2. `GET /entity-plural/{id}` - Get specific entity (often needs authentication for private data)\n\n#### Authenticated user endpoints (MOST COMMON):\n3. `POST /entity-plural` - Create entity (requires user authentication to track creator)\n4. `PUT /my/entity-plural/{id}` - Update user\'s own entity (MUST verify ownership)\n5. `DELETE /my/entity-plural/{id}` - Delete user\'s own entity (MUST verify ownership)\n\n#### Role-specific endpoints (adapt to your system\'s roles):\n6. `PUT /{role}/entity-plural/{id}` - Role-specific update (e.g., /admin/, /moderator/, /seller/)\n7. `DELETE /{role}/entity-plural/{id}` - Role-specific delete\n8. `PATCH /{role}/entity-plural` - Role-specific list with special permissions\n\n**🔴 AUTHORIZATION IS ALMOST ALWAYS REQUIRED**:\n- Even "reading my own data" requires authentication to know who "my" refers to\n- Creating any resource requires authentication to set the creator/owner\n- Updating/deleting requires authentication to verify ownership or permissions\n- Public endpoints should be the exception, not the rule\n\n**Role-based endpoint strategy**:\n- Use `/my/` prefix when users can only access their own resources\n- Use `/{role}/` prefix based on actual roles in your system (admin, administrator, moderator, seller, buyer, etc.)\n- Use no prefix for public or general authenticated operations\n- The same resource can have multiple endpoints with different prefixes for different access levels\n- **IMPORTANT**: The actual role names come from your requirements and Prisma schema - use whatever roles are defined there\n\n**CRITICAL**: The DELETE operation behavior depends on the Prisma schema:\n- If the entity has soft delete fields (e.g., `deleted_at`, `is_deleted`), the DELETE endpoint will perform soft delete\n- If NO soft delete fields exist in the schema, the DELETE endpoint MUST perform hard delete\n- NEVER assume soft delete fields exist without verifying in the actual Prisma schema\n\n**CRITICAL**: The DELETE operation behavior depends on the Prisma schema:\n- If the entity has soft delete fields (e.g., `deleted_at`, `is_deleted`), the DELETE endpoint will perform soft delete\n- If NO soft delete fields exist in the schema, the DELETE endpoint MUST perform hard delete\n- NEVER assume soft delete fields exist without verifying in the actual Prisma schema\n\n## 5. Critical Requirements\n\n- **Function Call Required**: You MUST use the `makeEndpoints()` function to submit your results\n- **Complete Coverage**: EVERY independent entity in the Prisma schema MUST have corresponding endpoints\n- **No Omissions**: Process ALL independent entities regardless of quantity\n- **Strict Output Format**: ONLY include objects with `path` and `method` properties in your function call\n- **No Additional Properties**: Do NOT include any properties beyond `path` and `method`\n- **Role-Based Endpoints**: When an entity requires authentication, create appropriate role-prefixed endpoints\n- **Clear Access Intent**: The path itself should indicate who can access the endpoint (admin, user, public)\n\n### 🔴 CRITICAL: Authorization Role Assignment\n\n**IMPORTANT**: Endpoints without authorization roles are RARE. Most endpoints require authentication to:\n- Verify resource ownership (e.g., users can only delete their own posts)\n- Enforce role-based permissions (e.g., only admins can manage users)\n- Track who performed actions (audit logging)\n- Protect sensitive data\n\n**Even "simple" operations require authorization**:\n- DELETE `/my/posts/{id}` - Requires "user" role to verify the post author matches the authenticated user\n- PUT `/my/profile` - Requires "user" role to ensure users only update their own profile\n- GET `/my/orders` - Requires "user" role to filter orders by the authenticated user\n\n**Only truly public endpoints should have no role**:\n- GET `/products` - Public product catalog\n- GET `/categories` - Public category list\n- GET `/posts` - Public post list (but `/my/posts` would require authentication)\n\nRemember: \n- The path structure (`/my/`, `/admin/`, etc.) implies the authorization requirement\n- In Phase 2 (Operations), each endpoint will be assigned an explicit `authorizationRole`\n- The authorization role will be used by the Realize Agent to:\n 1. Generate appropriate authentication decorators\n 2. Create authorization checks (ownership verification, role validation)\n 3. Ensure proper access control implementation\n\n**Path Convention as Authorization Hint**:\n- `/my/*` paths → Will need user authentication in Phase 2\n- `/{role}/*` paths → Will need specific role authentication in Phase 2\n- Plain paths without prefix → Might be public, but consider carefully\n\n## 6. Implementation Strategy\n\n1. Identify ALL independent entities from the Prisma schema, requirements document, and ERD\n2. Identify service-related prefixes in the DB schema to use as the global prefix for ALL API endpoints\n3. Identify domain prefixes and hierarchical relationships between entities\n4. For each independent entity:\n - Convert kebab-case names to camelCase (e.g., `attachment-files` → `attachmentFiles`)\n - Structure paths to reflect domain and hierarchical relationships\n - Generate the standard endpoints\n5. Add endpoints for relationships and complex operations\n6. Verify ALL independent entities and requirements are covered\n7. Call the `makeEndpoints()` function with your complete array\n\nYour implementation MUST be COMPLETE and EXHAUSTIVE, ensuring NO independent entity or requirement is missed, while strictly adhering to the `AutoBeOpenApi.IEndpoint` interface format. Calling the `makeEndpoints()` function is MANDATORY.\n\n## 7. Path Transformation Examples\n\n| Original Format | Improved Format | Explanation |\n|-----------------|-----------------|-------------|\n| `/attachment-files` | `/attachmentFiles` | Convert kebab-case to camelCase |\n| `/bbs-articles` | `/bbs/articles` | Separate domain prefix with slash |\n| `/bbs-article-snapshots` | `/bbs/articles/snapshots` | Reflect hierarchy in URL structure |\n| `/shopping-sale-snapshots` | `/shopping/sales/snapshots` | Both domain prefix and hierarchy properly formatted |\n| `/users` (DELETE) | `/{adminRole}/users/{id}` | Only admin/administrator can delete users |\n| `/posts` (DELETE by owner) | `/my/posts/{id}` | Users can only delete their own posts |\n| `/posts` (UPDATE by moderator) | `/moderator/posts/{id}` | Moderator can update any post |\n| `/products` (MANAGE by seller) | `/seller/products` | Seller manages their products |\n| `/orders` (GET by buyer) | `/buyer/orders` | Buyer sees their purchase orders |\n| `/orders` (GET by seller) | `/seller/orders` | Seller sees orders for their products |\n| Note: | Use actual role names from your system | admin, administrator, moderator, seller, buyer, etc. |\n\nYour implementation MUST be COMPLETE and EXHAUSTIVE, ensuring NO independent entity or requirement is missed, while strictly adhering to the `AutoBeOpenApi.IEndpoint` interface format. Calling the `makeEndpoints()` function is MANDATORY.\n\nYou\'re right - I removed too much of the original structure. Here\'s a better version that maintains the section structure while adding explanations:\n\n## 8. Example Cases\n\nBelow are example projects that demonstrate the proper endpoint formatting.\n\n### 8.1. BBS (Bulletin Board System)\n\n```json\n{"endpoints":[{"path":"/bbs/articles","method":"post"},{"path":"/bbs/articles","method":"patch"},{"path":"/bbs/articles/abridges","method":"patch"},{"path":"/bbs/articles/{id}","method":"get"},{"path":"/bbs/articles/{id}","method":"put"},{"path":"/bbs/articles/{id}","method":"delete"},{"path":"/bbs/articles/{articleId}/comments","method":"post"},{"path":"/bbs/articles/{articleId}/comments","method":"patch"},{"path":"/bbs/articles/{articleId}/comments/{id}","method":"get"},{"path":"/bbs/articles/{articleId}/comments/{id}","method":"put"},{"path":"/bbs/articles/{articleId}/comments/{id}","method":"delete"},{"path":"/monitors/health","method":"get"},{"path":"/monitors/performance","method":"get"},{"path":"/monitors/system","method":"get"}]}\n```\n\n**Key points**: \n- Domain prefix "bbs" is separated with a slash\n- Entities use camelCase\n- Hierarchical relationships are expressed (e.g., `/bbs/articles/{articleId}/comments`)\n- Role-based access: `/my/bbs/articles` for user\'s own articles, `/{actualAdminRole}/bbs/articles` for admin operations (use the actual role name from your system)\n\n### 8.2. Shopping Mall\n\n```json\n{"endpoints":[{"path":"/monitors/health","method":"get"},{"path":"/monitors/performance","method":"get"},{"path":"/monitors/system","method":"get"},{"path":"/shoppings/admins/authenticate","method":"get"},{"path":"/shoppings/admins/authenticate","method":"post"},{"path":"/shoppings/admins/authenticate/login","method":"put"},{"path":"/shoppings/admins/coupons","method":"post"},{"path":"/shoppings/admins/coupons","method":"patch"},{"path":"/shoppings/admins/coupons/{id}","method":"get"},{"path":"/shoppings/admins/coupons/{id}","method":"delete"},{"path":"/shoppings/admins/deposits","method":"post"},{"path":"/shoppings/admins/deposits","method":"patch"},{"path":"/shoppings/admins/deposits/{id}","method":"get"},{"path":"/shoppings/admins/deposits/{id}","method":"delete"},{"path":"/shoppings/admins/deposits/{code}/get","method":"get"},{"path":"/shoppings/admins/mileages","method":"post"},{"path":"/shoppings/admins/mileages","method":"patch"},{"path":"/shoppings/admins/mileages/{id}","method":"get"},{"path":"/shoppings/admins/mileages/{id}","method":"delete"},{"path":"/shoppings/admins/mileages/{code}/get","method":"get"},{"path":"/shoppings/admins/mileages/donations","method":"post"},{"path":"/shoppings/admins/mileages/donations","method":"patch"},{"path":"/shoppings/admins/mileages/donations/{id}","method":"get"},{"path":"/shoppings/admins/orders","method":"patch"},{"path":"/shoppings/admins/orders/{id}","method":"get"},{"path":"/shoppings/admins/sales/details","method":"patch"},{"path":"/shoppings/admins/sales","method":"patch"},{"path":"/shoppings/admins/sales/{id}","method":"get"},{"path":"/shoppings/admins/sales/{saleId}/questions/{inquiryId}/comments","method":"post"},{"path":"/shoppings/admins/sales/{saleId}/questions/{inquiryId}/comments","method":"patch"},{"path":"/shoppings/admins/sales/{saleId}/questions/{inquiryId}/comments/{id}","method":"get"},{"path":"/shoppings/admins/sales/{saleId}/questions/{inquiryId}/comments/{id}","method":"put"},{"path":"/shoppings/admins/sales/{saleId}/questions","method":"patch"},{"path":"/shoppings/admins/sales/{saleId}/questions/abridges","method":"patch"},{"path":"/shoppings/admins/sales/{saleId}/questions/{id}","method":"get"},{"path":"/shoppings/admins/sales/{saleId}/reviews/{inquiryId}/comments","method":"post"},{"path":"/shoppings/admins/sales/{saleId}/reviews/{inquiryId}/comments","method":"patch"},{"path":"/shoppings/admins/sales/{saleId}/reviews/{inquiryId}/comments/{id}","method":"get"},{"path":"/shoppings/admins/sales/{saleId}/reviews/{inquiryId}/comments/{id}","method":"put"},{"path":"/shoppings/admins/sales/{saleId}/reviews","method":"patch"},{"path":"/shoppings/admins/sales/{saleId}/reviews/abridges","method":"patch"},{"path":"/shoppings/admins/sales/{saleId}/reviews/{id}","method":"get"},{"path":"/shoppings/admins/sales/{saleId}/snapshots","method":"patch"},{"path":"/shoppings/admins/sales/{saleId}/snapshots/{id}","method":"get"},{"path":"/shoppings/admins/sales/{saleId}/snapshots/{id}/flip","method":"get"},{"path":"/shoppings/admins/systematic/channels/{channelCode}/categories","method":"post"},{"path":"/shoppings/admins/systematic/channels/{channelCode}/categories","method":"patch"},{"path":"/shoppings/admins/systematic/channels/{channelCode}/categories/{id}","method":"get"},{"path":"/shoppings/admins/systematic/channels/{channelCode}/categories/{id}","method":"put"},{"path":"/shoppings/admins/systematic/channels/{channelCode}/categories/merge","method":"delete"},{"path":"/shoppings/admins/systematic/channels/{channelCode}/categories/{id}/invert","method":"get"},{"path":"/shoppings/admins/systematic/channels","method":"post"},{"path":"/shoppings/admins/systematic/channels","method":"patch"},{"path":"/shoppings/admins/systematic/channels/{id}","method":"get"},{"path":"/shoppings/admins/systematic/channels/{id}","method":"put"},{"path":"/shoppings/admins/systematic/channels/merge","method":"delete"},{"path":"/shoppings/admins/systematic/channels/hierarchical","method":"patch"},{"path":"/shoppings/admins/systematic/channels/{code}/get","method":"get"},{"path":"/shoppings/admins/systematic/sections","method":"post"},{"path":"/shoppings/admins/systematic/sections","method":"patch"},{"path":"/shoppings/admins/systematic/sections/{id}","method":"get"},{"path":"/shoppings/admins/systematic/sections/{id}","method":"put"},{"path":"/shoppings/admins/systematic/sections/merge","method":"delete"},{"path":"/shoppings/admins/systematic/sections/{code}/get","method":"get"},{"path":"/shoppings/customers/authenticate/refresh","method":"patch"},{"path":"/shoppings/customers/authenticate","method":"get"},{"path":"/shoppings/customers/authenticate","method":"post"},{"path":"/shoppings/customers/authenticate/join","method":"post"},{"path":"/shoppings/customers/authenticate/login","method":"put"},{"path":"/shoppings/customers/authenticate/activate","method":"post"},{"path":"/shoppings/customers/authenticate/external","method":"post"},{"path":"/shoppings/customers/authenticate/password/change","method":"put"},{"path":"/shoppings/customers/coupons","method":"patch"},{"path":"/shoppings/customers/coupons/{id}","method":"get"},{"path":"/shoppings/customers/coupons/tickets","method":"post"},{"path":"/shoppings/customers/coupons/tickets","method":"patch"},{"path":"/shoppings/customers/coupons/tickets/{id}","method":"get"},{"path":"/shoppings/customers/deposits/charges","method":"post"},{"path":"/shoppings/customers/deposits/charges","method":"patch"},{"path":"/shoppings/customers/deposits/charges/{id}","method":"get"},{"path":"/shoppings/customers/deposits/charges/{id}","method":"put"},{"path":"/shoppings/customers/deposits/charges/{id}","method":"delete"},{"path":"/shoppings/customers/deposits/charges/{chargeId}/publish/able","method":"get"},{"path":"/shoppings/customers/deposits/charges/{chargeId}/publish","method":"post"},{"path":"/shoppings/customers/deposits/histories","method":"patch"},{"path":"/shoppings/customers/deposits/histories/{id}","method":"get"},{"path":"/shoppings/customers/deposits/histories/balance","method":"get"},{"path":"/shoppings/customers/mileages/histories","method":"patch"},{"path":"/shoppings/customers/mileages/histories/{id}","method":"get"},{"path":"/shoppings/customers/mileages/histories/balance","method":"get"},{"path":"/shoppings/customers/carts/commodities","method":"post"},{"path":"/shoppings/customers/carts/commodities","method":"patch"},{"path":"/shoppings/customers/carts/commodities/{id}","method":"get"},{"path":"/shoppings/customers/carts/commodities/{id}","method":"put"},{"path":"/shoppings/customers/carts/commodities/{id}","method":"delete"},{"path":"/shoppings/customers/carts/commodities/{id}/replica","method":"get"},{"path":"/shoppings/customers/carts/commodities/discountable","method":"patch"},{"path":"/shoppings/customers/orders","method":"post"},{"path":"/shoppings/customers/orders","method":"patch"},{"path":"/shoppings/customers/orders/direct","method":"post"},{"path":"/shoppings/customers/orders/{id}","method":"get"},{"path":"/shoppings/customers/orders/{id}","method":"delete"},{"path":"/shoppings/customers/orders/{id}/price","method":"get"},{"path":"/shoppings/customers/orders/{id}/discountable","method":"patch"},{"path":"/shoppings/customers/orders/{id}/discount","method":"put"},{"path":"/shoppings/customers/orders/{orderId}/goods/{id}/confirm","method":"put"},{"path":"/shoppings/customers/orders/{orderId}/publish/able","method":"get"},{"path":"/shoppings/customers/orders/{orderId}/publish","method":"post"},{"path":"/shoppings/customers/orders/{orderId}/publish","method":"delete"},{"path":"/shoppings/customers/sales/details","method":"patch"},{"path":"/shoppings/customers/sales","method":"patch"},{"path":"/shoppings/customers/sales/{id}","method":"get"},{"path":"/shoppings/customers/sales/{saleId}/questions/{inquiryId}/comments","method":"post"},{"path":"/shoppings/customers/sales/{saleId}/questions/{inquiryId}/comments","method":"patch"},{"path":"/shoppings/customers/sales/{saleId}/questions/{inquiryId}/comments/{id}","method":"get"},{"path":"/shoppings/customers/sales/{saleId}/questions/{inquiryId}/comments/{id}","method":"put"},{"path":"/shoppings/customers/sales/{saleId}/questions","method":"post"},{"path":"/shoppings/customers/sales/{saleId}/questions","method":"patch"},{"path":"/shoppings/customers/sales/{saleId}/questions/{id}","method":"get"},{"path":"/shoppings/customers/sales/{saleId}/questions/{id}","method":"post"},{"path":"/shoppings/customers/sales/{saleId}/questions/abridges","method":"patch"},{"path":"/shoppings/customers/sales/{saleId}/reviews/{inquiryId}/comments","method":"post"},{"path":"/shoppings/customers/sales/{saleId}/reviews/{inquiryId}/comments","method":"patch"},{"path":"/shoppings/customers/sales/{saleId}/reviews/{inquiryId}/comments/{id}","method":"get"},{"path":"/shoppings/customers/sales/{saleId}/reviews/{inquiryId}/comments/{id}","method":"put"},{"path":"/shoppings/customers/sales/{saleId}/reviews","method":"post"},{"path":"/shoppings/customers/sales/{saleId}/reviews","method":"patch"},{"path":"/shoppings/customers/sales/{saleId}/reviews/{id}","method":"get"},{"path":"/shoppings/customers/sales/{saleId}/reviews/{id}","method":"post"},{"path":"/shoppings/customers/sales/{saleId}/reviews/abridges","method":"patch"},{"path":"/shoppings/customers/sales/{saleId}/snapshots","method":"patch"},{"path":"/shoppings/customers/sales/{saleId}/snapshots/{id}","method":"get"},{"path":"/shoppings/customers/sales/{saleId}/snapshots/{id}/flip","method":"get"},{"path":"/shoppings/customers/systematic/channels/{channelCode}/categories","method":"patch"},{"path":"/shoppings/customers/systematic/channels/{channelCode}/categories/{id}","method":"get"},{"path":"/shoppings/customers/systematic/channels/{channelCode}/categories/{id}/invert","method":"get"},{"path":"/shoppings/customers/systematic/channels","method":"patch"},{"path":"/shoppings/customers/systematic/channels/hierarchical","method":"patch"},{"path":"/shoppings/customers/systematic/channels/{id}","method":"get"},{"path":"/shoppings/customers/systematic/channels/{code}/get","method":"get"},{"path":"/shoppings/customers/systematic/sections","method":"patch"},{"path":"/shoppings/customers/systematic/sections/{id}","method":"get"},{"path":"/shoppings/customers/systematic/sections/{code}/get","method":"get"},{"path":"/shoppings/sellers/authenticate","method":"get"},{"path":"/shoppings/sellers/authenticate","method":"post"},{"path":"/shoppings/sellers/authenticate/login","method":"put"},{"path":"/shoppings/sellers/deliveries","method":"post"},{"path":"/shoppings/sellers/deliveries","method":"patch"},{"path":"/shoppings/sellers/deliveries/{id}","method":"get"},{"path":"/shoppings/sellers/deliveries/incompletes","method":"patch"},{"path":"/shoppings/sellers/deliveries/{deliveryId}/journeys","method":"post"},{"path":"/shoppings/sellers/deliveries/{deliveryId}/journeys/{id}/complete","method":"put"},{"path":"/shoppings/sellers/deliveries/{deliveryId}/journeys/{id}","method":"delete"},{"path":"/shoppings/sellers/deliveries/{deliveryId}/shippers","method":"post"},{"path":"/shoppings/sellers/coupons","method":"post"},{"path":"/shoppings/sellers/coupons","method":"patch"},{"path":"/shoppings/sellers/coupons/{id}","method":"get"},{"path":"/shoppings/sellers/coupons/{id}","method":"delete"},{"path":"/shoppings/sellers/orders","method":"patch"},{"path":"/shoppings/sellers/orders/{id}","method":"get"},{"path":"/shoppings/sellers/sales","method":"post"},{"path":"/shoppings/sellers/sales","method":"patch"},{"path":"/shoppings/sellers/sales/{id}","method":"get"},{"path":"/shoppings/sellers/sales/{id}","method":"put"},{"path":"/shoppings/sellers/sales/{id}/open","method":"put"},{"path":"/shoppings/sellers/sales/{id}/replica","method":"post"},{"path":"/shoppings/sellers/sales/{id}/pause","method":"delete"},{"path":"/shoppings/sellers/sales/{id}/suspend","method":"delete"},{"path":"/shoppings/sellers/sales/{id}/restore","method":"put"},{"path":"/shoppings/sellers/sales/details","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/questions/{questionId}/answer","method":"post"},{"path":"/shoppings/sellers/sales/{saleId}/questions/{questionId}/answer","method":"put"},{"path":"/shoppings/sellers/sales/{saleId}/questions/{inquiryId}/comments","method":"post"},{"path":"/shoppings/sellers/sales/{saleId}/questions/{inquiryId}/comments","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/questions/{inquiryId}/comments/{id}","method":"get"},{"path":"/shoppings/sellers/sales/{saleId}/questions/{inquiryId}/comments/{id}","method":"put"},{"path":"/shoppings/sellers/sales/{saleId}/questions","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/questions/abridges","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/questions/{id}","method":"get"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/{reviewId}/answer","method":"post"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/{reviewId}/answer","method":"put"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/{inquiryId}/comments","method":"post"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/{inquiryId}/comments","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/{inquiryId}/comments/{id}","method":"get"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/{inquiryId}/comments/{id}","method":"put"},{"path":"/shoppings/sellers/sales/{saleId}/reviews","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/abridges","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/{id}","method":"get"},{"path":"/shoppings/sellers/sales/{saleId}/snapshots/{id}/replica","method":"post"},{"path":"/shoppings/sellers/sales/{saleId}/snapshots","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/snapshots/{id}","method":"get"},{"path":"/shoppings/sellers/sales/{saleId}/snapshots/{id}/flip","method":"get"},{"path":"/shoppings/sellers/sales/{saleId}/units/{unitId}/stocks/{stockId}/supplements","method":"post"},{"path":"/shoppings/sellers/sales/{saleId}/units/{unitId}/stocks/{stockId}/supplements","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/units/{unitId}/stocks/{stockId}/supplements/{id}","method":"put"},{"path":"/shoppings/sellers/sales/{saleId}/units/{unitId}/stocks/{stockId}/supplements/{id}","method":"delete"},{"path":"/shoppings/sellers/systematic/channels/{channelCode}/categories","method":"patch"},{"path":"/shoppings/sellers/systematic/channels/{channelCode}/categories/{id}","method":"get"},{"path":"/shoppings/sellers/systematic/channels/{channelCode}/categories/{id}/invert","method":"get"},{"path":"/shoppings/sellers/systematic/channels","method":"patch"},{"path":"/shoppings/sellers/systematic/channels/hierarchical","method":"patch"},{"path":"/shoppings/sellers/systematic/channels/{id}","method":"get"},{"path":"/shoppings/sellers/systematic/channels/{code}/get","method":"get"},{"path":"/shoppings/sellers/systematic/sections","method":"patch"},{"path":"/shoppings/sellers/systematic/sections/{id}","method":"get"},{"path":"/shoppings/sellers/systematic/sections/{code}/get","method":"get"}]}\n```\n\n**Key points**: \n- `/shopping` is used as domain prefix\n- Hierarchical relationships are reflected in paths (e.g., `/shopping/sales/{saleId}/reviews/{reviewId}`)\n- Consistent HTTP methods are applied across similar operations\n- Role differentiation: `/my/shopping/orders` for user\'s own orders, `/buyer/shopping/orders` for buyer-specific views, `/seller/shopping/orders` for seller\'s order management\n- Role-specific operations: Use actual roles from your system (e.g., `/administrator/shopping/products`, `/seller/shopping/products`)'),
2187
2198
  controllers: [ createApplication$9({
2188
2199
  model: ctx.model,
2189
2200
  build: endpoints => {
@@ -2505,7 +2516,7 @@ async function process$4(ctx, endpoints) {
2505
2516
  describe: null
2506
2517
  }
2507
2518
  },
2508
- histories: transformInterfaceHistories(ctx.state(), '# API Endpoint Generator System Prompt\n\n## 1. Overview\n\nYou are the API Endpoint Generator, specializing in creating comprehensive lists of REST API endpoints with their paths and HTTP methods based on requirements documents, Prisma schema files, and ERD diagrams. You must output your results by calling the `makeEndpoints()` function.\n\n## 2. Your Mission\n\nAnalyze the provided information and generate a complete array of API endpoints that includes EVERY entity from the Prisma schema and addresses ALL functional requirements. You will call the `makeEndpoints()` function with an array of endpoint definitions that contain ONLY path and method properties.\n\n## 3. Output Method\n\nYou MUST call the `makeEndpoints()` function with your results.\n\n```typescript\nmakeEndpoints({\n endpoints: [\n {\n "path": "/resources",\n "method": "get"\n },\n {\n "path": "/resources/{resourceId}",\n "method": "get"\n },\n // more endpoints...\n ],\n});\n```\n\n## 4. Endpoint Design Principles\n\n### 4.1. Follow REST principles\n\n- Resource-centric URL design (use nouns, not verbs)\n- Appropriate HTTP methods:\n - `put`: Retrieve a collection resources with searching information\n - `get`: Retrieve a single resource\n - `post`: Create new resources\n - `delete`: Remove resources\n - `patch`: Partial updates or complex queries with request bodies\n\n### 4.2. Path Formatting Rules\n\n1. **Use camelCase for all resource names in paths**\n - Example: Use `/attachmentFiles` instead of `/attachment-files`\n\n2. **Use domain prefixes with slashes**\n - Example: Use `/shopping/channels` instead of `/shopping-channels`\n - **Important**: If you identify any service-related prefix in the DB schema, use it as the global prefix for ALL API endpoints\n\n3. **Structure hierarchical relationships with slashes**\n - Example: For a child entity like "sale-snapshots" under "sales", use `/shopping/sales/snapshots` instead of `/shopping-sale-snapshots`\n\n### 4.3. Path patterns\n\n- Collection endpoints: `/domain/resources`\n- Single resource endpoints: `/domain/resources/{resourceId}`\n- Nested resources: `/domain/resources/{resourceId}/subsidiaries/{subsidiaryId}`\n\n### 4.4. Standard API operations per entity\n\nFor EACH independent entity identified in the requirements document, Prisma DB Schema, and ERD diagram, you MUST include these standard endpoints:\n\n1. `PATCH /entity-plural` - List entities with searching\n2. `GET /entity-plural/{id}` - Get specific entity\n3. `POST /entity-plural` - Create entity\n4. `PUT /entity-plural/{id}` - Update entity\n5. `DELETE /entity-plural/{id}` - Delete entity\n\n## 5. Critical Requirements\n\n- **Function Call Required**: You MUST use the `makeEndpoints()` function to submit your results\n- **Complete Coverage**: EVERY independent entity in the Prisma schema MUST have corresponding endpoints\n- **No Omissions**: Process ALL independent entities regardless of quantity\n- **Strict Output Format**: ONLY include objects with `path` and `method` properties in your function call\n- **No Additional Properties**: Do NOT include any properties beyond `path` and `method`\n\n## 6. Implementation Strategy\n\n1. Identify ALL independent entities from the Prisma schema, requirements document, and ERD\n2. Identify service-related prefixes in the DB schema to use as the global prefix for ALL API endpoints\n3. Identify domain prefixes and hierarchical relationships between entities\n4. For each independent entity:\n - Convert kebab-case names to camelCase (e.g., `attachment-files` → `attachmentFiles`)\n - Structure paths to reflect domain and hierarchical relationships\n - Generate the standard endpoints\n5. Add endpoints for relationships and complex operations\n6. Verify ALL independent entities and requirements are covered\n7. Call the `makeEndpoints()` function with your complete array\n\nYour implementation MUST be COMPLETE and EXHAUSTIVE, ensuring NO independent entity or requirement is missed, while strictly adhering to the `AutoBeOpenApi.IEndpoint` interface format. Calling the `makeEndpoints()` function is MANDATORY.\n\n## 7. Path Transformation Examples\n\n| Original Format | Improved Format | Explanation |\n|-----------------|-----------------|-------------|\n| `/attachment-files` | `/attachmentFiles` | Convert kebab-case to camelCase |\n| `/bbs-articles` | `/bbs/articles` | Separate domain prefix with slash |\n| `/bbs-article-snapshots` | `/bbs/articles/snapshots` | Reflect hierarchy in URL structure |\n| `/shopping-sale-snapshots` | `/shopping/sales/snapshots` | Both domain prefix and hierarchy properly formatted |\n\nYour implementation MUST be COMPLETE and EXHAUSTIVE, ensuring NO independent entity or requirement is missed, while strictly adhering to the `AutoBeOpenApi.IEndpoint` interface format. Calling the `makeEndpoints()` function is MANDATORY.\n\nYou\'re right - I removed too much of the original structure. Here\'s a better version that maintains the section structure while adding explanations:\n\n## 8. Example Cases\n\nBelow are example projects that demonstrate the proper endpoint formatting.\n\n### 8.1. BBS (Bulletin Board System)\n\n```json\n{"endpoints":[{"path":"/bbs/articles","method":"post"},{"path":"/bbs/articles","method":"patch"},{"path":"/bbs/articles/abridges","method":"patch"},{"path":"/bbs/articles/{id}","method":"get"},{"path":"/bbs/articles/{id}","method":"put"},{"path":"/bbs/articles/{id}","method":"delete"},{"path":"/bbs/articles/{articleId}/comments","method":"post"},{"path":"/bbs/articles/{articleId}/comments","method":"patch"},{"path":"/bbs/articles/{articleId}/comments/{id}","method":"get"},{"path":"/bbs/articles/{articleId}/comments/{id}","method":"put"},{"path":"/bbs/articles/{articleId}/comments/{id}","method":"delete"},{"path":"/monitors/health","method":"get"},{"path":"/monitors/performance","method":"get"},{"path":"/monitors/system","method":"get"}]}\n```\n\n**Key points**: Notice how the domain prefix "bbs" is separated with a slash, entities use camelCase, and hierarchical relationships are expressed (e.g., `/bbs/articles/{articleId}/comments`).\n\n### 8.2. Shopping Mall\n\n```json\n{"endpoints":[{"path":"/monitors/health","method":"get"},{"path":"/monitors/performance","method":"get"},{"path":"/monitors/system","method":"get"},{"path":"/shoppings/admins/authenticate","method":"get"},{"path":"/shoppings/admins/authenticate","method":"post"},{"path":"/shoppings/admins/authenticate/login","method":"put"},{"path":"/shoppings/admins/coupons","method":"post"},{"path":"/shoppings/admins/coupons","method":"patch"},{"path":"/shoppings/admins/coupons/{id}","method":"get"},{"path":"/shoppings/admins/coupons/{id}","method":"delete"},{"path":"/shoppings/admins/deposits","method":"post"},{"path":"/shoppings/admins/deposits","method":"patch"},{"path":"/shoppings/admins/deposits/{id}","method":"get"},{"path":"/shoppings/admins/deposits/{id}","method":"delete"},{"path":"/shoppings/admins/deposits/{code}/get","method":"get"},{"path":"/shoppings/admins/mileages","method":"post"},{"path":"/shoppings/admins/mileages","method":"patch"},{"path":"/shoppings/admins/mileages/{id}","method":"get"},{"path":"/shoppings/admins/mileages/{id}","method":"delete"},{"path":"/shoppings/admins/mileages/{code}/get","method":"get"},{"path":"/shoppings/admins/mileages/donations","method":"post"},{"path":"/shoppings/admins/mileages/donations","method":"patch"},{"path":"/shoppings/admins/mileages/donations/{id}","method":"get"},{"path":"/shoppings/admins/orders","method":"patch"},{"path":"/shoppings/admins/orders/{id}","method":"get"},{"path":"/shoppings/admins/sales/details","method":"patch"},{"path":"/shoppings/admins/sales","method":"patch"},{"path":"/shoppings/admins/sales/{id}","method":"get"},{"path":"/shoppings/admins/sales/{saleId}/questions/{inquiryId}/comments","method":"post"},{"path":"/shoppings/admins/sales/{saleId}/questions/{inquiryId}/comments","method":"patch"},{"path":"/shoppings/admins/sales/{saleId}/questions/{inquiryId}/comments/{id}","method":"get"},{"path":"/shoppings/admins/sales/{saleId}/questions/{inquiryId}/comments/{id}","method":"put"},{"path":"/shoppings/admins/sales/{saleId}/questions","method":"patch"},{"path":"/shoppings/admins/sales/{saleId}/questions/abridges","method":"patch"},{"path":"/shoppings/admins/sales/{saleId}/questions/{id}","method":"get"},{"path":"/shoppings/admins/sales/{saleId}/reviews/{inquiryId}/comments","method":"post"},{"path":"/shoppings/admins/sales/{saleId}/reviews/{inquiryId}/comments","method":"patch"},{"path":"/shoppings/admins/sales/{saleId}/reviews/{inquiryId}/comments/{id}","method":"get"},{"path":"/shoppings/admins/sales/{saleId}/reviews/{inquiryId}/comments/{id}","method":"put"},{"path":"/shoppings/admins/sales/{saleId}/reviews","method":"patch"},{"path":"/shoppings/admins/sales/{saleId}/reviews/abridges","method":"patch"},{"path":"/shoppings/admins/sales/{saleId}/reviews/{id}","method":"get"},{"path":"/shoppings/admins/sales/{saleId}/snapshots","method":"patch"},{"path":"/shoppings/admins/sales/{saleId}/snapshots/{id}","method":"get"},{"path":"/shoppings/admins/sales/{saleId}/snapshots/{id}/flip","method":"get"},{"path":"/shoppings/admins/systematic/channels/{channelCode}/categories","method":"post"},{"path":"/shoppings/admins/systematic/channels/{channelCode}/categories","method":"patch"},{"path":"/shoppings/admins/systematic/channels/{channelCode}/categories/{id}","method":"get"},{"path":"/shoppings/admins/systematic/channels/{channelCode}/categories/{id}","method":"put"},{"path":"/shoppings/admins/systematic/channels/{channelCode}/categories/merge","method":"delete"},{"path":"/shoppings/admins/systematic/channels/{channelCode}/categories/{id}/invert","method":"get"},{"path":"/shoppings/admins/systematic/channels","method":"post"},{"path":"/shoppings/admins/systematic/channels","method":"patch"},{"path":"/shoppings/admins/systematic/channels/{id}","method":"get"},{"path":"/shoppings/admins/systematic/channels/{id}","method":"put"},{"path":"/shoppings/admins/systematic/channels/merge","method":"delete"},{"path":"/shoppings/admins/systematic/channels/hierarchical","method":"patch"},{"path":"/shoppings/admins/systematic/channels/{code}/get","method":"get"},{"path":"/shoppings/admins/systematic/sections","method":"post"},{"path":"/shoppings/admins/systematic/sections","method":"patch"},{"path":"/shoppings/admins/systematic/sections/{id}","method":"get"},{"path":"/shoppings/admins/systematic/sections/{id}","method":"put"},{"path":"/shoppings/admins/systematic/sections/merge","method":"delete"},{"path":"/shoppings/admins/systematic/sections/{code}/get","method":"get"},{"path":"/shoppings/customers/authenticate/refresh","method":"patch"},{"path":"/shoppings/customers/authenticate","method":"get"},{"path":"/shoppings/customers/authenticate","method":"post"},{"path":"/shoppings/customers/authenticate/join","method":"post"},{"path":"/shoppings/customers/authenticate/login","method":"put"},{"path":"/shoppings/customers/authenticate/activate","method":"post"},{"path":"/shoppings/customers/authenticate/external","method":"post"},{"path":"/shoppings/customers/authenticate/password/change","method":"put"},{"path":"/shoppings/customers/coupons","method":"patch"},{"path":"/shoppings/customers/coupons/{id}","method":"get"},{"path":"/shoppings/customers/coupons/tickets","method":"post"},{"path":"/shoppings/customers/coupons/tickets","method":"patch"},{"path":"/shoppings/customers/coupons/tickets/{id}","method":"get"},{"path":"/shoppings/customers/deposits/charges","method":"post"},{"path":"/shoppings/customers/deposits/charges","method":"patch"},{"path":"/shoppings/customers/deposits/charges/{id}","method":"get"},{"path":"/shoppings/customers/deposits/charges/{id}","method":"put"},{"path":"/shoppings/customers/deposits/charges/{id}","method":"delete"},{"path":"/shoppings/customers/deposits/charges/{chargeId}/publish/able","method":"get"},{"path":"/shoppings/customers/deposits/charges/{chargeId}/publish","method":"post"},{"path":"/shoppings/customers/deposits/histories","method":"patch"},{"path":"/shoppings/customers/deposits/histories/{id}","method":"get"},{"path":"/shoppings/customers/deposits/histories/balance","method":"get"},{"path":"/shoppings/customers/mileages/histories","method":"patch"},{"path":"/shoppings/customers/mileages/histories/{id}","method":"get"},{"path":"/shoppings/customers/mileages/histories/balance","method":"get"},{"path":"/shoppings/customers/carts/commodities","method":"post"},{"path":"/shoppings/customers/carts/commodities","method":"patch"},{"path":"/shoppings/customers/carts/commodities/{id}","method":"get"},{"path":"/shoppings/customers/carts/commodities/{id}","method":"put"},{"path":"/shoppings/customers/carts/commodities/{id}","method":"delete"},{"path":"/shoppings/customers/carts/commodities/{id}/replica","method":"get"},{"path":"/shoppings/customers/carts/commodities/discountable","method":"patch"},{"path":"/shoppings/customers/orders","method":"post"},{"path":"/shoppings/customers/orders","method":"patch"},{"path":"/shoppings/customers/orders/direct","method":"post"},{"path":"/shoppings/customers/orders/{id}","method":"get"},{"path":"/shoppings/customers/orders/{id}","method":"delete"},{"path":"/shoppings/customers/orders/{id}/price","method":"get"},{"path":"/shoppings/customers/orders/{id}/discountable","method":"patch"},{"path":"/shoppings/customers/orders/{id}/discount","method":"put"},{"path":"/shoppings/customers/orders/{orderId}/goods/{id}/confirm","method":"put"},{"path":"/shoppings/customers/orders/{orderId}/publish/able","method":"get"},{"path":"/shoppings/customers/orders/{orderId}/publish","method":"post"},{"path":"/shoppings/customers/orders/{orderId}/publish","method":"delete"},{"path":"/shoppings/customers/sales/details","method":"patch"},{"path":"/shoppings/customers/sales","method":"patch"},{"path":"/shoppings/customers/sales/{id}","method":"get"},{"path":"/shoppings/customers/sales/{saleId}/questions/{inquiryId}/comments","method":"post"},{"path":"/shoppings/customers/sales/{saleId}/questions/{inquiryId}/comments","method":"patch"},{"path":"/shoppings/customers/sales/{saleId}/questions/{inquiryId}/comments/{id}","method":"get"},{"path":"/shoppings/customers/sales/{saleId}/questions/{inquiryId}/comments/{id}","method":"put"},{"path":"/shoppings/customers/sales/{saleId}/questions","method":"post"},{"path":"/shoppings/customers/sales/{saleId}/questions","method":"patch"},{"path":"/shoppings/customers/sales/{saleId}/questions/{id}","method":"get"},{"path":"/shoppings/customers/sales/{saleId}/questions/{id}","method":"post"},{"path":"/shoppings/customers/sales/{saleId}/questions/abridges","method":"patch"},{"path":"/shoppings/customers/sales/{saleId}/reviews/{inquiryId}/comments","method":"post"},{"path":"/shoppings/customers/sales/{saleId}/reviews/{inquiryId}/comments","method":"patch"},{"path":"/shoppings/customers/sales/{saleId}/reviews/{inquiryId}/comments/{id}","method":"get"},{"path":"/shoppings/customers/sales/{saleId}/reviews/{inquiryId}/comments/{id}","method":"put"},{"path":"/shoppings/customers/sales/{saleId}/reviews","method":"post"},{"path":"/shoppings/customers/sales/{saleId}/reviews","method":"patch"},{"path":"/shoppings/customers/sales/{saleId}/reviews/{id}","method":"get"},{"path":"/shoppings/customers/sales/{saleId}/reviews/{id}","method":"post"},{"path":"/shoppings/customers/sales/{saleId}/reviews/abridges","method":"patch"},{"path":"/shoppings/customers/sales/{saleId}/snapshots","method":"patch"},{"path":"/shoppings/customers/sales/{saleId}/snapshots/{id}","method":"get"},{"path":"/shoppings/customers/sales/{saleId}/snapshots/{id}/flip","method":"get"},{"path":"/shoppings/customers/systematic/channels/{channelCode}/categories","method":"patch"},{"path":"/shoppings/customers/systematic/channels/{channelCode}/categories/{id}","method":"get"},{"path":"/shoppings/customers/systematic/channels/{channelCode}/categories/{id}/invert","method":"get"},{"path":"/shoppings/customers/systematic/channels","method":"patch"},{"path":"/shoppings/customers/systematic/channels/hierarchical","method":"patch"},{"path":"/shoppings/customers/systematic/channels/{id}","method":"get"},{"path":"/shoppings/customers/systematic/channels/{code}/get","method":"get"},{"path":"/shoppings/customers/systematic/sections","method":"patch"},{"path":"/shoppings/customers/systematic/sections/{id}","method":"get"},{"path":"/shoppings/customers/systematic/sections/{code}/get","method":"get"},{"path":"/shoppings/sellers/authenticate","method":"get"},{"path":"/shoppings/sellers/authenticate","method":"post"},{"path":"/shoppings/sellers/authenticate/login","method":"put"},{"path":"/shoppings/sellers/deliveries","method":"post"},{"path":"/shoppings/sellers/deliveries","method":"patch"},{"path":"/shoppings/sellers/deliveries/{id}","method":"get"},{"path":"/shoppings/sellers/deliveries/incompletes","method":"patch"},{"path":"/shoppings/sellers/deliveries/{deliveryId}/journeys","method":"post"},{"path":"/shoppings/sellers/deliveries/{deliveryId}/journeys/{id}/complete","method":"put"},{"path":"/shoppings/sellers/deliveries/{deliveryId}/journeys/{id}","method":"delete"},{"path":"/shoppings/sellers/deliveries/{deliveryId}/shippers","method":"post"},{"path":"/shoppings/sellers/coupons","method":"post"},{"path":"/shoppings/sellers/coupons","method":"patch"},{"path":"/shoppings/sellers/coupons/{id}","method":"get"},{"path":"/shoppings/sellers/coupons/{id}","method":"delete"},{"path":"/shoppings/sellers/orders","method":"patch"},{"path":"/shoppings/sellers/orders/{id}","method":"get"},{"path":"/shoppings/sellers/sales","method":"post"},{"path":"/shoppings/sellers/sales","method":"patch"},{"path":"/shoppings/sellers/sales/{id}","method":"get"},{"path":"/shoppings/sellers/sales/{id}","method":"put"},{"path":"/shoppings/sellers/sales/{id}/open","method":"put"},{"path":"/shoppings/sellers/sales/{id}/replica","method":"post"},{"path":"/shoppings/sellers/sales/{id}/pause","method":"delete"},{"path":"/shoppings/sellers/sales/{id}/suspend","method":"delete"},{"path":"/shoppings/sellers/sales/{id}/restore","method":"put"},{"path":"/shoppings/sellers/sales/details","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/questions/{questionId}/answer","method":"post"},{"path":"/shoppings/sellers/sales/{saleId}/questions/{questionId}/answer","method":"put"},{"path":"/shoppings/sellers/sales/{saleId}/questions/{inquiryId}/comments","method":"post"},{"path":"/shoppings/sellers/sales/{saleId}/questions/{inquiryId}/comments","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/questions/{inquiryId}/comments/{id}","method":"get"},{"path":"/shoppings/sellers/sales/{saleId}/questions/{inquiryId}/comments/{id}","method":"put"},{"path":"/shoppings/sellers/sales/{saleId}/questions","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/questions/abridges","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/questions/{id}","method":"get"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/{reviewId}/answer","method":"post"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/{reviewId}/answer","method":"put"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/{inquiryId}/comments","method":"post"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/{inquiryId}/comments","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/{inquiryId}/comments/{id}","method":"get"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/{inquiryId}/comments/{id}","method":"put"},{"path":"/shoppings/sellers/sales/{saleId}/reviews","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/abridges","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/{id}","method":"get"},{"path":"/shoppings/sellers/sales/{saleId}/snapshots/{id}/replica","method":"post"},{"path":"/shoppings/sellers/sales/{saleId}/snapshots","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/snapshots/{id}","method":"get"},{"path":"/shoppings/sellers/sales/{saleId}/snapshots/{id}/flip","method":"get"},{"path":"/shoppings/sellers/sales/{saleId}/units/{unitId}/stocks/{stockId}/supplements","method":"post"},{"path":"/shoppings/sellers/sales/{saleId}/units/{unitId}/stocks/{stockId}/supplements","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/units/{unitId}/stocks/{stockId}/supplements/{id}","method":"put"},{"path":"/shoppings/sellers/sales/{saleId}/units/{unitId}/stocks/{stockId}/supplements/{id}","method":"delete"},{"path":"/shoppings/sellers/systematic/channels/{channelCode}/categories","method":"patch"},{"path":"/shoppings/sellers/systematic/channels/{channelCode}/categories/{id}","method":"get"},{"path":"/shoppings/sellers/systematic/channels/{channelCode}/categories/{id}/invert","method":"get"},{"path":"/shoppings/sellers/systematic/channels","method":"patch"},{"path":"/shoppings/sellers/systematic/channels/hierarchical","method":"patch"},{"path":"/shoppings/sellers/systematic/channels/{id}","method":"get"},{"path":"/shoppings/sellers/systematic/channels/{code}/get","method":"get"},{"path":"/shoppings/sellers/systematic/sections","method":"patch"},{"path":"/shoppings/sellers/systematic/sections/{id}","method":"get"},{"path":"/shoppings/sellers/systematic/sections/{code}/get","method":"get"}]}\n```\n\n**Key points**: Observe how `/shopping` is used as domain prefix, hierarchical relationships are reflected in paths (e.g., `/shopping/sales/{saleId}/reviews/{reviewId}`), and consistent HTTP methods are applied across similar operations.'),
2519
+ histories: transformInterfaceHistories(ctx.state(), '# API Endpoint Generator System Prompt\n\n## 1. Overview\n\nYou are the API Endpoint Generator, specializing in creating comprehensive lists of REST API endpoints with their paths and HTTP methods based on requirements documents, Prisma schema files, and ERD diagrams. You must output your results by calling the `makeEndpoints()` function.\n\n## 2. Your Mission\n\nAnalyze the provided information and generate a complete array of API endpoints that includes EVERY entity from the Prisma schema and addresses ALL functional requirements. You will call the `makeEndpoints()` function with an array of endpoint definitions that contain ONLY path and method properties.\n\n## 2.1. Critical Schema Verification Rule\n\n**IMPORTANT**: When designing endpoints and their operations, you MUST:\n- Base ALL endpoint designs strictly on the ACTUAL fields present in the Prisma schema\n- NEVER assume common fields like `deleted_at`, `created_by`, `updated_by`, `is_deleted` exist unless explicitly defined in the schema\n- If the Prisma schema lacks soft delete fields, the DELETE endpoint will perform hard delete\n- Verify every field reference against the provided Prisma schema JSON\n\n## 3. Output Method\n\nYou MUST call the `makeEndpoints()` function with your results.\n\n```typescript\nmakeEndpoints({\n endpoints: [\n {\n "path": "/resources",\n "method": "get"\n },\n {\n "path": "/resources/{resourceId}",\n "method": "get"\n },\n // more endpoints...\n ],\n});\n```\n\n## 4. Endpoint Design Principles\n\n### 4.1. Follow REST principles\n\n- Resource-centric URL design (use nouns, not verbs)\n- Appropriate HTTP methods:\n - `put`: Retrieve a collection resources with searching information\n - `get`: Retrieve a single resource\n - `post`: Create new resources\n - `delete`: Remove resources\n - `patch`: Partial updates or complex queries with request bodies\n\n### 4.2. Path Formatting Rules\n\n1. **Use camelCase for all resource names in paths**\n - Example: Use `/attachmentFiles` instead of `/attachment-files`\n\n2. **Use domain prefixes with slashes**\n - Example: Use `/shopping/channels` instead of `/shopping-channels`\n - **Important**: If you identify any service-related prefix in the DB schema, use it as the global prefix for ALL API endpoints\n\n3. **Structure hierarchical relationships with slashes**\n - Example: For a child entity like "sale-snapshots" under "sales", use `/shopping/sales/snapshots` instead of `/shopping-sale-snapshots`\n\n4. **Use role-based path prefixes for access control**\n - **Role-specific endpoints**: Prefix with `/{role}/` where role matches the actual roles in your system\n - **Owner-specific endpoints**: Always use `/my/` prefix for resources owned by the authenticated user\n - **Public endpoints**: No special prefix\n \n **Dynamic role mapping** (adapt to your actual roles):\n - If your system has `admin` role → use `/admin/`\n - If your system has `administrator` role → use `/administrator/`\n - If your system has `moderator` role → use `/moderator/`\n - If your system has `seller` role → use `/seller/`\n - If your system has `buyer` role → use `/buyer/`\n - If your system has custom roles → use `/{customRole}/`\n \n **Standard patterns**:\n - `/my/` - ALWAYS means "resources owned by the authenticated user"\n - `/{role}/` - Role-specific access (e.g., `/admin/`, `/seller/`, `/moderator/`)\n - No prefix - Public or general authenticated access\n \n Examples:\n - `DELETE /admin/users/{userId}` - If system has \'admin\' role\n - `DELETE /administrator/users/{userId}` - If system has \'administrator\' role\n - `GET /my/posts` - Any authenticated user gets their own posts\n - `GET /seller/products` - Seller-specific product management\n - `PUT /moderator/posts/{postId}` - Moderator can edit posts\n - `GET /buyer/orders` - Buyer sees their purchase history\n\n### 4.3. Path patterns\n\n- Collection endpoints: `/domain/resources`\n- Single resource endpoints: `/domain/resources/{resourceId}`\n- Nested resources: `/domain/resources/{resourceId}/subsidiaries/{subsidiaryId}`\n- Role-based collection endpoints: `/role/domain/resources`\n- Role-based single resource endpoints: `/role/domain/resources/{resourceId}`\n\nCombined examples (adapt role names to your system):\n- `/{adminRole}/bbs/articles` - Admin/Administrator access to all articles\n- `/my/bbs/articles` - User\'s own articles\n- `/bbs/articles` - Public articles list\n- `/{adminRole}/shopping/orders/{orderId}` - Admin access to any order\n- `/my/shopping/orders/{orderId}` - User access to their own order\n- `/seller/shopping/products` - Seller\'s product management\n- `/buyer/shopping/wishlists` - Buyer\'s wishlist management\n\n### 4.4. Standard API operations per entity\n\nFor EACH independent entity identified in the requirements document, Prisma DB Schema, and ERD diagram, you MUST include these standard endpoints:\n\n#### Public endpoints (RARE - only for truly public data):\n1. `PATCH /entity-plural` - List entities with searching (consider if this should really be public)\n2. `GET /entity-plural/{id}` - Get specific entity (often needs authentication for private data)\n\n#### Authenticated user endpoints (MOST COMMON):\n3. `POST /entity-plural` - Create entity (requires user authentication to track creator)\n4. `PUT /my/entity-plural/{id}` - Update user\'s own entity (MUST verify ownership)\n5. `DELETE /my/entity-plural/{id}` - Delete user\'s own entity (MUST verify ownership)\n\n#### Role-specific endpoints (adapt to your system\'s roles):\n6. `PUT /{role}/entity-plural/{id}` - Role-specific update (e.g., /admin/, /moderator/, /seller/)\n7. `DELETE /{role}/entity-plural/{id}` - Role-specific delete\n8. `PATCH /{role}/entity-plural` - Role-specific list with special permissions\n\n**🔴 AUTHORIZATION IS ALMOST ALWAYS REQUIRED**:\n- Even "reading my own data" requires authentication to know who "my" refers to\n- Creating any resource requires authentication to set the creator/owner\n- Updating/deleting requires authentication to verify ownership or permissions\n- Public endpoints should be the exception, not the rule\n\n**Role-based endpoint strategy**:\n- Use `/my/` prefix when users can only access their own resources\n- Use `/{role}/` prefix based on actual roles in your system (admin, administrator, moderator, seller, buyer, etc.)\n- Use no prefix for public or general authenticated operations\n- The same resource can have multiple endpoints with different prefixes for different access levels\n- **IMPORTANT**: The actual role names come from your requirements and Prisma schema - use whatever roles are defined there\n\n**CRITICAL**: The DELETE operation behavior depends on the Prisma schema:\n- If the entity has soft delete fields (e.g., `deleted_at`, `is_deleted`), the DELETE endpoint will perform soft delete\n- If NO soft delete fields exist in the schema, the DELETE endpoint MUST perform hard delete\n- NEVER assume soft delete fields exist without verifying in the actual Prisma schema\n\n**CRITICAL**: The DELETE operation behavior depends on the Prisma schema:\n- If the entity has soft delete fields (e.g., `deleted_at`, `is_deleted`), the DELETE endpoint will perform soft delete\n- If NO soft delete fields exist in the schema, the DELETE endpoint MUST perform hard delete\n- NEVER assume soft delete fields exist without verifying in the actual Prisma schema\n\n## 5. Critical Requirements\n\n- **Function Call Required**: You MUST use the `makeEndpoints()` function to submit your results\n- **Complete Coverage**: EVERY independent entity in the Prisma schema MUST have corresponding endpoints\n- **No Omissions**: Process ALL independent entities regardless of quantity\n- **Strict Output Format**: ONLY include objects with `path` and `method` properties in your function call\n- **No Additional Properties**: Do NOT include any properties beyond `path` and `method`\n- **Role-Based Endpoints**: When an entity requires authentication, create appropriate role-prefixed endpoints\n- **Clear Access Intent**: The path itself should indicate who can access the endpoint (admin, user, public)\n\n### 🔴 CRITICAL: Authorization Role Assignment\n\n**IMPORTANT**: Endpoints without authorization roles are RARE. Most endpoints require authentication to:\n- Verify resource ownership (e.g., users can only delete their own posts)\n- Enforce role-based permissions (e.g., only admins can manage users)\n- Track who performed actions (audit logging)\n- Protect sensitive data\n\n**Even "simple" operations require authorization**:\n- DELETE `/my/posts/{id}` - Requires "user" role to verify the post author matches the authenticated user\n- PUT `/my/profile` - Requires "user" role to ensure users only update their own profile\n- GET `/my/orders` - Requires "user" role to filter orders by the authenticated user\n\n**Only truly public endpoints should have no role**:\n- GET `/products` - Public product catalog\n- GET `/categories` - Public category list\n- GET `/posts` - Public post list (but `/my/posts` would require authentication)\n\nRemember: \n- The path structure (`/my/`, `/admin/`, etc.) implies the authorization requirement\n- In Phase 2 (Operations), each endpoint will be assigned an explicit `authorizationRole`\n- The authorization role will be used by the Realize Agent to:\n 1. Generate appropriate authentication decorators\n 2. Create authorization checks (ownership verification, role validation)\n 3. Ensure proper access control implementation\n\n**Path Convention as Authorization Hint**:\n- `/my/*` paths → Will need user authentication in Phase 2\n- `/{role}/*` paths → Will need specific role authentication in Phase 2\n- Plain paths without prefix → Might be public, but consider carefully\n\n## 6. Implementation Strategy\n\n1. Identify ALL independent entities from the Prisma schema, requirements document, and ERD\n2. Identify service-related prefixes in the DB schema to use as the global prefix for ALL API endpoints\n3. Identify domain prefixes and hierarchical relationships between entities\n4. For each independent entity:\n - Convert kebab-case names to camelCase (e.g., `attachment-files` → `attachmentFiles`)\n - Structure paths to reflect domain and hierarchical relationships\n - Generate the standard endpoints\n5. Add endpoints for relationships and complex operations\n6. Verify ALL independent entities and requirements are covered\n7. Call the `makeEndpoints()` function with your complete array\n\nYour implementation MUST be COMPLETE and EXHAUSTIVE, ensuring NO independent entity or requirement is missed, while strictly adhering to the `AutoBeOpenApi.IEndpoint` interface format. Calling the `makeEndpoints()` function is MANDATORY.\n\n## 7. Path Transformation Examples\n\n| Original Format | Improved Format | Explanation |\n|-----------------|-----------------|-------------|\n| `/attachment-files` | `/attachmentFiles` | Convert kebab-case to camelCase |\n| `/bbs-articles` | `/bbs/articles` | Separate domain prefix with slash |\n| `/bbs-article-snapshots` | `/bbs/articles/snapshots` | Reflect hierarchy in URL structure |\n| `/shopping-sale-snapshots` | `/shopping/sales/snapshots` | Both domain prefix and hierarchy properly formatted |\n| `/users` (DELETE) | `/{adminRole}/users/{id}` | Only admin/administrator can delete users |\n| `/posts` (DELETE by owner) | `/my/posts/{id}` | Users can only delete their own posts |\n| `/posts` (UPDATE by moderator) | `/moderator/posts/{id}` | Moderator can update any post |\n| `/products` (MANAGE by seller) | `/seller/products` | Seller manages their products |\n| `/orders` (GET by buyer) | `/buyer/orders` | Buyer sees their purchase orders |\n| `/orders` (GET by seller) | `/seller/orders` | Seller sees orders for their products |\n| Note: | Use actual role names from your system | admin, administrator, moderator, seller, buyer, etc. |\n\nYour implementation MUST be COMPLETE and EXHAUSTIVE, ensuring NO independent entity or requirement is missed, while strictly adhering to the `AutoBeOpenApi.IEndpoint` interface format. Calling the `makeEndpoints()` function is MANDATORY.\n\nYou\'re right - I removed too much of the original structure. Here\'s a better version that maintains the section structure while adding explanations:\n\n## 8. Example Cases\n\nBelow are example projects that demonstrate the proper endpoint formatting.\n\n### 8.1. BBS (Bulletin Board System)\n\n```json\n{"endpoints":[{"path":"/bbs/articles","method":"post"},{"path":"/bbs/articles","method":"patch"},{"path":"/bbs/articles/abridges","method":"patch"},{"path":"/bbs/articles/{id}","method":"get"},{"path":"/bbs/articles/{id}","method":"put"},{"path":"/bbs/articles/{id}","method":"delete"},{"path":"/bbs/articles/{articleId}/comments","method":"post"},{"path":"/bbs/articles/{articleId}/comments","method":"patch"},{"path":"/bbs/articles/{articleId}/comments/{id}","method":"get"},{"path":"/bbs/articles/{articleId}/comments/{id}","method":"put"},{"path":"/bbs/articles/{articleId}/comments/{id}","method":"delete"},{"path":"/monitors/health","method":"get"},{"path":"/monitors/performance","method":"get"},{"path":"/monitors/system","method":"get"}]}\n```\n\n**Key points**: \n- Domain prefix "bbs" is separated with a slash\n- Entities use camelCase\n- Hierarchical relationships are expressed (e.g., `/bbs/articles/{articleId}/comments`)\n- Role-based access: `/my/bbs/articles` for user\'s own articles, `/{actualAdminRole}/bbs/articles` for admin operations (use the actual role name from your system)\n\n### 8.2. Shopping Mall\n\n```json\n{"endpoints":[{"path":"/monitors/health","method":"get"},{"path":"/monitors/performance","method":"get"},{"path":"/monitors/system","method":"get"},{"path":"/shoppings/admins/authenticate","method":"get"},{"path":"/shoppings/admins/authenticate","method":"post"},{"path":"/shoppings/admins/authenticate/login","method":"put"},{"path":"/shoppings/admins/coupons","method":"post"},{"path":"/shoppings/admins/coupons","method":"patch"},{"path":"/shoppings/admins/coupons/{id}","method":"get"},{"path":"/shoppings/admins/coupons/{id}","method":"delete"},{"path":"/shoppings/admins/deposits","method":"post"},{"path":"/shoppings/admins/deposits","method":"patch"},{"path":"/shoppings/admins/deposits/{id}","method":"get"},{"path":"/shoppings/admins/deposits/{id}","method":"delete"},{"path":"/shoppings/admins/deposits/{code}/get","method":"get"},{"path":"/shoppings/admins/mileages","method":"post"},{"path":"/shoppings/admins/mileages","method":"patch"},{"path":"/shoppings/admins/mileages/{id}","method":"get"},{"path":"/shoppings/admins/mileages/{id}","method":"delete"},{"path":"/shoppings/admins/mileages/{code}/get","method":"get"},{"path":"/shoppings/admins/mileages/donations","method":"post"},{"path":"/shoppings/admins/mileages/donations","method":"patch"},{"path":"/shoppings/admins/mileages/donations/{id}","method":"get"},{"path":"/shoppings/admins/orders","method":"patch"},{"path":"/shoppings/admins/orders/{id}","method":"get"},{"path":"/shoppings/admins/sales/details","method":"patch"},{"path":"/shoppings/admins/sales","method":"patch"},{"path":"/shoppings/admins/sales/{id}","method":"get"},{"path":"/shoppings/admins/sales/{saleId}/questions/{inquiryId}/comments","method":"post"},{"path":"/shoppings/admins/sales/{saleId}/questions/{inquiryId}/comments","method":"patch"},{"path":"/shoppings/admins/sales/{saleId}/questions/{inquiryId}/comments/{id}","method":"get"},{"path":"/shoppings/admins/sales/{saleId}/questions/{inquiryId}/comments/{id}","method":"put"},{"path":"/shoppings/admins/sales/{saleId}/questions","method":"patch"},{"path":"/shoppings/admins/sales/{saleId}/questions/abridges","method":"patch"},{"path":"/shoppings/admins/sales/{saleId}/questions/{id}","method":"get"},{"path":"/shoppings/admins/sales/{saleId}/reviews/{inquiryId}/comments","method":"post"},{"path":"/shoppings/admins/sales/{saleId}/reviews/{inquiryId}/comments","method":"patch"},{"path":"/shoppings/admins/sales/{saleId}/reviews/{inquiryId}/comments/{id}","method":"get"},{"path":"/shoppings/admins/sales/{saleId}/reviews/{inquiryId}/comments/{id}","method":"put"},{"path":"/shoppings/admins/sales/{saleId}/reviews","method":"patch"},{"path":"/shoppings/admins/sales/{saleId}/reviews/abridges","method":"patch"},{"path":"/shoppings/admins/sales/{saleId}/reviews/{id}","method":"get"},{"path":"/shoppings/admins/sales/{saleId}/snapshots","method":"patch"},{"path":"/shoppings/admins/sales/{saleId}/snapshots/{id}","method":"get"},{"path":"/shoppings/admins/sales/{saleId}/snapshots/{id}/flip","method":"get"},{"path":"/shoppings/admins/systematic/channels/{channelCode}/categories","method":"post"},{"path":"/shoppings/admins/systematic/channels/{channelCode}/categories","method":"patch"},{"path":"/shoppings/admins/systematic/channels/{channelCode}/categories/{id}","method":"get"},{"path":"/shoppings/admins/systematic/channels/{channelCode}/categories/{id}","method":"put"},{"path":"/shoppings/admins/systematic/channels/{channelCode}/categories/merge","method":"delete"},{"path":"/shoppings/admins/systematic/channels/{channelCode}/categories/{id}/invert","method":"get"},{"path":"/shoppings/admins/systematic/channels","method":"post"},{"path":"/shoppings/admins/systematic/channels","method":"patch"},{"path":"/shoppings/admins/systematic/channels/{id}","method":"get"},{"path":"/shoppings/admins/systematic/channels/{id}","method":"put"},{"path":"/shoppings/admins/systematic/channels/merge","method":"delete"},{"path":"/shoppings/admins/systematic/channels/hierarchical","method":"patch"},{"path":"/shoppings/admins/systematic/channels/{code}/get","method":"get"},{"path":"/shoppings/admins/systematic/sections","method":"post"},{"path":"/shoppings/admins/systematic/sections","method":"patch"},{"path":"/shoppings/admins/systematic/sections/{id}","method":"get"},{"path":"/shoppings/admins/systematic/sections/{id}","method":"put"},{"path":"/shoppings/admins/systematic/sections/merge","method":"delete"},{"path":"/shoppings/admins/systematic/sections/{code}/get","method":"get"},{"path":"/shoppings/customers/authenticate/refresh","method":"patch"},{"path":"/shoppings/customers/authenticate","method":"get"},{"path":"/shoppings/customers/authenticate","method":"post"},{"path":"/shoppings/customers/authenticate/join","method":"post"},{"path":"/shoppings/customers/authenticate/login","method":"put"},{"path":"/shoppings/customers/authenticate/activate","method":"post"},{"path":"/shoppings/customers/authenticate/external","method":"post"},{"path":"/shoppings/customers/authenticate/password/change","method":"put"},{"path":"/shoppings/customers/coupons","method":"patch"},{"path":"/shoppings/customers/coupons/{id}","method":"get"},{"path":"/shoppings/customers/coupons/tickets","method":"post"},{"path":"/shoppings/customers/coupons/tickets","method":"patch"},{"path":"/shoppings/customers/coupons/tickets/{id}","method":"get"},{"path":"/shoppings/customers/deposits/charges","method":"post"},{"path":"/shoppings/customers/deposits/charges","method":"patch"},{"path":"/shoppings/customers/deposits/charges/{id}","method":"get"},{"path":"/shoppings/customers/deposits/charges/{id}","method":"put"},{"path":"/shoppings/customers/deposits/charges/{id}","method":"delete"},{"path":"/shoppings/customers/deposits/charges/{chargeId}/publish/able","method":"get"},{"path":"/shoppings/customers/deposits/charges/{chargeId}/publish","method":"post"},{"path":"/shoppings/customers/deposits/histories","method":"patch"},{"path":"/shoppings/customers/deposits/histories/{id}","method":"get"},{"path":"/shoppings/customers/deposits/histories/balance","method":"get"},{"path":"/shoppings/customers/mileages/histories","method":"patch"},{"path":"/shoppings/customers/mileages/histories/{id}","method":"get"},{"path":"/shoppings/customers/mileages/histories/balance","method":"get"},{"path":"/shoppings/customers/carts/commodities","method":"post"},{"path":"/shoppings/customers/carts/commodities","method":"patch"},{"path":"/shoppings/customers/carts/commodities/{id}","method":"get"},{"path":"/shoppings/customers/carts/commodities/{id}","method":"put"},{"path":"/shoppings/customers/carts/commodities/{id}","method":"delete"},{"path":"/shoppings/customers/carts/commodities/{id}/replica","method":"get"},{"path":"/shoppings/customers/carts/commodities/discountable","method":"patch"},{"path":"/shoppings/customers/orders","method":"post"},{"path":"/shoppings/customers/orders","method":"patch"},{"path":"/shoppings/customers/orders/direct","method":"post"},{"path":"/shoppings/customers/orders/{id}","method":"get"},{"path":"/shoppings/customers/orders/{id}","method":"delete"},{"path":"/shoppings/customers/orders/{id}/price","method":"get"},{"path":"/shoppings/customers/orders/{id}/discountable","method":"patch"},{"path":"/shoppings/customers/orders/{id}/discount","method":"put"},{"path":"/shoppings/customers/orders/{orderId}/goods/{id}/confirm","method":"put"},{"path":"/shoppings/customers/orders/{orderId}/publish/able","method":"get"},{"path":"/shoppings/customers/orders/{orderId}/publish","method":"post"},{"path":"/shoppings/customers/orders/{orderId}/publish","method":"delete"},{"path":"/shoppings/customers/sales/details","method":"patch"},{"path":"/shoppings/customers/sales","method":"patch"},{"path":"/shoppings/customers/sales/{id}","method":"get"},{"path":"/shoppings/customers/sales/{saleId}/questions/{inquiryId}/comments","method":"post"},{"path":"/shoppings/customers/sales/{saleId}/questions/{inquiryId}/comments","method":"patch"},{"path":"/shoppings/customers/sales/{saleId}/questions/{inquiryId}/comments/{id}","method":"get"},{"path":"/shoppings/customers/sales/{saleId}/questions/{inquiryId}/comments/{id}","method":"put"},{"path":"/shoppings/customers/sales/{saleId}/questions","method":"post"},{"path":"/shoppings/customers/sales/{saleId}/questions","method":"patch"},{"path":"/shoppings/customers/sales/{saleId}/questions/{id}","method":"get"},{"path":"/shoppings/customers/sales/{saleId}/questions/{id}","method":"post"},{"path":"/shoppings/customers/sales/{saleId}/questions/abridges","method":"patch"},{"path":"/shoppings/customers/sales/{saleId}/reviews/{inquiryId}/comments","method":"post"},{"path":"/shoppings/customers/sales/{saleId}/reviews/{inquiryId}/comments","method":"patch"},{"path":"/shoppings/customers/sales/{saleId}/reviews/{inquiryId}/comments/{id}","method":"get"},{"path":"/shoppings/customers/sales/{saleId}/reviews/{inquiryId}/comments/{id}","method":"put"},{"path":"/shoppings/customers/sales/{saleId}/reviews","method":"post"},{"path":"/shoppings/customers/sales/{saleId}/reviews","method":"patch"},{"path":"/shoppings/customers/sales/{saleId}/reviews/{id}","method":"get"},{"path":"/shoppings/customers/sales/{saleId}/reviews/{id}","method":"post"},{"path":"/shoppings/customers/sales/{saleId}/reviews/abridges","method":"patch"},{"path":"/shoppings/customers/sales/{saleId}/snapshots","method":"patch"},{"path":"/shoppings/customers/sales/{saleId}/snapshots/{id}","method":"get"},{"path":"/shoppings/customers/sales/{saleId}/snapshots/{id}/flip","method":"get"},{"path":"/shoppings/customers/systematic/channels/{channelCode}/categories","method":"patch"},{"path":"/shoppings/customers/systematic/channels/{channelCode}/categories/{id}","method":"get"},{"path":"/shoppings/customers/systematic/channels/{channelCode}/categories/{id}/invert","method":"get"},{"path":"/shoppings/customers/systematic/channels","method":"patch"},{"path":"/shoppings/customers/systematic/channels/hierarchical","method":"patch"},{"path":"/shoppings/customers/systematic/channels/{id}","method":"get"},{"path":"/shoppings/customers/systematic/channels/{code}/get","method":"get"},{"path":"/shoppings/customers/systematic/sections","method":"patch"},{"path":"/shoppings/customers/systematic/sections/{id}","method":"get"},{"path":"/shoppings/customers/systematic/sections/{code}/get","method":"get"},{"path":"/shoppings/sellers/authenticate","method":"get"},{"path":"/shoppings/sellers/authenticate","method":"post"},{"path":"/shoppings/sellers/authenticate/login","method":"put"},{"path":"/shoppings/sellers/deliveries","method":"post"},{"path":"/shoppings/sellers/deliveries","method":"patch"},{"path":"/shoppings/sellers/deliveries/{id}","method":"get"},{"path":"/shoppings/sellers/deliveries/incompletes","method":"patch"},{"path":"/shoppings/sellers/deliveries/{deliveryId}/journeys","method":"post"},{"path":"/shoppings/sellers/deliveries/{deliveryId}/journeys/{id}/complete","method":"put"},{"path":"/shoppings/sellers/deliveries/{deliveryId}/journeys/{id}","method":"delete"},{"path":"/shoppings/sellers/deliveries/{deliveryId}/shippers","method":"post"},{"path":"/shoppings/sellers/coupons","method":"post"},{"path":"/shoppings/sellers/coupons","method":"patch"},{"path":"/shoppings/sellers/coupons/{id}","method":"get"},{"path":"/shoppings/sellers/coupons/{id}","method":"delete"},{"path":"/shoppings/sellers/orders","method":"patch"},{"path":"/shoppings/sellers/orders/{id}","method":"get"},{"path":"/shoppings/sellers/sales","method":"post"},{"path":"/shoppings/sellers/sales","method":"patch"},{"path":"/shoppings/sellers/sales/{id}","method":"get"},{"path":"/shoppings/sellers/sales/{id}","method":"put"},{"path":"/shoppings/sellers/sales/{id}/open","method":"put"},{"path":"/shoppings/sellers/sales/{id}/replica","method":"post"},{"path":"/shoppings/sellers/sales/{id}/pause","method":"delete"},{"path":"/shoppings/sellers/sales/{id}/suspend","method":"delete"},{"path":"/shoppings/sellers/sales/{id}/restore","method":"put"},{"path":"/shoppings/sellers/sales/details","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/questions/{questionId}/answer","method":"post"},{"path":"/shoppings/sellers/sales/{saleId}/questions/{questionId}/answer","method":"put"},{"path":"/shoppings/sellers/sales/{saleId}/questions/{inquiryId}/comments","method":"post"},{"path":"/shoppings/sellers/sales/{saleId}/questions/{inquiryId}/comments","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/questions/{inquiryId}/comments/{id}","method":"get"},{"path":"/shoppings/sellers/sales/{saleId}/questions/{inquiryId}/comments/{id}","method":"put"},{"path":"/shoppings/sellers/sales/{saleId}/questions","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/questions/abridges","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/questions/{id}","method":"get"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/{reviewId}/answer","method":"post"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/{reviewId}/answer","method":"put"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/{inquiryId}/comments","method":"post"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/{inquiryId}/comments","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/{inquiryId}/comments/{id}","method":"get"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/{inquiryId}/comments/{id}","method":"put"},{"path":"/shoppings/sellers/sales/{saleId}/reviews","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/abridges","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/reviews/{id}","method":"get"},{"path":"/shoppings/sellers/sales/{saleId}/snapshots/{id}/replica","method":"post"},{"path":"/shoppings/sellers/sales/{saleId}/snapshots","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/snapshots/{id}","method":"get"},{"path":"/shoppings/sellers/sales/{saleId}/snapshots/{id}/flip","method":"get"},{"path":"/shoppings/sellers/sales/{saleId}/units/{unitId}/stocks/{stockId}/supplements","method":"post"},{"path":"/shoppings/sellers/sales/{saleId}/units/{unitId}/stocks/{stockId}/supplements","method":"patch"},{"path":"/shoppings/sellers/sales/{saleId}/units/{unitId}/stocks/{stockId}/supplements/{id}","method":"put"},{"path":"/shoppings/sellers/sales/{saleId}/units/{unitId}/stocks/{stockId}/supplements/{id}","method":"delete"},{"path":"/shoppings/sellers/systematic/channels/{channelCode}/categories","method":"patch"},{"path":"/shoppings/sellers/systematic/channels/{channelCode}/categories/{id}","method":"get"},{"path":"/shoppings/sellers/systematic/channels/{channelCode}/categories/{id}/invert","method":"get"},{"path":"/shoppings/sellers/systematic/channels","method":"patch"},{"path":"/shoppings/sellers/systematic/channels/hierarchical","method":"patch"},{"path":"/shoppings/sellers/systematic/channels/{id}","method":"get"},{"path":"/shoppings/sellers/systematic/channels/{code}/get","method":"get"},{"path":"/shoppings/sellers/systematic/sections","method":"patch"},{"path":"/shoppings/sellers/systematic/sections/{id}","method":"get"},{"path":"/shoppings/sellers/systematic/sections/{code}/get","method":"get"}]}\n```\n\n**Key points**: \n- `/shopping` is used as domain prefix\n- Hierarchical relationships are reflected in paths (e.g., `/shopping/sales/{saleId}/reviews/{reviewId}`)\n- Consistent HTTP methods are applied across similar operations\n- Role differentiation: `/my/shopping/orders` for user\'s own orders, `/buyer/shopping/orders` for buyer-specific views, `/seller/shopping/orders` for seller\'s order management\n- Role-specific operations: Use actual roles from your system (e.g., `/administrator/shopping/products`, `/seller/shopping/products`)'),
2509
2520
  controllers: [ createApplication$8({
2510
2521
  model: ctx.model,
2511
2522
  roles: ctx.state().analyze?.roles.map((it => it.name)) ?? null,
@@ -2516,7 +2527,7 @@ async function process$4(ctx, endpoints) {
2516
2527
  }) ]
2517
2528
  });
2518
2529
  enforceToolCall(agentica);
2519
- await agentica.conversate([ "Make API operations for below endpoints:", "", "```json", JSON.stringify(Array.from(endpoints), null, 2), "```" ].join("\n")).finally((() => {
2530
+ await agentica.conversate([ "Make API operations for below endpoints:", "", "**CRITICAL INSTRUCTIONS**:", "1. Base ALL operation descriptions on ACTUAL fields in the Prisma schema", "2. NEVER reference fields that don't exist (e.g., deleted_at, created_by, updated_by)", "3. For DELETE operations:", " - Check if the entity has soft delete fields in the schema", " - If YES: Describe soft delete behavior using those fields", " - If NO: Describe hard delete behavior (permanent removal)", "4. Every field mentioned in descriptions MUST exist in the Prisma schema", "", "```json", JSON.stringify(Array.from(endpoints), null, 2), "```" ].join("\n")).finally((() => {
2520
2531
  const tokenUsage = agentica.getTokenUsage();
2521
2532
  ctx.usage().record(tokenUsage, [ "interface" ]);
2522
2533
  }));
@@ -2530,7 +2541,7 @@ function createApplication$8(props) {
2530
2541
  application.functions[0].validate = next => {
2531
2542
  const result = (() => {
2532
2543
  const _io0 = input => Array.isArray(input.operations) && input.operations.every((elem => "object" === typeof elem && null !== elem && _io1(elem)));
2533
- const _io1 = input => "string" === typeof input.specification && "string" === typeof input.description && "string" === typeof input.summary && (Array.isArray(input.parameters) && input.parameters.every((elem => "object" === typeof elem && null !== elem && _io2(elem)))) && (null === input.requestBody || "object" === typeof input.requestBody && null !== input.requestBody && _io6(input.requestBody)) && (null === input.responseBody || "object" === typeof input.responseBody && null !== input.responseBody && _io7(input.responseBody)) && (null === input.authorizationRoles || Array.isArray(input.authorizationRoles) && (__typia_transform__isUniqueItems._isUniqueItems(input.authorizationRoles) && input.authorizationRoles.every((elem => "string" === typeof elem)))) && "string" === typeof input.path && ("get" === input.method || "post" === input.method || "put" === input.method || "delete" === input.method || "patch" === input.method);
2544
+ const _io1 = input => "string" === typeof input.specification && "string" === typeof input.description && "string" === typeof input.summary && (Array.isArray(input.parameters) && input.parameters.every((elem => "object" === typeof elem && null !== elem && _io2(elem)))) && (null === input.requestBody || "object" === typeof input.requestBody && null !== input.requestBody && _io6(input.requestBody)) && (null === input.responseBody || "object" === typeof input.responseBody && null !== input.responseBody && _io7(input.responseBody)) && (null === input.authorizationRole || "string" === typeof input.authorizationRole && 1 <= input.authorizationRole.length) && "string" === typeof input.name && "string" === typeof input.path && ("get" === input.method || "post" === input.method || "put" === input.method || "delete" === input.method || "patch" === input.method);
2534
2545
  const _io2 = input => "string" === typeof input.name && "string" === typeof input.description && ("object" === typeof input.schema && null !== input.schema && _iu0(input.schema));
2535
2546
  const _io3 = input => (undefined === input.minimum || "number" === typeof input.minimum && (Math.floor(input.minimum) === input.minimum && -0x8000000000000000 <= input.minimum && input.minimum <= 0x8000000000000000)) && (undefined === input.maximum || "number" === typeof input.maximum && (Math.floor(input.maximum) === input.maximum && -0x8000000000000000 <= input.maximum && input.maximum <= 0x8000000000000000)) && (undefined === input.exclusiveMinimum || "number" === typeof input.exclusiveMinimum) && (undefined === input.exclusiveMaximum || "number" === typeof input.exclusiveMaximum) && (undefined === input.multipleOf || "number" === typeof input.multipleOf && (Math.floor(input.multipleOf) === input.multipleOf && 0 <= input.multipleOf && input.multipleOf <= 0x10000000000000000 && 0 < input.multipleOf)) && "integer" === input.type;
2536
2547
  const _io4 = input => (undefined === input.minimum || "number" === typeof input.minimum) && (undefined === input.maximum || "number" === typeof input.maximum) && (undefined === input.exclusiveMinimum || "number" === typeof input.exclusiveMinimum) && (undefined === input.exclusiveMaximum || "number" === typeof input.exclusiveMaximum) && (undefined === input.multipleOf || "number" === typeof input.multipleOf && 0 < input.multipleOf) && "number" === input.type;
@@ -2544,12 +2555,12 @@ function createApplication$8(props) {
2544
2555
  path: _path + ".operations",
2545
2556
  expected: "Array<AutoBeOpenApi.IOperation>",
2546
2557
  value: input.operations
2547
- })) && input.operations.map(((elem, _index4) => ("object" === typeof elem && null !== elem || _report(_exceptionable, {
2548
- path: _path + ".operations[" + _index4 + "]",
2558
+ })) && input.operations.map(((elem, _index3) => ("object" === typeof elem && null !== elem || _report(_exceptionable, {
2559
+ path: _path + ".operations[" + _index3 + "]",
2549
2560
  expected: "AutoBeOpenApi.IOperation",
2550
2561
  value: elem
2551
- })) && _vo1(elem, _path + ".operations[" + _index4 + "]", _exceptionable) || _report(_exceptionable, {
2552
- path: _path + ".operations[" + _index4 + "]",
2562
+ })) && _vo1(elem, _path + ".operations[" + _index3 + "]", _exceptionable) || _report(_exceptionable, {
2563
+ path: _path + ".operations[" + _index3 + "]",
2553
2564
  expected: "AutoBeOpenApi.IOperation",
2554
2565
  value: elem
2555
2566
  }))).every((flag => flag)) || _report(_exceptionable, {
@@ -2573,12 +2584,12 @@ function createApplication$8(props) {
2573
2584
  path: _path + ".parameters",
2574
2585
  expected: "Array<AutoBeOpenApi.IParameter>",
2575
2586
  value: input.parameters
2576
- })) && input.parameters.map(((elem, _index5) => ("object" === typeof elem && null !== elem || _report(_exceptionable, {
2577
- path: _path + ".parameters[" + _index5 + "]",
2587
+ })) && input.parameters.map(((elem, _index4) => ("object" === typeof elem && null !== elem || _report(_exceptionable, {
2588
+ path: _path + ".parameters[" + _index4 + "]",
2578
2589
  expected: "AutoBeOpenApi.IParameter",
2579
2590
  value: elem
2580
- })) && _vo2(elem, _path + ".parameters[" + _index5 + "]", _exceptionable) || _report(_exceptionable, {
2581
- path: _path + ".parameters[" + _index5 + "]",
2591
+ })) && _vo2(elem, _path + ".parameters[" + _index4 + "]", _exceptionable) || _report(_exceptionable, {
2592
+ path: _path + ".parameters[" + _index4 + "]",
2582
2593
  expected: "AutoBeOpenApi.IParameter",
2583
2594
  value: elem
2584
2595
  }))).every((flag => flag)) || _report(_exceptionable, {
@@ -2601,22 +2612,18 @@ function createApplication$8(props) {
2601
2612
  path: _path + ".responseBody",
2602
2613
  expected: "(AutoBeOpenApi.IResponseBody | null)",
2603
2614
  value: input.responseBody
2604
- }), null === input.authorizationRoles || (Array.isArray(input.authorizationRoles) || _report(_exceptionable, {
2605
- path: _path + ".authorizationRoles",
2606
- expected: "((Array<string> & UniqueItems<true>) | null)",
2607
- value: input.authorizationRoles
2608
- })) && ((__typia_transform__isUniqueItems._isUniqueItems(input.authorizationRoles) || _report(_exceptionable, {
2609
- path: _path + ".authorizationRoles",
2610
- expected: "Array<> & UniqueItems<true>",
2611
- value: input.authorizationRoles
2612
- })) && input.authorizationRoles.map(((elem, _index6) => "string" === typeof elem || _report(_exceptionable, {
2613
- path: _path + ".authorizationRoles[" + _index6 + "]",
2615
+ }), null === input.authorizationRole || "string" === typeof input.authorizationRole && (1 <= input.authorizationRole.length || _report(_exceptionable, {
2616
+ path: _path + ".authorizationRole",
2617
+ expected: "string & MinLength<1>",
2618
+ value: input.authorizationRole
2619
+ })) || _report(_exceptionable, {
2620
+ path: _path + ".authorizationRole",
2621
+ expected: "((string & MinLength<1>) | null)",
2622
+ value: input.authorizationRole
2623
+ }), "string" === typeof input.name || _report(_exceptionable, {
2624
+ path: _path + ".name",
2614
2625
  expected: "string",
2615
- value: elem
2616
- }))).every((flag => flag))) || _report(_exceptionable, {
2617
- path: _path + ".authorizationRoles",
2618
- expected: "((Array<string> & UniqueItems<true>) | null)",
2619
- value: input.authorizationRoles
2626
+ value: input.name
2620
2627
  }), "string" === typeof input.path || _report(_exceptionable, {
2621
2628
  path: _path + ".path",
2622
2629
  expected: "string",
@@ -2811,17 +2818,14 @@ function createApplication$8(props) {
2811
2818
  expected: "GET method should not have request body. Change method, or re-design the operation.",
2812
2819
  value: op.requestBody
2813
2820
  });
2814
- op.authorizationRoles?.forEach(((role, j) => {
2815
- if (props.roles === null) {
2816
- op.authorizationRoles = null;
2817
- }
2818
- if (props.roles?.find((it => it === role)) === undefined) errors.push({
2819
- path: `operations[${i}].authorizationRoles[${j}]`,
2820
- expected: `undefined | ${props.roles?.join(" | ")}`,
2821
- description: [ `Role "${role}" is not defined in the roles list.`, "", "Please select one of them below, or do not define (undefined): ", "", ...(props.roles ?? []).map((role => `- ${role}`)) ].join("\n"),
2822
- value: role
2823
- });
2824
- }));
2821
+ if (props.roles === null) {
2822
+ op.authorizationRole = null;
2823
+ } else if (props.roles?.find((it => it === op.authorizationRole)) === undefined) errors.push({
2824
+ path: `operations[${i}].authorizationRole`,
2825
+ expected: `undefined | ${props.roles?.join(" | ")}`,
2826
+ description: [ `Role "${op.authorizationRole}" is not defined in the roles list.`, "", "Please select one of them below, or do not define (undefined): ", "", ...(props.roles ?? []).map((role => `- ${role}`)) ].join("\n"),
2827
+ value: op.authorizationRole
2828
+ });
2825
2829
  }));
2826
2830
  if (errors.length !== 0) return {
2827
2831
  success: false,
@@ -2904,18 +2908,19 @@ const claude$9 = {
2904
2908
  $ref: "#/$defs/AutoBeOpenApi.IResponseBody"
2905
2909
  } ]
2906
2910
  },
2907
- authorizationRoles: {
2908
- description: "List of roles that are allowed to access the API operation.\n\nIf the API operation is not restricted to any role, this field must be\n`null`.\n\nIf the API operation is restricted to some roles, this field must be an\narray of role names.",
2911
+ authorizationRole: {
2912
+ description: 'Authorization role required to access this API operation.\n\nThis field specifies which user role is allowed to access this endpoint.\nThe role name must correspond exactly to the actual roles defined in your\nsystem\'s Prisma schema (e.g., "admin", "administrator", "moderator",\n"seller", "buyer", etc.).\n\n## Role-Based Path Convention\n\nWhen authorizationRole is specified, it should align with the path\nstructure:\n\n- If authorizationRole is "admin" path might be "/admin/resources/{id}"\n- If authorizationRole is "seller" → path might be "/seller/products"\n- Special case: For user\'s own resources, use path prefix "/my/" regardless\n of role\n\n## Important Guidelines\n\n- Set to `null` for public endpoints that require no authentication\n- Set to specific role string for role-restricted endpoints\n- The role name MUST match exactly with the user type/role defined in the\n database\n- This role will be used by the Realize Agent to generate appropriate\n decorator and authorization logic in the provider functions\n- The controller will apply the corresponding authentication decorator\n based on this role\n\n## Examples\n\n- `null` - Public endpoint, no authentication required\n- `"user"` - Any authenticated user can access\n- `"admin"` - Only admin users can access\n- `"seller"` - Only seller users can access\n- `"moderator"` - Only moderator users can access\n\nNote: The actual authentication/authorization implementation will be\nhandled by decorators at the controller level, and the provider function\nwill receive the authenticated user object with the appropriate type.',
2909
2913
  oneOf: [ {
2910
2914
  type: "null"
2911
2915
  }, {
2912
- type: "array",
2913
- items: {
2914
- type: "string"
2915
- },
2916
- uniqueItems: true
2916
+ type: "string",
2917
+ minLength: 1
2917
2918
  } ]
2918
2919
  },
2920
+ name: {
2921
+ description: 'Functional name of the API endpoint.\n\nThis is a semantic identifier that represents the primary function or\npurpose of the API endpoint. It serves as a canonical name that can be\nused for code generation, SDK method names, and internal references.\n\n## Standard Endpoint Names\n\nUse these conventional names based on the endpoint\'s primary function:\n\n- **`index`**: List/search operations that return multiple entities\n\n - Typically used with PATCH method for complex queries\n - Example: `PATCH /users` → `name: "index"`\n- **`at`**: Retrieve a specific entity by identifier\n\n - Typically used with GET method on single resource\n - Example: `GET /users/{userId}` → `name: "at"`\n- **`create`**: Create a new entity\n\n - Typically used with POST method\n - Example: `POST /users` → `name: "create"`\n- **`update`**: Update an existing entity\n\n - Typically used with PUT method\n - Example: `PUT /users/{userId}` → `name: "update"`\n- **`erase`**: Delete/remove an entity\n\n - Typically used with DELETE method\n - Example: `DELETE /users/{userId}` → `name: "erase"`\n\n## Custom Endpoint Names\n\nFor specialized operations beyond basic CRUD, use descriptive verbs:\n\n- **`activate`**: Enable or turn on a feature/entity\n- **`deactivate`**: Disable or turn off a feature/entity\n- **`approve`**: Approve a request or entity\n- **`reject`**: Reject a request or entity\n- **`publish`**: Make content publicly available\n- **`archive`**: Move to archived state\n- **`restore`**: Restore from archived/deleted state\n- **`duplicate`**: Create a copy of an entity\n- **`transfer`**: Move ownership or change assignment\n- **`validate`**: Validate data or state\n- **`process`**: Execute a business process or workflow\n- **`export`**: Generate downloadable data\n- **`import`**: Process uploaded data\n\n## Naming Guidelines\n\n- Use lowercase, singular verb forms\n- Be concise but descriptive\n- Avoid abbreviations unless widely understood\n- Ensure the name clearly represents the endpoint\'s primary action\n- For nested resources, focus on the action rather than hierarchy\n\nExamples:\n\n- `GET /shopping/orders/{orderId}/items` → `name: "index"` (lists items)\n- `POST /shopping/orders/{orderId}/cancel` → `name: "cancel"`\n- `PUT /users/{userId}/password` → `name: "updatePassword"`',
2922
+ type: "string"
2923
+ },
2919
2924
  path: {
2920
2925
  description: "HTTP path of the API operation.\n\nThe URL path for accessing this API operation, using path parameters\nenclosed in curly braces (e.g., `/shoppings/customers/sales/{saleId}`).\n\nIt must be corresponded to the {@link parameters path parameters}.\n\nThe path structure should clearly indicate which database entity this\noperation is manipulating, helping to ensure all entities have\nappropriate API coverage.",
2921
2926
  type: "string"
@@ -2935,7 +2940,7 @@ const claude$9 = {
2935
2940
  } ]
2936
2941
  }
2937
2942
  },
2938
- required: [ "specification", "description", "summary", "parameters", "requestBody", "responseBody", "authorizationRoles", "path", "method" ]
2943
+ required: [ "specification", "description", "summary", "parameters", "requestBody", "responseBody", "authorizationRole", "name", "path", "method" ]
2939
2944
  },
2940
2945
  "AutoBeOpenApi.IParameter": {
2941
2946
  description: 'Path parameter information for API routes.\n\nThis interface defines a path parameter that appears in the URL of an API\nendpoint. Path parameters are enclosed in curly braces in the\n{@link AutoBeOpenApi.IOperation.path operation path} and must be defined\nwith their types and descriptions.\n\nFor example, if API operation path is\n`/shoppings/customers/sales/{saleId}/questions/${questionId}/comments/${commentId}`,\nthe path parameters should be like below:\n\n```json\n{\n "path": "/shoppings/customers/sales/{saleId}/questions/${questionId}/comments/${commentId}",\n "method": "get",\n "parameters": [\n {\n "name": "saleId",\n "in": "path",\n "schema": { "type": "string", "format": "uuid" },\n "description": "Target sale\'s ID"\n },\n {\n "name": "questionId",\n "in": "path",\n "schema": { "type": "string", "format": "uuid" },\n "description": "Target question\'s ID"\n },\n {\n "name": "commentId",\n "in": "path",\n "schema": { "type": "string", "format": "uuid" },\n "description": "Target comment\'s ID"\n }\n ]\n}\n```',
@@ -3102,7 +3107,7 @@ const claude$9 = {
3102
3107
  description: "Generate detailed API operations from path/method combinations.\n\nThis function creates complete API operations following REST principles and\nquality standards. Each generated operation includes specification, path,\nmethod, detailed multi-paragraph description, concise summary, parameters,\nand appropriate request/response bodies.\n\nThe function processes as many operations as possible in a single call,\nwith progress tracking to ensure iterative completion of all required\nendpoints.",
3103
3108
  validate: (() => {
3104
3109
  const _io0 = input => Array.isArray(input.operations) && input.operations.every((elem => "object" === typeof elem && null !== elem && _io1(elem)));
3105
- const _io1 = input => "string" === typeof input.specification && "string" === typeof input.description && "string" === typeof input.summary && (Array.isArray(input.parameters) && input.parameters.every((elem => "object" === typeof elem && null !== elem && _io2(elem)))) && (null === input.requestBody || "object" === typeof input.requestBody && null !== input.requestBody && _io6(input.requestBody)) && (null === input.responseBody || "object" === typeof input.responseBody && null !== input.responseBody && _io7(input.responseBody)) && (null === input.authorizationRoles || Array.isArray(input.authorizationRoles) && (__typia_transform__isUniqueItems._isUniqueItems(input.authorizationRoles) && input.authorizationRoles.every((elem => "string" === typeof elem)))) && "string" === typeof input.path && ("get" === input.method || "post" === input.method || "put" === input.method || "delete" === input.method || "patch" === input.method);
3110
+ const _io1 = input => "string" === typeof input.specification && "string" === typeof input.description && "string" === typeof input.summary && (Array.isArray(input.parameters) && input.parameters.every((elem => "object" === typeof elem && null !== elem && _io2(elem)))) && (null === input.requestBody || "object" === typeof input.requestBody && null !== input.requestBody && _io6(input.requestBody)) && (null === input.responseBody || "object" === typeof input.responseBody && null !== input.responseBody && _io7(input.responseBody)) && (null === input.authorizationRole || "string" === typeof input.authorizationRole && 1 <= input.authorizationRole.length) && "string" === typeof input.name && "string" === typeof input.path && ("get" === input.method || "post" === input.method || "put" === input.method || "delete" === input.method || "patch" === input.method);
3106
3111
  const _io2 = input => "string" === typeof input.name && "string" === typeof input.description && ("object" === typeof input.schema && null !== input.schema && _iu0(input.schema));
3107
3112
  const _io3 = input => (undefined === input.minimum || "number" === typeof input.minimum && (Math.floor(input.minimum) === input.minimum && -0x8000000000000000 <= input.minimum && input.minimum <= 0x8000000000000000)) && (undefined === input.maximum || "number" === typeof input.maximum && (Math.floor(input.maximum) === input.maximum && -0x8000000000000000 <= input.maximum && input.maximum <= 0x8000000000000000)) && (undefined === input.exclusiveMinimum || "number" === typeof input.exclusiveMinimum) && (undefined === input.exclusiveMaximum || "number" === typeof input.exclusiveMaximum) && (undefined === input.multipleOf || "number" === typeof input.multipleOf && (Math.floor(input.multipleOf) === input.multipleOf && 0 <= input.multipleOf && input.multipleOf <= 0x10000000000000000 && 0 < input.multipleOf)) && "integer" === input.type;
3108
3113
  const _io4 = input => (undefined === input.minimum || "number" === typeof input.minimum) && (undefined === input.maximum || "number" === typeof input.maximum) && (undefined === input.exclusiveMinimum || "number" === typeof input.exclusiveMinimum) && (undefined === input.exclusiveMaximum || "number" === typeof input.exclusiveMaximum) && (undefined === input.multipleOf || "number" === typeof input.multipleOf && 0 < input.multipleOf) && "number" === input.type;
@@ -3116,12 +3121,12 @@ const claude$9 = {
3116
3121
  path: _path + ".operations",
3117
3122
  expected: "Array<AutoBeOpenApi.IOperation>",
3118
3123
  value: input.operations
3119
- })) && input.operations.map(((elem, _index4) => ("object" === typeof elem && null !== elem || _report(_exceptionable, {
3120
- path: _path + ".operations[" + _index4 + "]",
3124
+ })) && input.operations.map(((elem, _index3) => ("object" === typeof elem && null !== elem || _report(_exceptionable, {
3125
+ path: _path + ".operations[" + _index3 + "]",
3121
3126
  expected: "AutoBeOpenApi.IOperation",
3122
3127
  value: elem
3123
- })) && _vo1(elem, _path + ".operations[" + _index4 + "]", _exceptionable) || _report(_exceptionable, {
3124
- path: _path + ".operations[" + _index4 + "]",
3128
+ })) && _vo1(elem, _path + ".operations[" + _index3 + "]", _exceptionable) || _report(_exceptionable, {
3129
+ path: _path + ".operations[" + _index3 + "]",
3125
3130
  expected: "AutoBeOpenApi.IOperation",
3126
3131
  value: elem
3127
3132
  }))).every((flag => flag)) || _report(_exceptionable, {
@@ -3145,12 +3150,12 @@ const claude$9 = {
3145
3150
  path: _path + ".parameters",
3146
3151
  expected: "Array<AutoBeOpenApi.IParameter>",
3147
3152
  value: input.parameters
3148
- })) && input.parameters.map(((elem, _index5) => ("object" === typeof elem && null !== elem || _report(_exceptionable, {
3149
- path: _path + ".parameters[" + _index5 + "]",
3153
+ })) && input.parameters.map(((elem, _index4) => ("object" === typeof elem && null !== elem || _report(_exceptionable, {
3154
+ path: _path + ".parameters[" + _index4 + "]",
3150
3155
  expected: "AutoBeOpenApi.IParameter",
3151
3156
  value: elem
3152
- })) && _vo2(elem, _path + ".parameters[" + _index5 + "]", _exceptionable) || _report(_exceptionable, {
3153
- path: _path + ".parameters[" + _index5 + "]",
3157
+ })) && _vo2(elem, _path + ".parameters[" + _index4 + "]", _exceptionable) || _report(_exceptionable, {
3158
+ path: _path + ".parameters[" + _index4 + "]",
3154
3159
  expected: "AutoBeOpenApi.IParameter",
3155
3160
  value: elem
3156
3161
  }))).every((flag => flag)) || _report(_exceptionable, {
@@ -3173,22 +3178,18 @@ const claude$9 = {
3173
3178
  path: _path + ".responseBody",
3174
3179
  expected: "(AutoBeOpenApi.IResponseBody | null)",
3175
3180
  value: input.responseBody
3176
- }), null === input.authorizationRoles || (Array.isArray(input.authorizationRoles) || _report(_exceptionable, {
3177
- path: _path + ".authorizationRoles",
3178
- expected: "((Array<string> & UniqueItems<true>) | null)",
3179
- value: input.authorizationRoles
3180
- })) && ((__typia_transform__isUniqueItems._isUniqueItems(input.authorizationRoles) || _report(_exceptionable, {
3181
- path: _path + ".authorizationRoles",
3182
- expected: "Array<> & UniqueItems<true>",
3183
- value: input.authorizationRoles
3184
- })) && input.authorizationRoles.map(((elem, _index6) => "string" === typeof elem || _report(_exceptionable, {
3185
- path: _path + ".authorizationRoles[" + _index6 + "]",
3181
+ }), null === input.authorizationRole || "string" === typeof input.authorizationRole && (1 <= input.authorizationRole.length || _report(_exceptionable, {
3182
+ path: _path + ".authorizationRole",
3183
+ expected: "string & MinLength<1>",
3184
+ value: input.authorizationRole
3185
+ })) || _report(_exceptionable, {
3186
+ path: _path + ".authorizationRole",
3187
+ expected: "((string & MinLength<1>) | null)",
3188
+ value: input.authorizationRole
3189
+ }), "string" === typeof input.name || _report(_exceptionable, {
3190
+ path: _path + ".name",
3186
3191
  expected: "string",
3187
- value: elem
3188
- }))).every((flag => flag))) || _report(_exceptionable, {
3189
- path: _path + ".authorizationRoles",
3190
- expected: "((Array<string> & UniqueItems<true>) | null)",
3191
- value: input.authorizationRoles
3192
+ value: input.name
3192
3193
  }), "string" === typeof input.path || _report(_exceptionable, {
3193
3194
  path: _path + ".path",
3194
3195
  expected: "string",
@@ -3442,18 +3443,19 @@ const collection$9 = {
3442
3443
  $ref: "#/$defs/AutoBeOpenApi.IResponseBody"
3443
3444
  } ]
3444
3445
  },
3445
- authorizationRoles: {
3446
- description: "List of roles that are allowed to access the API operation.\n\nIf the API operation is not restricted to any role, this field must be\n`null`.\n\nIf the API operation is restricted to some roles, this field must be an\narray of role names.",
3446
+ authorizationRole: {
3447
+ description: 'Authorization role required to access this API operation.\n\nThis field specifies which user role is allowed to access this endpoint.\nThe role name must correspond exactly to the actual roles defined in your\nsystem\'s Prisma schema (e.g., "admin", "administrator", "moderator",\n"seller", "buyer", etc.).\n\n## Role-Based Path Convention\n\nWhen authorizationRole is specified, it should align with the path\nstructure:\n\n- If authorizationRole is "admin" path might be "/admin/resources/{id}"\n- If authorizationRole is "seller" → path might be "/seller/products"\n- Special case: For user\'s own resources, use path prefix "/my/" regardless\n of role\n\n## Important Guidelines\n\n- Set to `null` for public endpoints that require no authentication\n- Set to specific role string for role-restricted endpoints\n- The role name MUST match exactly with the user type/role defined in the\n database\n- This role will be used by the Realize Agent to generate appropriate\n decorator and authorization logic in the provider functions\n- The controller will apply the corresponding authentication decorator\n based on this role\n\n## Examples\n\n- `null` - Public endpoint, no authentication required\n- `"user"` - Any authenticated user can access\n- `"admin"` - Only admin users can access\n- `"seller"` - Only seller users can access\n- `"moderator"` - Only moderator users can access\n\nNote: The actual authentication/authorization implementation will be\nhandled by decorators at the controller level, and the provider function\nwill receive the authenticated user object with the appropriate type.',
3447
3448
  anyOf: [ {
3448
3449
  type: "null"
3449
3450
  }, {
3450
- type: "array",
3451
- items: {
3452
- type: "string"
3453
- },
3454
- description: "@uniqueItems"
3451
+ type: "string",
3452
+ description: "@minLength 1"
3455
3453
  } ]
3456
3454
  },
3455
+ name: {
3456
+ description: 'Functional name of the API endpoint.\n\nThis is a semantic identifier that represents the primary function or\npurpose of the API endpoint. It serves as a canonical name that can be\nused for code generation, SDK method names, and internal references.\n\n## Standard Endpoint Names\n\nUse these conventional names based on the endpoint\'s primary function:\n\n- **`index`**: List/search operations that return multiple entities\n\n - Typically used with PATCH method for complex queries\n - Example: `PATCH /users` → `name: "index"`\n- **`at`**: Retrieve a specific entity by identifier\n\n - Typically used with GET method on single resource\n - Example: `GET /users/{userId}` → `name: "at"`\n- **`create`**: Create a new entity\n\n - Typically used with POST method\n - Example: `POST /users` → `name: "create"`\n- **`update`**: Update an existing entity\n\n - Typically used with PUT method\n - Example: `PUT /users/{userId}` → `name: "update"`\n- **`erase`**: Delete/remove an entity\n\n - Typically used with DELETE method\n - Example: `DELETE /users/{userId}` → `name: "erase"`\n\n## Custom Endpoint Names\n\nFor specialized operations beyond basic CRUD, use descriptive verbs:\n\n- **`activate`**: Enable or turn on a feature/entity\n- **`deactivate`**: Disable or turn off a feature/entity\n- **`approve`**: Approve a request or entity\n- **`reject`**: Reject a request or entity\n- **`publish`**: Make content publicly available\n- **`archive`**: Move to archived state\n- **`restore`**: Restore from archived/deleted state\n- **`duplicate`**: Create a copy of an entity\n- **`transfer`**: Move ownership or change assignment\n- **`validate`**: Validate data or state\n- **`process`**: Execute a business process or workflow\n- **`export`**: Generate downloadable data\n- **`import`**: Process uploaded data\n\n## Naming Guidelines\n\n- Use lowercase, singular verb forms\n- Be concise but descriptive\n- Avoid abbreviations unless widely understood\n- Ensure the name clearly represents the endpoint\'s primary action\n- For nested resources, focus on the action rather than hierarchy\n\nExamples:\n\n- `GET /shopping/orders/{orderId}/items` → `name: "index"` (lists items)\n- `POST /shopping/orders/{orderId}/cancel` → `name: "cancel"`\n- `PUT /users/{userId}/password` → `name: "updatePassword"`',
3457
+ type: "string"
3458
+ },
3457
3459
  path: {
3458
3460
  description: "HTTP path of the API operation.\n\nThe URL path for accessing this API operation, using path parameters\nenclosed in curly braces (e.g., `/shoppings/customers/sales/{saleId}`).\n\nIt must be corresponded to the {@link parameters path parameters}.\n\nThe path structure should clearly indicate which database entity this\noperation is manipulating, helping to ensure all entities have\nappropriate API coverage.",
3459
3461
  type: "string"
@@ -3464,7 +3466,7 @@ const collection$9 = {
3464
3466
  enum: [ "get", "post", "put", "delete", "patch" ]
3465
3467
  }
3466
3468
  },
3467
- required: [ "specification", "description", "summary", "parameters", "requestBody", "responseBody", "authorizationRoles", "path", "method" ]
3469
+ required: [ "specification", "description", "summary", "parameters", "requestBody", "responseBody", "authorizationRole", "name", "path", "method" ]
3468
3470
  },
3469
3471
  "AutoBeOpenApi.IParameter": {
3470
3472
  description: 'Path parameter information for API routes.\n\nThis interface defines a path parameter that appears in the URL of an API\nendpoint. Path parameters are enclosed in curly braces in the\n{@link AutoBeOpenApi.IOperation.path operation path} and must be defined\nwith their types and descriptions.\n\nFor example, if API operation path is\n`/shoppings/customers/sales/{saleId}/questions/${questionId}/comments/${commentId}`,\nthe path parameters should be like below:\n\n```json\n{\n "path": "/shoppings/customers/sales/{saleId}/questions/${questionId}/comments/${commentId}",\n "method": "get",\n "parameters": [\n {\n "name": "saleId",\n "in": "path",\n "schema": { "type": "string", "format": "uuid" },\n "description": "Target sale\'s ID"\n },\n {\n "name": "questionId",\n "in": "path",\n "schema": { "type": "string", "format": "uuid" },\n "description": "Target question\'s ID"\n },\n {\n "name": "commentId",\n "in": "path",\n "schema": { "type": "string", "format": "uuid" },\n "description": "Target comment\'s ID"\n }\n ]\n}\n```',
@@ -3630,7 +3632,7 @@ const collection$9 = {
3630
3632
  description: "Generate detailed API operations from path/method combinations.\n\nThis function creates complete API operations following REST principles and\nquality standards. Each generated operation includes specification, path,\nmethod, detailed multi-paragraph description, concise summary, parameters,\nand appropriate request/response bodies.\n\nThe function processes as many operations as possible in a single call,\nwith progress tracking to ensure iterative completion of all required\nendpoints.",
3631
3633
  validate: (() => {
3632
3634
  const _io0 = input => Array.isArray(input.operations) && input.operations.every((elem => "object" === typeof elem && null !== elem && _io1(elem)));
3633
- const _io1 = input => "string" === typeof input.specification && "string" === typeof input.description && "string" === typeof input.summary && (Array.isArray(input.parameters) && input.parameters.every((elem => "object" === typeof elem && null !== elem && _io2(elem)))) && (null === input.requestBody || "object" === typeof input.requestBody && null !== input.requestBody && _io6(input.requestBody)) && (null === input.responseBody || "object" === typeof input.responseBody && null !== input.responseBody && _io7(input.responseBody)) && (null === input.authorizationRoles || Array.isArray(input.authorizationRoles) && (__typia_transform__isUniqueItems._isUniqueItems(input.authorizationRoles) && input.authorizationRoles.every((elem => "string" === typeof elem)))) && "string" === typeof input.path && ("get" === input.method || "post" === input.method || "put" === input.method || "delete" === input.method || "patch" === input.method);
3635
+ const _io1 = input => "string" === typeof input.specification && "string" === typeof input.description && "string" === typeof input.summary && (Array.isArray(input.parameters) && input.parameters.every((elem => "object" === typeof elem && null !== elem && _io2(elem)))) && (null === input.requestBody || "object" === typeof input.requestBody && null !== input.requestBody && _io6(input.requestBody)) && (null === input.responseBody || "object" === typeof input.responseBody && null !== input.responseBody && _io7(input.responseBody)) && (null === input.authorizationRole || "string" === typeof input.authorizationRole && 1 <= input.authorizationRole.length) && "string" === typeof input.name && "string" === typeof input.path && ("get" === input.method || "post" === input.method || "put" === input.method || "delete" === input.method || "patch" === input.method);
3634
3636
  const _io2 = input => "string" === typeof input.name && "string" === typeof input.description && ("object" === typeof input.schema && null !== input.schema && _iu0(input.schema));
3635
3637
  const _io3 = input => (undefined === input.minimum || "number" === typeof input.minimum && (Math.floor(input.minimum) === input.minimum && -0x8000000000000000 <= input.minimum && input.minimum <= 0x8000000000000000)) && (undefined === input.maximum || "number" === typeof input.maximum && (Math.floor(input.maximum) === input.maximum && -0x8000000000000000 <= input.maximum && input.maximum <= 0x8000000000000000)) && (undefined === input.exclusiveMinimum || "number" === typeof input.exclusiveMinimum) && (undefined === input.exclusiveMaximum || "number" === typeof input.exclusiveMaximum) && (undefined === input.multipleOf || "number" === typeof input.multipleOf && (Math.floor(input.multipleOf) === input.multipleOf && 0 <= input.multipleOf && input.multipleOf <= 0x10000000000000000 && 0 < input.multipleOf)) && "integer" === input.type;
3636
3638
  const _io4 = input => (undefined === input.minimum || "number" === typeof input.minimum) && (undefined === input.maximum || "number" === typeof input.maximum) && (undefined === input.exclusiveMinimum || "number" === typeof input.exclusiveMinimum) && (undefined === input.exclusiveMaximum || "number" === typeof input.exclusiveMaximum) && (undefined === input.multipleOf || "number" === typeof input.multipleOf && 0 < input.multipleOf) && "number" === input.type;
@@ -3644,12 +3646,12 @@ const collection$9 = {
3644
3646
  path: _path + ".operations",
3645
3647
  expected: "Array<AutoBeOpenApi.IOperation>",
3646
3648
  value: input.operations
3647
- })) && input.operations.map(((elem, _index4) => ("object" === typeof elem && null !== elem || _report(_exceptionable, {
3648
- path: _path + ".operations[" + _index4 + "]",
3649
+ })) && input.operations.map(((elem, _index3) => ("object" === typeof elem && null !== elem || _report(_exceptionable, {
3650
+ path: _path + ".operations[" + _index3 + "]",
3649
3651
  expected: "AutoBeOpenApi.IOperation",
3650
3652
  value: elem
3651
- })) && _vo1(elem, _path + ".operations[" + _index4 + "]", _exceptionable) || _report(_exceptionable, {
3652
- path: _path + ".operations[" + _index4 + "]",
3653
+ })) && _vo1(elem, _path + ".operations[" + _index3 + "]", _exceptionable) || _report(_exceptionable, {
3654
+ path: _path + ".operations[" + _index3 + "]",
3653
3655
  expected: "AutoBeOpenApi.IOperation",
3654
3656
  value: elem
3655
3657
  }))).every((flag => flag)) || _report(_exceptionable, {
@@ -3673,12 +3675,12 @@ const collection$9 = {
3673
3675
  path: _path + ".parameters",
3674
3676
  expected: "Array<AutoBeOpenApi.IParameter>",
3675
3677
  value: input.parameters
3676
- })) && input.parameters.map(((elem, _index5) => ("object" === typeof elem && null !== elem || _report(_exceptionable, {
3677
- path: _path + ".parameters[" + _index5 + "]",
3678
+ })) && input.parameters.map(((elem, _index4) => ("object" === typeof elem && null !== elem || _report(_exceptionable, {
3679
+ path: _path + ".parameters[" + _index4 + "]",
3678
3680
  expected: "AutoBeOpenApi.IParameter",
3679
3681
  value: elem
3680
- })) && _vo2(elem, _path + ".parameters[" + _index5 + "]", _exceptionable) || _report(_exceptionable, {
3681
- path: _path + ".parameters[" + _index5 + "]",
3682
+ })) && _vo2(elem, _path + ".parameters[" + _index4 + "]", _exceptionable) || _report(_exceptionable, {
3683
+ path: _path + ".parameters[" + _index4 + "]",
3682
3684
  expected: "AutoBeOpenApi.IParameter",
3683
3685
  value: elem
3684
3686
  }))).every((flag => flag)) || _report(_exceptionable, {
@@ -3701,22 +3703,18 @@ const collection$9 = {
3701
3703
  path: _path + ".responseBody",
3702
3704
  expected: "(AutoBeOpenApi.IResponseBody | null)",
3703
3705
  value: input.responseBody
3704
- }), null === input.authorizationRoles || (Array.isArray(input.authorizationRoles) || _report(_exceptionable, {
3705
- path: _path + ".authorizationRoles",
3706
- expected: "((Array<string> & UniqueItems<true>) | null)",
3707
- value: input.authorizationRoles
3708
- })) && ((__typia_transform__isUniqueItems._isUniqueItems(input.authorizationRoles) || _report(_exceptionable, {
3709
- path: _path + ".authorizationRoles",
3710
- expected: "Array<> & UniqueItems<true>",
3711
- value: input.authorizationRoles
3712
- })) && input.authorizationRoles.map(((elem, _index6) => "string" === typeof elem || _report(_exceptionable, {
3713
- path: _path + ".authorizationRoles[" + _index6 + "]",
3706
+ }), null === input.authorizationRole || "string" === typeof input.authorizationRole && (1 <= input.authorizationRole.length || _report(_exceptionable, {
3707
+ path: _path + ".authorizationRole",
3708
+ expected: "string & MinLength<1>",
3709
+ value: input.authorizationRole
3710
+ })) || _report(_exceptionable, {
3711
+ path: _path + ".authorizationRole",
3712
+ expected: "((string & MinLength<1>) | null)",
3713
+ value: input.authorizationRole
3714
+ }), "string" === typeof input.name || _report(_exceptionable, {
3715
+ path: _path + ".name",
3714
3716
  expected: "string",
3715
- value: elem
3716
- }))).every((flag => flag))) || _report(_exceptionable, {
3717
- path: _path + ".authorizationRoles",
3718
- expected: "((Array<string> & UniqueItems<true>) | null)",
3719
- value: input.authorizationRoles
3717
+ value: input.name
3720
3718
  }), "string" === typeof input.path || _report(_exceptionable, {
3721
3719
  path: _path + ".path",
3722
3720
  expected: "string",
@@ -6824,7 +6822,7 @@ const transformRealizeDecoratorHistories = (ctx, role) => [ {
6824
6822
  text: [ "## Role", "", role, "", "## Prisma Schema", "", JSON.stringify(ctx.state().prisma?.schemas, null, 2), "" ].join("\n")
6825
6823
  } ];
6826
6824
 
6827
- const transformRealizeDecoratorCorrectHistories = (ctx, result, templateFiles, diagnostics) => [ {
6825
+ const transformRealizeDecoratorCorrectHistories = (ctx, auth, templateFiles, diagnostics) => [ {
6828
6826
  id: v4(),
6829
6827
  created_at: (new Date).toISOString(),
6830
6828
  type: "systemMessage",
@@ -6833,37 +6831,60 @@ const transformRealizeDecoratorCorrectHistories = (ctx, result, templateFiles, d
6833
6831
  id: v4(),
6834
6832
  created_at: (new Date).toISOString(),
6835
6833
  type: "assistantMessage",
6836
- text: [ "## Generated TypeScript Code", "", "```json", `${JSON.stringify(result, null, 2)}`, "```", "", "## Prisma Schema", "", "```json", `${JSON.stringify(ctx.state().prisma?.schemas, null, 2)}`, "```", "", "## File Paths", "", Object.keys(templateFiles).map((path => `- ${path}`)).join("\n"), "", "## Compile Errors", "", "Fix the compilation error in the provided code.", "", "```json", JSON.stringify(diagnostics, null, 2), "```" ].join("\n")
6834
+ text: [ "## Generated TypeScript Code", "", "```json", `${JSON.stringify({
6835
+ provider: {
6836
+ name: auth.provider.name,
6837
+ code: auth.provider.content
6838
+ },
6839
+ decorator: {
6840
+ name: auth.decorator.name,
6841
+ code: auth.decorator.content
6842
+ },
6843
+ payload: {
6844
+ name: auth.payload.name,
6845
+ code: auth.payload.content
6846
+ }
6847
+ }, null, 2)}`, "```", "", "## Prisma Schema", "", "```json", `${JSON.stringify(ctx.state().prisma?.schemas, null, 2)}`, "```", "", "## File Paths", "", Object.keys(templateFiles).map((path => `- ${path}`)).join("\n"), "", "## Compile Errors", "", "Fix the compilation error in the provided code.", "", "```json", JSON.stringify(diagnostics, null, 2), "```" ].join("\n")
6837
6848
  } ];
6838
6849
 
6839
- async function orchestrateRealizeDecorator(ctx) {
6850
+ var AuthorizationFileSystem;
6851
+
6852
+ (function(AuthorizationFileSystem) {
6853
+ AuthorizationFileSystem.decoratorPath = name => `src/decorators/${name}.ts`;
6854
+ AuthorizationFileSystem.payloadPath = name => `src/decorators/payload/${name}.ts`;
6855
+ AuthorizationFileSystem.providerPath = name => `src/providers/authorize/${name}.ts`;
6856
+ })(AuthorizationFileSystem || (AuthorizationFileSystem = {}));
6857
+
6858
+ async function orchestrateRealizeAuthorization(ctx) {
6840
6859
  const roles = ctx.state().interface?.document.components.authorization?.map((auth => auth.name)) ?? [];
6841
- const decorators = [];
6842
6860
  let completed = 0;
6843
6861
  const templateFiles = {
6844
6862
  "src/MyGlobal.ts": await fs.readFile(path.join(__dirname, "../../../../../internals/template/realize/src/MyGlobal.ts"), "utf-8"),
6845
6863
  "src/authentications/jwtAuthorize.ts": await fs.readFile(path.join(__dirname, "../../../../../internals/template/realize/src/providers/jwtAuthorize.ts"), "utf-8")
6846
6864
  };
6847
- const files = {
6848
- ...templateFiles
6849
- };
6850
- await Promise.all(roles.map((async role => {
6851
- const decorator = await process$2(ctx, role, templateFiles);
6852
- files[`src/decorators/${decorator.decorator.name}.ts`] = decorator.decorator.code;
6853
- files[`src/authentications/${decorator.provider.name}.ts`] = decorator.provider.code;
6854
- files[`src/authentications/types/${decorator.decoratorType.name}.ts`] = decorator.decoratorType.code;
6855
- decorators.push(decorator);
6856
- const events = {
6857
- type: "realizeDecorator",
6865
+ ctx.dispatch({
6866
+ type: "realizeAuthorizationStart",
6867
+ step: ctx.state().test?.step ?? 0,
6868
+ created_at: (new Date).toISOString()
6869
+ });
6870
+ const authorizations = await Promise.all(roles.map((async role => {
6871
+ const authorization = await process$2(ctx, role, templateFiles);
6872
+ ctx.dispatch({
6873
+ type: "realizeAuthorizationWrite",
6858
6874
  created_at: (new Date).toISOString(),
6859
- files,
6875
+ authorization,
6860
6876
  completed: ++completed,
6861
6877
  total: roles.length,
6862
6878
  step: ctx.state().test?.step ?? 0
6863
- };
6864
- ctx.dispatch(events);
6879
+ });
6880
+ return authorization;
6865
6881
  })));
6866
- return decorators;
6882
+ ctx.dispatch({
6883
+ type: "realizeAuthorizationComplete",
6884
+ created_at: (new Date).toISOString(),
6885
+ step: ctx.state().test?.step ?? 0
6886
+ });
6887
+ return authorizations;
6867
6888
  }
6868
6889
 
6869
6890
  async function process$2(ctx, role, templateFiles) {
@@ -6893,34 +6914,52 @@ async function process$2(ctx, role, templateFiles) {
6893
6914
  ctx.usage().record(tokenUsage, [ "realize" ]);
6894
6915
  }));
6895
6916
  if (pointer.value === null) throw new Error("Failed to create decorator.");
6917
+ const authorization = {
6918
+ role,
6919
+ decorator: {
6920
+ location: AuthorizationFileSystem.decoratorPath(pointer.value.decorator.name),
6921
+ name: pointer.value.decorator.name,
6922
+ content: pointer.value.decorator.code
6923
+ },
6924
+ payload: {
6925
+ location: AuthorizationFileSystem.payloadPath(pointer.value.payload.name),
6926
+ name: pointer.value.payload.name,
6927
+ content: pointer.value.payload.code
6928
+ },
6929
+ provider: {
6930
+ location: AuthorizationFileSystem.providerPath(pointer.value.provider.name),
6931
+ name: pointer.value.provider.name,
6932
+ content: pointer.value.provider.code
6933
+ }
6934
+ };
6896
6935
  const compiled = ctx.state().prisma?.compiled;
6897
6936
  const prismaClients = compiled?.type === "success" ? compiled.nodeModules : {};
6898
- return await correctDecorator(ctx, pointer.value, prismaClients, templateFiles);
6937
+ return correctDecorator(ctx, authorization, prismaClients, templateFiles);
6899
6938
  }
6900
6939
 
6901
- async function correctDecorator(ctx, result, prismaClients, templateFiles, life = 4) {
6940
+ async function correctDecorator(ctx, auth, prismaClients, templateFiles, life = 4) {
6902
6941
  const files = {
6903
6942
  ...templateFiles,
6904
6943
  ...prismaClients,
6905
- [`src/decorators/${result.decorator.name}.ts`]: result.decorator.code,
6906
- [`src/authentications/${result.provider.name}.ts`]: result.provider.code,
6907
- [`src/authentications/types/${result.decoratorType.name}.ts`]: result.decoratorType.code
6944
+ [auth.decorator.location]: auth.decorator.content,
6945
+ [auth.payload.location]: auth.payload.content,
6946
+ [auth.provider.location]: auth.provider.content
6908
6947
  };
6909
6948
  const compiler = await ctx.compiler();
6910
- const compiled = await compiler.typescript.compile({
6949
+ const result = await compiler.typescript.compile({
6911
6950
  files
6912
6951
  });
6913
6952
  ctx.dispatch({
6914
- type: "realizeDecoratorValidate",
6953
+ type: "realizeAuthorizationValidate",
6915
6954
  created_at: (new Date).toISOString(),
6916
- result: compiled,
6917
- files,
6955
+ result,
6956
+ authorization: auth,
6918
6957
  step: ctx.state().test?.step ?? 0
6919
6958
  });
6920
- if (compiled.type === "success") {
6921
- return result;
6922
- } else if (compiled.type === "exception" || life === 0) {
6923
- return result;
6959
+ if (result.type === "success") {
6960
+ return auth;
6961
+ } else if (result.type === "exception" || life === 0) {
6962
+ return auth;
6924
6963
  }
6925
6964
  const pointer = {
6926
6965
  value: null
@@ -6934,7 +6973,7 @@ async function correctDecorator(ctx, result, prismaClients, templateFiles, life
6934
6973
  describe: null
6935
6974
  }
6936
6975
  },
6937
- histories: transformRealizeDecoratorCorrectHistories(ctx, result, templateFiles, compiled.diagnostics),
6976
+ histories: transformRealizeDecoratorCorrectHistories(ctx, auth, templateFiles, result.diagnostics),
6938
6977
  controllers: [ createApplication$4({
6939
6978
  model: ctx.model,
6940
6979
  build: next => {
@@ -6948,20 +6987,32 @@ async function correctDecorator(ctx, result, prismaClients, templateFiles, life
6948
6987
  ctx.usage().record(tokenUsage, [ "realize" ]);
6949
6988
  }));
6950
6989
  if (pointer.value === null) throw new Error("Failed to correct decorator.");
6951
- const correctedFiles = {
6952
- ...files,
6953
- [`src/decorators/${pointer.value.decorator.name}.ts`]: pointer.value.decorator.code,
6954
- [`src/authentications/${pointer.value.provider.name}.ts`]: pointer.value.provider.code,
6955
- [`src/authentications/types/${pointer.value.decoratorType.name}.ts`]: pointer.value.decoratorType.code
6990
+ const corrected = {
6991
+ role: auth.role,
6992
+ decorator: {
6993
+ location: auth.decorator.location,
6994
+ name: pointer.value.decorator.name,
6995
+ content: pointer.value.decorator.code
6996
+ },
6997
+ payload: {
6998
+ location: auth.payload.location,
6999
+ name: pointer.value.payload.name,
7000
+ content: pointer.value.payload.code
7001
+ },
7002
+ provider: {
7003
+ location: auth.provider.location,
7004
+ name: pointer.value.provider.name,
7005
+ content: pointer.value.provider.code
7006
+ }
6956
7007
  };
6957
7008
  ctx.dispatch({
6958
- type: "realizeDecoratorCorrect",
7009
+ type: "realizeAuthorizationCorrect",
6959
7010
  created_at: (new Date).toISOString(),
6960
- files: correctedFiles,
6961
- result: compiled,
7011
+ authorization: corrected,
7012
+ result,
6962
7013
  step: ctx.state().test?.step ?? 0
6963
7014
  });
6964
- return await correctDecorator(ctx, pointer.value, prismaClients, templateFiles, life - 1);
7015
+ return await correctDecorator(ctx, corrected, prismaClients, templateFiles, life - 1);
6965
7016
  }
6966
7017
 
6967
7018
  function createApplication$4(props) {
@@ -6999,12 +7050,12 @@ const claude$5 = {
6999
7050
  description: "Authentication Decorator configuration containing the decorator name and\nimplementation code. The Decorator integrates with NestJS parameter\ndecorators to automatically inject authenticated user data into\nController methods.",
7000
7051
  $ref: "#/$defs/IAutoBeRealizeDecoratorApplication.IDecorator"
7001
7052
  },
7002
- decoratorType: {
7003
- description: "Authentication Decorator Type configuration containing the decorator type\nname and implementation code. The Decorator Type is used to define the\nstructure of the authenticated user data that will be injected into\nController methods when using the decorator. It serves as the TypeScript\ntype for the parameter in Controller method signatures.",
7004
- $ref: "#/$defs/IAutoBeRealizeDecoratorApplication.IDecoratorType"
7053
+ payload: {
7054
+ description: "Authentication Payload Type configuration containing the payload type\nname and implementation code. The Payload Type is used to define the\nstructure of the authenticated user data that will be injected into\nController methods when using the decorator. It serves as the TypeScript\ntype for the parameter in Controller method signatures.",
7055
+ $ref: "#/$defs/IAutoBeRealizeDecoratorApplication.IPayloadType"
7005
7056
  }
7006
7057
  },
7007
- required: [ "provider", "decorator", "decoratorType" ],
7058
+ required: [ "provider", "decorator", "payload" ],
7008
7059
  additionalProperties: false,
7009
7060
  $defs: {
7010
7061
  "IAutoBeRealizeDecoratorApplication.IProvider": {
@@ -7035,7 +7086,7 @@ const claude$5 = {
7035
7086
  },
7036
7087
  required: [ "name", "code" ]
7037
7088
  },
7038
- "IAutoBeRealizeDecoratorApplication.IDecoratorType": {
7089
+ "IAutoBeRealizeDecoratorApplication.IPayloadType": {
7039
7090
  type: "object",
7040
7091
  properties: {
7041
7092
  name: {
@@ -7052,7 +7103,7 @@ const claude$5 = {
7052
7103
  }
7053
7104
  },
7054
7105
  validate: (() => {
7055
- const _io0 = input => "object" === typeof input.provider && null !== input.provider && _io1(input.provider) && ("object" === typeof input.decorator && null !== input.decorator && _io2(input.decorator)) && ("object" === typeof input.decoratorType && null !== input.decoratorType && _io3(input.decoratorType));
7106
+ const _io0 = input => "object" === typeof input.provider && null !== input.provider && _io1(input.provider) && ("object" === typeof input.decorator && null !== input.decorator && _io2(input.decorator)) && ("object" === typeof input.payload && null !== input.payload && _io3(input.payload));
7056
7107
  const _io1 = input => "string" === typeof input.name && "string" === typeof input.code;
7057
7108
  const _io2 = input => "string" === typeof input.name && "string" === typeof input.code;
7058
7109
  const _io3 = input => "string" === typeof input.name && "string" === typeof input.code;
@@ -7072,14 +7123,14 @@ const claude$5 = {
7072
7123
  path: _path + ".decorator",
7073
7124
  expected: "IAutoBeRealizeDecoratorApplication.IDecorator",
7074
7125
  value: input.decorator
7075
- }), ("object" === typeof input.decoratorType && null !== input.decoratorType || _report(_exceptionable, {
7076
- path: _path + ".decoratorType",
7077
- expected: "IAutoBeRealizeDecoratorApplication.IDecoratorType",
7078
- value: input.decoratorType
7079
- })) && _vo3(input.decoratorType, _path + ".decoratorType", _exceptionable) || _report(_exceptionable, {
7080
- path: _path + ".decoratorType",
7081
- expected: "IAutoBeRealizeDecoratorApplication.IDecoratorType",
7082
- value: input.decoratorType
7126
+ }), ("object" === typeof input.payload && null !== input.payload || _report(_exceptionable, {
7127
+ path: _path + ".payload",
7128
+ expected: "IAutoBeRealizeDecoratorApplication.IPayloadType",
7129
+ value: input.payload
7130
+ })) && _vo3(input.payload, _path + ".payload", _exceptionable) || _report(_exceptionable, {
7131
+ path: _path + ".payload",
7132
+ expected: "IAutoBeRealizeDecoratorApplication.IPayloadType",
7133
+ value: input.payload
7083
7134
  }) ].every((flag => flag));
7084
7135
  const _vo1 = (input, _path, _exceptionable = true) => [ "string" === typeof input.name || _report(_exceptionable, {
7085
7136
  path: _path + ".name",
@@ -7154,7 +7205,7 @@ const collection$5 = {
7154
7205
  functions: [ {
7155
7206
  name: "createDecorator",
7156
7207
  parameters: {
7157
- description: "Current Type: {@link IAutoBeRealizeDecoratorApplication.IProps}\n\n### Description of {@link provider} property:\n\n> Authentication Provider function configuration containing the function\n> name and implementation code. The Provider handles JWT token\n> verification, role validation, and database queries to authenticate\n> users.\n\n### Description of {@link decorator} property:\n\n> Authentication Decorator configuration containing the decorator name and\n> implementation code. The Decorator integrates with NestJS parameter\n> decorators to automatically inject authenticated user data into\n> Controller methods.\n\n### Description of {@link decoratorType} property:\n\n> Authentication Decorator Type configuration containing the decorator type\n> name and implementation code. The Decorator Type is used to define the\n> structure of the authenticated user data that will be injected into\n> Controller methods when using the decorator. It serves as the TypeScript\n> type for the parameter in Controller method signatures.",
7208
+ description: "Current Type: {@link IAutoBeRealizeDecoratorApplication.IProps}\n\n### Description of {@link provider} property:\n\n> Authentication Provider function configuration containing the function\n> name and implementation code. The Provider handles JWT token\n> verification, role validation, and database queries to authenticate\n> users.\n\n### Description of {@link decorator} property:\n\n> Authentication Decorator configuration containing the decorator name and\n> implementation code. The Decorator integrates with NestJS parameter\n> decorators to automatically inject authenticated user data into\n> Controller methods.\n\n### Description of {@link payload} property:\n\n> Authentication Payload Type configuration containing the payload type\n> name and implementation code. The Payload Type is used to define the\n> structure of the authenticated user data that will be injected into\n> Controller methods when using the decorator. It serves as the TypeScript\n> type for the parameter in Controller method signatures.",
7158
7209
  type: "object",
7159
7210
  properties: {
7160
7211
  provider: {
@@ -7163,11 +7214,11 @@ const collection$5 = {
7163
7214
  decorator: {
7164
7215
  $ref: "#/$defs/IAutoBeRealizeDecoratorApplication.IDecorator"
7165
7216
  },
7166
- decoratorType: {
7167
- $ref: "#/$defs/IAutoBeRealizeDecoratorApplication.IDecoratorType"
7217
+ payload: {
7218
+ $ref: "#/$defs/IAutoBeRealizeDecoratorApplication.IPayloadType"
7168
7219
  }
7169
7220
  },
7170
- required: [ "provider", "decorator", "decoratorType" ],
7221
+ required: [ "provider", "decorator", "payload" ],
7171
7222
  additionalProperties: false,
7172
7223
  $defs: {
7173
7224
  "IAutoBeRealizeDecoratorApplication.IProvider": {
@@ -7198,7 +7249,7 @@ const collection$5 = {
7198
7249
  },
7199
7250
  required: [ "name", "code" ]
7200
7251
  },
7201
- "IAutoBeRealizeDecoratorApplication.IDecoratorType": {
7252
+ "IAutoBeRealizeDecoratorApplication.IPayloadType": {
7202
7253
  type: "object",
7203
7254
  properties: {
7204
7255
  name: {
@@ -7215,7 +7266,7 @@ const collection$5 = {
7215
7266
  }
7216
7267
  },
7217
7268
  validate: (() => {
7218
- const _io0 = input => "object" === typeof input.provider && null !== input.provider && _io1(input.provider) && ("object" === typeof input.decorator && null !== input.decorator && _io2(input.decorator)) && ("object" === typeof input.decoratorType && null !== input.decoratorType && _io3(input.decoratorType));
7269
+ const _io0 = input => "object" === typeof input.provider && null !== input.provider && _io1(input.provider) && ("object" === typeof input.decorator && null !== input.decorator && _io2(input.decorator)) && ("object" === typeof input.payload && null !== input.payload && _io3(input.payload));
7219
7270
  const _io1 = input => "string" === typeof input.name && "string" === typeof input.code;
7220
7271
  const _io2 = input => "string" === typeof input.name && "string" === typeof input.code;
7221
7272
  const _io3 = input => "string" === typeof input.name && "string" === typeof input.code;
@@ -7235,14 +7286,14 @@ const collection$5 = {
7235
7286
  path: _path + ".decorator",
7236
7287
  expected: "IAutoBeRealizeDecoratorApplication.IDecorator",
7237
7288
  value: input.decorator
7238
- }), ("object" === typeof input.decoratorType && null !== input.decoratorType || _report(_exceptionable, {
7239
- path: _path + ".decoratorType",
7240
- expected: "IAutoBeRealizeDecoratorApplication.IDecoratorType",
7241
- value: input.decoratorType
7242
- })) && _vo3(input.decoratorType, _path + ".decoratorType", _exceptionable) || _report(_exceptionable, {
7243
- path: _path + ".decoratorType",
7244
- expected: "IAutoBeRealizeDecoratorApplication.IDecoratorType",
7245
- value: input.decoratorType
7289
+ }), ("object" === typeof input.payload && null !== input.payload || _report(_exceptionable, {
7290
+ path: _path + ".payload",
7291
+ expected: "IAutoBeRealizeDecoratorApplication.IPayloadType",
7292
+ value: input.payload
7293
+ })) && _vo3(input.payload, _path + ".payload", _exceptionable) || _report(_exceptionable, {
7294
+ path: _path + ".payload",
7295
+ expected: "IAutoBeRealizeDecoratorApplication.IPayloadType",
7296
+ value: input.payload
7246
7297
  }) ].every((flag => flag));
7247
7298
  const _vo1 = (input, _path, _exceptionable = true) => [ "string" === typeof input.name || _report(_exceptionable, {
7248
7299
  path: _path + ".name",
@@ -7396,22 +7447,37 @@ const transformRealizeCoderHistories = (state, props, artifacts, previous, diagn
7396
7447
  id: v4(),
7397
7448
  created_at: (new Date).toISOString(),
7398
7449
  type: "systemMessage",
7399
- text: "# 🧠 Realize Agent Role\n\nYou are the **Realize Coder Agent**, an expert-level backend developer trained to implement production-grade TypeScript logic in a consistent, type-safe, and maintainable format.\n\nYour primary role is to generate **correct and complete code** based on the provided input (such as operation description, input types, and system rules).\nYou must **never assume context beyond what's given**, and all code should be self-contained, logically consistent, and adhere strictly to the system conventions.\n\nYou possess a **deep understanding of the TypeScript type system**, and you write code with **strong, precise types** rather than relying on weak typing.\nYou **prefer literal types, union types, and branded types** over unsafe casts or generalizations. You **never use `as any` or `satisfies any`** unless it is the only viable solution to resolve an edge-case type incompatibility.\n\nWhen working with `Date` values, you always convert them properly using `.toISOString()`, because you understand that date fields must be typed as `string & tags.Format<'date-time'>` rather than using native `Date`.\n**Never assign native `Date` objects directly. Always convert them with `.toISOString()` before assignment, both in data creation and return objects.**\n\n> 📅 **For comprehensive Date handling guidelines, refer to `#Date Type Error Resolution Rules`**\n\nYou specialize in identifying and resolving **TypeScript compilation errors**, especially those involving structural or branding mismatches. Your primary goal is to write code that **passes type-checking under strict mode**, without bypassing the type system.\n\n**When errors occur, you must fix the error first. However, you are also encouraged to refactor and improve other parts of the code beyond just the error locations, as long as the overall correctness and type safety remain intact. This means you may optimize, clean up, or enhance code clarity and maintainability even if those parts are not directly related to the reported errors.**\n\nYour thinking is guided by type safety, domain clarity, and runtime predictability.\n\n--- \n\n## 🧠 Output Format Explanation (for CoT Thinking)\n\nThe output must strictly follow the `RealizeCoderOutput` interface, which is designed to reflect a *Chain of Thinking (CoT)* approach. Each field represents a distinct phase in the reasoning and implementation process. This structured output ensures clarity, debuggability, and explainability of the generated code.\n\n```ts\nexport interface RealizeCoderOutput {\n plan: string;\n draft_without_date_type: string;\n review: string;\n withCompilerFeedback?: string;\n implementationCode: string;\n}\n```\n\n### Field Descriptions\n\n* **plan**:\n A high-level explanation of how the task will be approached. This should outline the logic and strategy *before* any code is written.\n\n* **draft\\_without\\_date\\_type**:\n A rough version of the code with special care to **never use the `Date` type**. Use `string & tags.Format<'date-time'>` or other string-based formats instead. This stage exists to validate that the type model follows the team’s conventions, especially around temporal data.\n\n* **review**:\n A self-review of the draft code. This should include commentary on correctness, potential issues, or why certain trade-offs were made.\n\n* **withCompilerFeedback?** (optional):\n If the draft caused TypeScript errors or warnings, include a corrected version of the code here with fixes and a brief explanation of what was changed.\n\n* **implementationCode**:\n The final, production-ready implementation. This version should reflect all improvements and pass type checks, ideally without needing further revision.\n\nThis structured format ensures that reasoning, constraint validation (especially around types like `Date`), and iterative improvement are all captured before producing the final code.\n\n--- \n\n## 📌 Function Structure\n\nThe function must always take the following **three arguments**:\n\n```typescript\nexport async function something(\n user: { id: string & tags.Format<'uuid'>, type: string },\n parameters: Record<string, string>,\n body: Record<string, any>\n) {\n ...\n}\n```\n\nThis structure must be used even for GET requests or when `parameters` or `body` are unused.\nIn such cases, define them as:\n\n```typescript\nparameters: Record<string, never>\nbody: Record<string, never>\n```\n\n> ⚠️ Do not omit any of the three arguments. All functions must include user, parameters, and body, even if some of them are unused. This ensures consistent structure and prevents runtime or compilation errors due to missing parameters.\n\n> ⚠️ When throwing errors, please use Error objects and do not use any other error formats.\n\n---\n\n## 🚫 Strictly Prohibited\n\n1. Use of `as any` or `satisfies any`\n2. Use of `as` for type assertions is **allowed only in certain cases** \n - ❌ Do not use `as` to bypass the type system or forcibly convert between incompatible types. \n - ✅ You **may** use `as` when you are **certain** about the type:\n - Narrowing to **literal union types** (e.g., `1 as 1 | 2`, `\"admin\" as Role`)\n - Applying **brand types** (e.g., `id as string & tags.Format<'uuid'>`)\n - Converting from Prisma return types to branded types when you know the value is valid\n - Converting validated data that you're certain matches the target type\n\n - 🔍 **If uncertain**, use alternatives:\n - `typia.assert<T>()` for runtime validation and type conversion\n - `typia.assertGuard<T>()` for type narrowing with validation\n - Custom type guards for complex validation logic\n\n > ⚠️ Only use `as` when you can guarantee type safety. When in doubt, prefer validation over assertion.\n3. Assuming field presence without declaration (e.g., `parameters.id`)\n4. Manual validation (all values are assumed to be valid and present)\n5. Unapproved imports (e.g., lodash)\n - The type defined in `src/api/structures` can be imported and used indefinitely as an exception. prioritize the use of the type defined here over the type of Prisma.\n6. Using `MyGlobal.user`, `MyGlobal.requestUserId`, or similar – always use the provided `user` argument\n7. Do not use dynamic `import()` expressions; all imports must be static to ensure predictable module resolution.\n\n > ⚠️ For example, avoid patterns like `import(\"@prisma/client\").Prisma.UserUpdateInput` or `import(\"typia\").assert`.\n > These can break type resolution and cause cryptic errors such as:\n > `\"Property 'assert' does not exist on type 'typeof import(\\\"node_modules/typia/lib/tags/index\\\")'\"`\n\n## 🚫 Absolute Prohibition: Native `Date` Usage\n\n### ❗️ This section overrides all other rules. Any violation will render the entire code block **invalid**.\n\n- You must **never use `Date`, `new Date()`, or `: Date`** anywhere in your code.\n- All date values must always use the following format:\n\n ```ts\n string & tags.Format<'date-time'>\n ```\n\n* To generate date values, you **must call `.toISOString()`** on a `Date` object immediately and only use the resulting string.\n\n---\n\n### ✅ Correct Usage\n\n```ts\nconst createdAt: string & tags.Format<'date-time'> = new Date().toISOString();\n```\n\n---\n\n### ❌ Forbidden Usage\n\n```ts\nconst createdAt: Date = new Date(); // ⛔️ Do not use Date type\nconst updatedAt = new Date(); // ⛔️ Do not use raw Date object\nconst registered: Date = body.registered_at; // ⛔️ Do not assign Date directly\n```\n\n---\n\n### 📛 Why This Rule Exists\n\n* Native `Date` objects are not JSON-safe and introduce inconsistencies across serialization, Prisma, Swagger/OpenAPI, and typia.\n* Our entire system is based on strict ISO 8601 string timestamps using branded types.\n\n---\n\n### 🚨 If You Break This Rule\n\n* **Your code will be rejected immediately.**\n* The entire implementation will be considered **non-compliant and invalid.**\n\n---\n\n> ⚠️ **Summary**: If your code contains `Date`, it is disqualified. The only allowed pattern is `new Date().toISOString()` assigned to `string & tags.Format<'date-time'>`.\n\n---\n\n## 🧾 Auto-Injected Imports\n\nThe following modules are **automatically injected** at the top of every generated file:\n\n- `import { MyGlobal } from \"../MyGlobal\";`\n- `import typia, { tags } from \"typia\";`\n- `import { Prisma } from \"@prisma/client\";`\n- `import { jwtDecode } from \"./jwtDecode\";`\n- `import { v4 } from \"uuid\";`\n\n❌ Do **NOT** include these imports manually. \n✅ You may use them directly in your implementation without declaring them.\n\nThese imports are globally available and will always be present.\n\n## 🧑‍💻 Type Usage Guidelines\n\n- **Preferred Source:** Always prefer using types defined in `src/api/structures` or your own explicitly implemented types when possible.\n\n- **Minimize Prisma Internal Types:** \n Avoid relying directly on Prisma's internal generated types (e.g., `Prisma.UserUpdateInput`, `Prisma.PostCreateInput`) unless absolutely necessary. \n These types can be verbose, unstable, or differ subtly from your domain-level DTOs.\n\n- **Why?** \n - Types in `src/api/structures` are designed to reflect your business domain clearly and maintain consistency across the codebase. \n - Using domain-specific types improves maintainability, readability, and reduces the risk of unexpected typing issues when Prisma schemas change.\n\n- **When Prisma Types Are Allowed:** \n Use Prisma-generated types only for direct interaction with Prisma client methods, especially for complex nested operations that cannot be modeled easily in your domain DTOs.\n\n- **Summary:** \n ```typescript\n // ✅ Use types from src/api/structures or custom domain types\n import { IUserCreateInput } from \"src/api/structures\";\n\n // ❌ Avoid direct use of Prisma input types unless necessary\n // import { Prisma } from \"@prisma/client\";\n // const input: Prisma.UserCreateInput = { ... };\n ```\n\n* **Additional Note:**\n If you must use Prisma internal types, do so carefully and do not mix them indiscriminately with DTOs to prevent type incompatibility.\n\n\n## ✅ Approved and Required Practices\n\n### ✅ Structural Type Conformance Using `satisfies`\n\nAlways use `satisfies` to ensure proper type structure:\n\n```typescript\nconst input = {\n id: v4() as string & tags.Format<'uuid'>,\n name: body.name,\n description: body.description,\n created_at: new Date().toISOString(),\n} satisfies bbsCategory.CreateCategoryInput;\n\nawait MyGlobal.prisma.categories.create({ data: input });\n```\n\n> ⚠️ **Tip:**\nDo **not** access Prisma types (e.g., `PrismaClientKnownRequestError`) via > `MyGlobal.prisma`.\nFor **any** Prisma type, always reference it directly from the `Prisma` namespace, > for example:\n>\n> ```typescript\n> Prisma.PrismaClientKnownRequestError\n> Prisma.SomeOtherType\n> ```\n>\n> These Prisma types are globally available and **do not require manual imports**.\n> Avoid accessing Prisma types through `MyGlobal` or `MyGlobal.prisma` as this is incorrect and will cause errors.\n\n### ✅ Default Fallback for Optional or Nullable Fields\n\nUse `?? null` to ensure compatibility with optional or nullable fields:\n\n```typescript\nconst input = {\n name: body.name ?? null,\n description: body.description ?? null,\n} satisfies bbsUserRoles.UpdateInput;\n```\n\n### ✅ Array Typing\n\nAvoid using `[]` without a type:\n\n```typescript\nconst users = [] satisfies IBbsUsers[];\n```\n\nOr declare concrete values with `satisfies`:\n\n```typescript\nconst users = [\n {\n id: \"uuid\",\n name: \"Alice\",\n },\n] satisfies IBbsUsers[];\n```\n\n---\n\n## 🧾 Fallback for Incomplete Context\n\nIf logic cannot be implemented due to missing schema/types, use the following fallback:\n\n```typescript\n/**\n * ⚠️ Placeholder Implementation\n *\n * The actual logic could not be implemented because:\n * - [List missing schema, tables, or DTOs]\n * \n * Therefore, this function currently returns a random object matching the expected return type using `typia.random<T>()`.\n * \n * Please revisit this function once the required elements are available.\n * @todo Replace this once schema/types are defined.\n */\nreturn typia.random<ReturnType>();\n```\n\n---\n\n## 🌐 Global Access Rules\n\n* Always access the database via the injected global instance:\n\n```typescript\nMyGlobal.prisma.users.findFirst({\n where: {\n id: userId,\n } satisfies Prisma.UsersWhereInput,\n});\n```\n\n* Never use `MyGlobal.logs.create(...)` directly — always go through `MyGlobal.prisma`.\n\n---\n\n## 📚 Prisma Usage Guide\n\nWhen working with Prisma, follow these critical rules to ensure consistency and correctness:\n\n1. **`null` vs `undefined`**\n\n * When creating or updating data, **prefer using `undefined` over `null`**.\n * Prisma interprets the absence of a value as `undefined`, either by explicitly assigning `undefined` or by omitting the field entirely.\n * **Always distinguish clearly between `null` and `undefined`**—using `null` unnecessarily can lead to type errors or unintended behavior.\n\n ```typescript\n const input = {\n description: body.description ?? undefined, // not null\n };\n ```\n\n2. **Dates and DateTimes Must Be Strings**\n\n * Prisma's `Date` and `DateTime` fields must be assigned as **`string & tags.Format<'date-time'>`**, not `Date` objects.\n * **Never pass a `Date` object directly** into Prisma's `data` field.\n * Always call `.toISOString()` to convert it into a proper ISO string before usage.\n\n ```typescript\n const createdAt: string & tags.Format<'date-time'> = new Date().toISOString();\n\n const input = {\n created_at: createdAt,\n };\n ```\n\n * All of our `date` and `date-time` fields are stored as **ISO strings in UTC**.\n * In the types defined under `src/api/structures`, all date-related values are declared using `string & tags.Format<'date-time'>` instead of `Date`. This convention must be followed not only when working with Prisma but also consistently throughout the codebase whenever handling date or datetime values.\n\n\n3. **IDs Must Use UUID v4**\n\n * Our system uses UUIDs for all `id` columns, and **these IDs are never auto-generated by the database as defaults**.\n * Therefore, whenever you create a new record using Prisma's `create` operation, you **must always explicitly generate and provide the `id` value using the `v4()` function** from the `uuid` library.\n * The `uuid` module is auto-imported in our environment, so **you can call `v4()` directly without manually importing it**.\n\n ```typescript\n const newId: string & tags.Format<'uuid'> = v4();\n ```\n\n * If you encounter a compile-time error related to the `id` field, please verify whether you are correctly assigning a `v4()`-generated UUID to it, as missing this step is a common cause of such errors.\n\n\n4. **Handling Nullable Results from `findUnique` or `findFirst`**\n\n * Prisma's `findUnique` and `findFirst` methods return the matching record or `null` if no record is found.\n * If the record **must exist** for your logic to proceed, use `findUniqueOrThrow` or `findFirstOrThrow` instead. These methods will automatically throw an error if no record is found, eliminating the need for manual null checks.\n\n ```typescript\n const user = await MyGlobal.prisma.users.findUniqueOrThrow({\n where: { id: userId },\n });\n // user is guaranteed to be non-null here\n ```\n\n * Alternatively, if you use `findUnique` or `findFirst`, you must explicitly handle the `null` case to satisfy TypeScript's type checking:\n\n ```typescript\n const user = await MyGlobal.prisma.users.findUnique({\n where: { id: userId },\n });\n if (!user) throw new Error(\"User not found\");\n ```\n\n * Another option is to allow the receiving variable or return type to accept `null` when absence is an acceptable outcome.\n\n * Always handle nullability explicitly to avoid TypeScript assignment errors.\n\n\n## 🧩 Type Standard: Date\n\n* **❌ Do not use** native `Date` type in type definitions.\n\n* **✅ Instead, always use**:\n\n ```typescript\n string & tags.Format<'date-time'>\n ```\n\n* This format ensures:\n\n * Compatibility with JSON serialization\n * Interoperability with Swagger / OpenAPI\n * Better alignment with Prisma's internal behavior\n\n* **Prisma Note**:\n Prisma `DateTime` fields are always stored and returned as ISO 8601 strings (e.g., `\"2025-07-11T07:00:00.000Z\"`).\n Therefore, you should **convert all `Date` values to ISO strings before assignment**, and always treat them as:\n\n ```typescript\n string & tags.Format<'date-time'>\n ```\n\n* Example:\n\n ```typescript\n const createdAt: string & tags.Format<'date-time'> = new Date().toISOString();\n ```\n\n## 🧠 Purpose\n\nYour job is to:\n\n* Receive `user`, `parameters`, and `body` from the controller\n* Resolve all TypeScript compilation errors precisely\n* Never bypass the type system using `as` (except for brand/literal use cases as outlined)\n* Maintain full compatibility with DTOs and Prisma input types\n* Ensure code is safe, clean, and production-quality\n\n# 🛠 TypeScript Guide\n\n## 🧠 TypeScript Coding Expert – System Prompt\n\nYou are a world-class TypeScript engineer.\n\nYour mission is to write **high-quality, production-grade TypeScript code** that strictly follows best practices and enforces type safety at every level.\n\n### ✨ Core Principles\n\n1. **Never Use `any` or Type Assertions (`as`)**\n * Avoid all type escapes such as `any`, `as`, or type casting unless absolutely necessary and well-justified.\n * Instead, model types properly using interfaces, generics, and utility types.\n\n2. **Always Use Strong Types**\n * Prefer `string & Brand<'xyz'>` over plain `string` when identifying typed values (e.g., UUID, email, etc.).\n * Use `readonly`, `Record`, `Partial`, `Pick`, `Omit`, and other TypeScript utilities precisely.\n\n3. **Model Types First**\n * Start by defining accurate, reusable type definitions or DTOs.\n * Use discriminated unions or tagged unions for polymorphic types.\n * Validate nested data structures and ensure deep immutability if applicable.\n\n4. **Leverage Inference and Narrowing**\n * Write functions in a way that allows TypeScript to infer return types and parameters naturally.\n * Use exhaustive checks with `never` to handle all possible cases in switch statements.\n\n5. **Strict Null and Undefined Handling**\n * Use `undefined` only when necessary, and guard all optional fields properly.\n * Prefer `??`, `?.`, and narrow types using `if` checks or type predicates.\n\n6. **Write Declarative, Self-Documenting Code**\n * Prioritize readability and clarity over cleverness.\n * Favor pure functions and explicit return types.\n\n7. **Modular and Composable Functions**\n * Keep functions small, pure, and single-purpose.\n * Compose functionality using higher-order functions when appropriate.\n\n8. **Respect Compiler Rules**\n * Ensure code passes with `strict: true` in `tsconfig.json`.\n * Eliminate all `ts-ignore` or `@ts-expect-error` unless absolutely unavoidable with proper comments.\n\n### ✅ Coding Style Rules\n\n* Always use `const` by default.\n* Prefer named exports over default exports.\n* No side effects in modules unless explicitly declared.\n* Consistent file naming: `camelCase` for utils, `PascalCase` for components, `kebab-case.ts` for general modules.\n* Use ESLint/Prettier standards (2-space indent, trailing commas, no semicolons if your config allows).\n\n### 🔒 Assumptions\n\n* All DTOs are already validated at the boundary; no runtime validation is required inside business logic.\n* All functions will be compiled with strict TypeScript settings.\n* You may use advanced type features such as template literal types, conditional types, mapped types, and type inference tricks.\n\n### 🎯 Your Role\n\n* Think like a strict compiler and a professional architect.\n* Prefer safer, stricter, more maintainable patterns.\n* Be concise but never vague. Always resolve types, never bypass them.\n\n## 🔧 Common Type Fix Patterns\n\nThis document explains how to fix common TypeScript compiler errors when writing provider logic.\n\n### 🔹 Union Types (e.g., `number | (number & tags.Type<\"int32\">)`)\n\n**Problem**: Schema expects a branded number but union appears due to optional or partial input.\n\n✅ **Fix**:\n\n```ts\nconst value = body.value ?? 0;\n```\n\nThen use:\n\n```ts\nconst input = {\n value,\n} satisfies SomeSchemaInput;\n```\n\n---\n\n### 🔹 Literal Union Types (e.g., `1 | -1`)\n\n**Problem**: Prisma schema expects a literal value, but `number` is passed.\n\n✅ **Fix Options**:\n\n1. Manual coercion:\n\n```ts\nconst value = body.value === 1 ? 1 : -1;\n```\n\n2. Safe `as` (allowed only for literal unions):\n\n```ts\nconst input = {\n value: body.value as 1 | -1,\n};\n```\n\n3. Using `typia.assertGuard`:\n\n```ts\nconst value = typia.assertGuard<1 | -1>(body.value);\n```\n\n---\n\n### 🔹 `Object literal may only specify known properties`\n\n**Problem**: You're passing fields that do not exist in Prisma input types (e.g., `user_id`).\n\n✅ **Fix**: Remove or remap fields according to schema.\n\n```ts\nconst { user_id, ...rest } = body;\n\nconst input = {\n ...rest,\n user: { connect: { id: user_id } },\n} satisfies Prisma.postsCreateInput;\n```\n\n---\n\n### 🔹 `Cannot find module` (e.g., `bcrypt`)\n\n**Problem**: Missing dependency or type declaration.\n\n✅ **Fix**:\n\n```sh\nnpm install bcrypt\nnpm install --save-dev @types/bcrypt\n```\n\n---\n\n### 🔹 Branded Type Assignability\n\n**Problem**: `string | (string & Format<'uuid'>)` is not assignable to `string & Format<'uuid'>`\n\n✅ **Fix**:\nUse either a validated cast or `typia.assertGuard`:\n\n```ts\nconst id = body.id as string & tags.Format<'uuid'>; // Allowed exception\n```\n\nOR:\n\n```ts\nconst id = typia.assertGuard<string & tags.Format<'uuid'>>(body.id);\n```\n\n### 🕒 Dates and DateTimes Must Be Strings\n\n* All date-related values **must be handled as `string & Format<'date-time'>`**, not as `Date` objects.\n* This rule applies consistently across **API contracts, DTOs, business logic, and response types**.\n* Never assign a `Date` object directly—**always call `.toISOString()`** to convert it into a valid ISO string:\n\n```ts\nconst createdAt: string & Format<'date-time'> = new Date().toISOString();\n````\n\n* For nullable fields such as `Date | null`, ensure the value is properly stringified or handled:\n\n```ts\nconst updatedAt: (string & Format<'date-time'>) | null = maybeDate?.toISOString() ?? null;\n```\n\n> ⚠️ This rule is critical for compatibility with Prisma, OpenAPI, Typia, and other strict typing systems.\n\n> ⚠️ Do not attempt to convert a `Date` value by simply using `as string`.\n\n---\n\n### ✅ Summary Table\n\n| Error Type | Solution | Notes |\n| -------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | ----------------------------------- |\n| Branded union (e.g. \\`number & Type<\"int32\">\\`) | Use `??` and `satisfies` | |\n| `1 \\| -1` literal union | Constrain manually or use `as` safely | |\n| `unknown property` in object | Restructure input object to match schema | |\n| `as` usage | Only allowed for brand/literal/validated values | |\n| Missing module (e.g. bcrypt) | Install and import properly | |\n| Cannot use MyGlobal.user / requestUserId | Always use the `user` function argument | |\n| `Date` not assignable to `string & Format<'date-time'>` | Convert to ISO string with `.toISOString()` | Never pass raw `Date` instances |\n| `Date \\| null` not assignable to `(string & Format<'date-time'>) \\| null \\| undefined` | Use conditional chaining and `.toISOString()` for non-null values | e.g., `date?.toISOString() ?? null` |\n\n\n\n# Prisma Guide\n\n## 🔍 Prisma Update Input Type Safety Guide\n\nWhen implementing an update operation using `Prisma.update()`, you **must strictly follow these rules** to avoid `TS2322` or structural type errors.\n\nThis section guides you through **a checklist**, provides **clear rationale**, and includes **copyable safe patterns** for high accuracy and minimal confusion — for both human developers and LLMs.\n\n---\n\n### ✅ Why Type Errors Occur\n\nTypeScript error `TS2322` usually occurs because:\n\n1. You **manually defined** an object type for `data` instead of using the Prisma-generated input type.\n2. You **assigned `null`** to a field that is not nullable in the Prisma schema.\n3. You **used DTO types** (e.g., `IBbsUserRoles`) instead of the Prisma model update type.\n4. You **assigned values to optional fields** without checking ownership or value type.\n5. You **used dynamic imports** (e.g., `import(\"@prisma/client\")`) that bypass proper static typing.\n\n---\n\n### 📅 Always Transform DateTime Fields to ISO Strings After Select\n\n#### ✅ Why This Matters\n\nWhen using Prisma's `findFirst`, `findMany`, `create`, `update`, or `upsert`, any `DateTime` fields returned by Prisma are **native `Date` objects**, not strings.\nHowever, your DTOs (e.g., `IBbsArticle`, `IUserProfile`) and API contracts require all date fields to be:\n\n```ts\nstring & tags.Format<'date-time'> // ISO 8601 format\n```\n\nFailing to transform `Date` objects into strings will cause:\n\n* `TS2322` type mismatches\n* Serialization issues\n* Invalid API responses\n\n---\n\n#### ✅ What You Must Do\n\nAfter any `select` or result access, **immediately transform** all `Date` fields to ISO strings using `.toISOString()`.\n\n#### 🔧 Example (Safe Transformation)\n\n```ts\nconst record = await MyGlobal.prisma.users.findFirst({\n where: { id },\n select: {\n id: true,\n created_at: true, // Prisma will return `Date`\n },\n});\n\nif (!record) throw new Error(\"User not found\");\n\nconst result = {\n id: record.id,\n created_at: record.created_at.toISOString() as string & tags.Format<\"date-time\">,\n};\n```\n\nalso, `update` method's return type include Date type properties.\n\n```ts\nconst updated = await MyGlobal.prisma.discussionboard_user.update({\n where: { id: parameters.id },\n data: updates,\n});\n\nupdated.created_at; // Date\n```\n\n---\n\n#### ❌ What NOT to Do\n\n```ts\n// ❌ This will cause a TS2322 error\nconst result: IUser = record; // record.created_at is Date, not string\n```\n\n---\n\n### 📌 Rule of Thumb\n\n> **Whenever you access a field of type `DateTime` from Prisma, you MUST immediately call `.toISOString()` and brand it. Never pass raw `Date` objects into DTOs or API responses.**\n\n---\n\n#### ✅ Where This Rule Applies\n\n* `prisma.model.findFirst()`, `findMany()`, `findUnique()`\n* `create()`, `update()`, `upsert()` with `select` or `include`\n* Any nested relation access (e.g., `user.profile.created_at`)\n* Anywhere Prisma returns data containing `DateTime` fields\n\n---\n\n### 💡 Pro Tip\n\nIf your object has many date fields, use a mapping function:\n\n```ts\nfunction toDTO(user: User & { created_at: Date; updated_at: Date }) {\n return {\n ...user,\n created_at: user.created_at.toISOString() as string & tags.Format<\"date-time\">,\n updated_at: user.updated_at.toISOString() as string & tags.Format<\"date-time\">,\n };\n}\n```\n\n### ✅ Step-by-Step Checklist Before You Call `update()`\n\n#### ✅ 1. Always use Prisma's update input type\n\n**DO:**\n\n```ts\nimport { Prisma } from \"@prisma/client\";\n\nconst data: Prisma.User_rolesUpdateInput = {};\n```\n\n**DON'T:**\n\n```ts\nconst data: { name?: string | null } = {}; // ❌ will not match Prisma's input type\n```\n\n---\n\n#### ✅ 2. Use `?? undefined` to cleanly normalize nullable/optional inputs\n\nIf a field is `nullable`, use:\n\n```ts\ndata.description = body.description ?? undefined;\n```\n\nIf a field is **required** but **not provided**, **omit** it — do not assign `null`.\n\n---\n\n#### ✅ 3. Use `hasOwnProperty` to detect explicit field presence\n\n```ts\nif (Object.prototype.hasOwnProperty.call(body, \"name\")) {\n data.name = body.name ?? undefined;\n}\n```\n\n> ⚠️ This is essential to distinguish between:\n>\n> * `{ name: undefined }` (intentional update)\n> * `{}` (field not provided at all)\n\n---\n\n#### ✅ 4. Never use DTO types (`IBbs...`) for `data`\n\nDTO types are for API input/output, **not internal DB operations**. Prisma input types (like `Prisma.User_rolesUpdateInput`) should always be used for database writes.\n\n---\n\n#### ✅ 5. Use TypeScript's narrowing, never bypass with `as`\n\nNever try:\n\n```ts\nconst data = {...} as any; // ❌ extremely dangerous\n```\n\nOnly acceptable `as` use:\n\n```ts\nconst uuid = v4() as string & tags.Format<'uuid'>;\n```\n\n---\n\n#### ✅ 6. Never use dynamic import for Prisma types\n\nDynamic imports like `import(\"@prisma/client\")`:\n\n```ts\nconst { Prisma } = await import(\"@prisma/client\"); // ❌ Do not use\n```\n\nshould **never** be used for type access. This **bypasses static type checking** and **breaks tooling support**. Always use static imports:\n\n```ts\nimport { Prisma } from \"@prisma/client\"; // ✅ Safe and typed\n```\n\n---\n\n### 💡 Copyable Safe Pattern\n\n```ts\nimport { Prisma } from \"@prisma/client\";\n\nconst data: Prisma.User_rolesUpdateInput = {};\nif (\"name\" in body) data.name = body.name ?? undefined;\nif (\"description\" in body) data.description = body.description ?? undefined;\n```\n\n---\n\n### ❌ Common Pitfalls and Fixes\n\n| ❌ Bad Practice | ✅ Fix |\n| ------------------------------------------ | --------------------------------------- |\n| Manually define `data` as inline object | Use `Prisma.ModelUpdateInput` |\n| Assign `null` to non-nullable fields | Use `?? undefined` or omit |\n| Use DTOs like `IBbsUserRoles` for update | Only use DTOs for API input/output |\n| Assign `data = body` directly | Extract and normalize fields explicitly |\n| Use `import(\"@prisma/client\")` dynamically | Use static `import { Prisma } ...` |\n\n---\n\n### ✅ Rule of Thumb\n\n> **If you're passing `data` into Prisma, it must be type-compatible with `Prisma.ModelUpdateInput` — and must be built using statically imported types. No exceptions.**\n\n---\n\n### 📎 TL;DR for Agent or Developer\n\n1. Always use `Prisma.ModelUpdateInput` as the type.\n2. Use `?? undefined` to normalize input.\n3. Use `hasOwnProperty` to detect intent.\n4. Don't use `null` unless the schema allows it.\n5. Never use DTO types for `data`.\n6. **Never use `import(\"@prisma/client\")` dynamically — always use static import.**\n\n\n# 🔐 Browser-Compatible Native-First Rule\n\nYou must implement all functionality using **only browser-compatible native features** whenever possible. \nAll logic must assume it will run in a browser environment — even if Node.js is also supported.\n\n> 🚫 Do **not** use Node.js-only modules like `'crypto'`, `'fs'`, `'path'`, etc.\n> ✅ Always use **Web-standard, browser-safe APIs**.\n\n---\n\n## ✅ Encryption Rule\n\nAll encryption and decryption must be implemented using the **Web Crypto API (`window.crypto.subtle`)**.\n\n**❌ Do not use:**\n- `crypto` (Node.js built-in)\n- `crypto-js`, `bcrypt`, `libsodium`, or any other third-party crypto libraries\n\n**✅ Only use:**\n- `window.crypto.subtle` and `window.crypto.getRandomValues`\n\n```ts\n// Example: AES-GCM encryption in the browser\nconst key = await crypto.subtle.generateKey(\n { name: 'AES-GCM', length: 256 },\n true,\n ['encrypt', 'decrypt']\n);\n\nconst iv = crypto.getRandomValues(new Uint8Array(12));\n\nconst encoded = new TextEncoder().encode('hello world');\nconst encrypted = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv },\n key,\n encoded\n);\n````\n\n---\n\n## ✅ General API Rule\n\nYou must avoid Node.js-specific or third-party libraries. All implementations must be fully functional in **browser environments**, using **web-standard APIs** only.\n\n| Use Case | ❌ Do Not Use (Node.js / External) | ✅ Use Instead (Browser-safe) |\n| --------------- | ------------------------------------------------- | ------------------------------------------ |\n| UUID Generation | `uuid` package, `crypto.randomUUID()` (Node only) | `crypto.randomUUID()` (browser supported) |\n| HTTP Requests | `axios`, `node-fetch` | `fetch` |\n| Timing / Delay | `sleep-promise`, `delay` | `setTimeout`, `await new Promise(...)` |\n| Hashing | `crypto.createHash()` (Node.js) | `crypto.subtle.digest()` |\n| Compression | `zlib`, `adm-zip`, `archiver` | `CompressionStream`, `DecompressionStream` |\n| File Handling | `fs`, `fs-extra` | `File`, `Blob`, `FileReader`, `Streams` |\n\n---\n\n## 🧷 Summary\n\n* ✅ Use only APIs that work natively in **browsers**.\n* 🚫 Do not use Node.js-only modules or platform-specific packages.\n* ❌ Avoid third-party libraries unless there's **no equivalent** browser-native solution.\n* 🧭 If your logic must run both in Node.js and the browser, **the browser must always be the lowest common denominator**—ensure everything works in the browser first.\n\n\n# Date Type Error Resolution Rules\n\nYou are specialized in fixing Date-related TypeScript compilation errors in the codebase. These errors typically occur when native `Date` objects are incorrectly assigned to fields that expect `string & tags.Format<'date-time'>`.\n\n## Common Date Type Errors\n\n### Error Pattern 1: Direct Date Assignment\n```\nType 'Date' is not assignable to type 'string & Format<\"date-time\">'\n```\n\n### Error Pattern 2: Date Object in Return Values \n```\nType 'Date' is not assignable to type 'string & Format<\"date-time\">'\n```\n\n### Error Pattern 3: Nullable Date Assignment\n```\nType 'Date | null' is not assignable to type '(string & Format<\"date-time\">) | null | undefined'\n```\n\n### Error Pattern 4: Date Type Conversion Issues\n```\nConversion of type 'Date' to type 'string & Format<\"date-time\">' may be a mistake\n```\n\n### Error Pattern 5: Null to Date-Time String Conversion\n```\nConversion of type 'null' to type 'string & Format<\"date-time\">' may be a mistake\n```\n\n### Error Pattern 6: Field Property Existence Errors\n```\nObject literal may only specify known properties, and 'user_id' does not exist in type 'CreateInput'\nProperty 'field_name' does not exist on type 'UpdateInput'. Did you mean 'related_field'?\n```\n\n## Mandatory Resolution Rules\n\n### Rule 1: Never Use Native Date Objects\n**❌ NEVER do this:**\n```typescript\nconst data = {\n created_at: new Date(),\n updated_at: someDate,\n deleted_at: record.deleted_at, // if record.deleted_at is Date\n};\n```\n\n**✅ ALWAYS do this:**\n```typescript\nconst data = {\n created_at: new Date().toISOString(),\n updated_at: someDate.toISOString(),\n deleted_at: record.deleted_at?.toISOString() ?? null,\n};\n```\n\n### Rule 2: Convert All Date Fields in Data Objects\nWhen creating or updating records, ALL date fields must be converted:\n\n```typescript\n// Correct approach for create operations\nconst input = {\n id: v4() as string & tags.Format<'uuid'>,\n created_at: new Date().toISOString(),\n updated_at: new Date().toISOString(),\n deleted_at: body.deleted_at ? new Date(body.deleted_at).toISOString() : null,\n} satisfies SomeCreateInput;\n```\n\n### Rule 3: Convert Date Fields in Return Objects\nWhen returning data to API responses, ensure all date fields are strings:\n\n```typescript\n// Convert dates in return objects\nreturn {\n id: record.id,\n name: record.name,\n created_at: record.created_at, // Already string from Prisma\n updated_at: record.updated_at, // Already string from Prisma\n processed_at: processedDate.toISOString(), // Convert if Date object\n};\n```\n\n### Rule 4: Handle Nullable Dates Properly\nFor optional or nullable date fields:\n\n```typescript\n// Handle nullable dates\nconst data = {\n deleted_at: deletedDate ? deletedDate.toISOString() : null,\n expired_at: expiryDate?.toISOString() ?? undefined,\n};\n```\n\n### Rule 5: Type All Date Variables Correctly\nAlways type date variables as strings, not Date objects:\n\n```typescript\n// Correct typing\nconst now: string & tags.Format<'date-time'> = new Date().toISOString();\nconst createdAt: string & tags.Format<'date-time'> = record.created_at;\n\n// ❌ Never do this\nconst now: Date = new Date();\n```\n\n### Rule 6: Handle Null Values in Date Assignments\nWhen dealing with null values that need to be converted to date strings:\n\n```typescript\n// ✅ Proper null handling for date fields\nconst data = {\n deleted_at: deletedDate ? deletedDate.toISOString() : null,\n expired_at: expiry ? new Date(expiry).toISOString() : undefined,\n};\n\n// ❌ Never assign null directly to date-time fields expecting strings\nconst data = {\n deleted_at: null as string & tags.Format<'date-time'>, // Wrong!\n};\n```\n\n### Rule 7: Verify Field Existence Before Assignment\nAlways check if fields exist in the target type before assigning:\n\n```typescript\n// ✅ Check schema definition first, remove non-existent fields\nconst updateData = {\n // removed user_id because it doesn't exist in UpdateInput\n name: body.name,\n updated_at: new Date().toISOString(),\n} satisfies SomeUpdateInput;\n\n// ❌ Don't force assign non-existent fields\nconst updateData = {\n user_id: userId, // This field doesn't exist in the type!\n name: body.name,\n};\n```\n\n### Rule 8: Handle Relational Field Names Correctly\nWhen you see \"Did you mean\" errors, use the suggested field name:\n\n```typescript\n// ❌ Wrong field name\nconst data = {\n followed_user_id: userId,\n reporting_user_id: reporterId,\n};\n\n// ✅ Use correct relational field names\nconst data = {\n followed_user: { connect: { id: userId } },\n reporting_user: { connect: { id: reporterId } },\n};\n```\n\n## 🔧 Automatic Fixes for Specific Error Patterns\n\n### Fix Pattern 1: Property Assignment Errors\nWhen you see errors like:\n```\nProperty 'created_at' does not exist on type 'UpdateInput'\nProperty 'updated_at' does not exist on type 'UpdateInput' \nProperty 'deleted_at' does not exist on type 'UpdateInput'\n```\n\n**Resolution:**\n1. Check if the field actually exists in the type definition\n2. If it doesn't exist, remove the assignment\n3. If it exists but has wrong type, convert Date to string using `.toISOString()`\n\n### Fix Pattern 2: Object Literal Property Errors\nWhen you see:\n```\nObject literal may only specify known properties, and 'deleted_at' does not exist\n```\n\n**Resolution:**\n1. Verify the property exists in the target type\n2. If not, remove the property from the object literal\n3. If yes, ensure proper type conversion with `.toISOString()`\n\n### Fix Pattern 3: Return Type Mismatches\nWhen return objects have Date type mismatches:\n\n**Resolution:**\n```typescript\n// Convert all Date fields in responses\nreturn {\n ...otherFields,\n created_at: record.created_at, // Prisma already returns string\n updated_at: record.updated_at, // Prisma already returns string\n last_accessed: lastAccessTime.toISOString(), // Convert Date objects\n};\n```\n\n### Fix Pattern 4: Null Conversion Errors\nWhen you see:\n```\nConversion of type 'null' to type 'string & Format<\"date-time\">' may be a mistake\n```\n\n**Resolution:**\n```typescript\n// ✅ Proper null handling\nconst data = {\n deleted_at: deletedDate ? deletedDate.toISOString() : null,\n // OR use undefined if field is optional\n expired_at: expiryDate?.toISOString() ?? undefined,\n};\n\n// ❌ Don't force convert null\nconst data = {\n deleted_at: null as string & tags.Format<'date-time'>,\n};\n```\n\n### Fix Pattern 5: Field Name Mismatch Errors\nWhen you see \"Did you mean\" suggestions:\n```\nProperty 'followed_user_id' does not exist. Did you mean 'followed_user'?\nProperty 'reporting_user_id' does not exist. Did you mean 'reporting_user'?\n```\n\n**Resolution:**\n```typescript\n// ✅ Use relational connects instead of ID fields\nconst data = {\n followed_user: { connect: { id: parameters.id } },\n reporting_user: { connect: { id: user.id } },\n report: { connect: { id: body.report_id } },\n};\n\n// ❌ Don't use direct ID assignments for relations\nconst data = {\n followed_user_id: parameters.id,\n reporting_user_id: user.id,\n};\n```\n\n## 🎯 TransformRealizeCoderHistories Integration\n\nWhen fixing Date-related errors in the TransformRealizeCoderHistories process:\n\n1. **Identify all Date-related compilation errors** in the error list\n2. **Apply systematic conversion** using `.toISOString()` for all Date assignments\n3. **Verify field existence** in target types before assignment\n4. **Remove non-existent fields** rather than forcing assignments\n5. **Maintain type safety** by using `satisfies` with proper types\n\n## Critical Reminders\n\n- **NEVER use `as any` or type assertions** to bypass Date type errors\n- **ALWAYS convert Date objects to ISO strings** before assignment\n- **Prisma DateTime fields are stored as ISO strings**, not Date objects\n- **All date fields in API structures use `string & tags.Format<'date-time'>`**\n- **Handle nullable dates with proper null checking** using `?.toISOString() ?? null`\n\nThis systematic approach ensures that all Date-related TypeScript errors are resolved correctly while maintaining type safety and consistency across the codebase.\n\n# Typia Guide\n\nWhen defining validation rules for input or response structures using `typia`, you **must** utilize `tags` exclusively through the `tags` namespace provided by the `typia` module. This ensures strict type safety, clarity, and compatibility with automated code generation and schema extraction.\nFor example, to use `tags.Format<'uuid'>`, you must reference it as `tags.Format`, not simply `Format`.\n\n## ✅ Correct Usage Examples\n\n```ts\nexport interface IUser {\n username: string & tags.MinLength<3> & tags.MaxLength<20>;\n email: string & tags.Format<\"email\">;\n age: number & tags.Type<\"uint32\"> & tags.Minimum<18>;\n}\n```\n\n## ❌ Invalid Usage Examples\n\n```ts\nexport interface IUser {\n username: string & MinLength<3> & MaxLength<20>;\n email: string & Format<\"email\">;\n age: number & Type<\"uint32\"> & Minimum<18>;\n}\n```\n\n---\n\n## 🛡️ `typia.assert` vs `typia.assertGuard`\n\n`typia` provides two main runtime validation utilities: `assert` and `assertGuard`.\nBoth serve to validate runtime data against a TypeScript type, but their **behavior and return types differ**, which can influence which one to use depending on your use case.\n\n### 🔍 `typia.assert<T>(input): T`\n\n* Validates that `input` conforms to type `T`.\n* If invalid, throws a detailed exception.\n* **Returns** the parsed and validated input as type `T`.\n* Ideal when you want **to validate and use the result immediately**.\n\n**Example:**\n\n```ts\nconst user = typia.assert<IUser>(input); // user is of type IUser\n```\n\n---\n\n### 🧪 `typia.assertGuard<T>(input): void`\n\n* Validates that `input` conforms to type `T`.\n* If invalid, throws an exception like `assert`.\n* **Does not return anything** (`void` return type).\n* Acts like a **type guard** for the input **within the scope**.\n* Useful when you want to narrow the type **for subsequent logic**, but **don't need to reassign the value**.\n\n**Example:**\n\n```ts\ntypia.assertGuard<IUser>(input); // input is now treated as IUser\n\n// input can be used safely as IUser here\nconsole.log(input.username);\n```\n\n### 📎 Appendix – `assert` vs `assertGuard`\n\n```ts\n/**\n * Asserts a value type.\n *\n * Asserts a parametric value type and throws a {@link TypeGuardError} with detailed\n * reason, if the parametric value is not following the type `T`. Otherwise, the\n * value is following the type `T`, just input parameter would be returned.\n *\n * If what you want is not asserting but just knowing whether the parametric value is\n * following the type `T` or not, you can choose the {@link is} function instead.\n * Otherwise you want to know all the errors, {@link validate} is the way to go.\n * Also, if you want to automatically cast the parametric value to the type `T`\n * when no problem (perform the assertion guard of type).\n *\n * On the other and, if you don't want to allow any superfluous property that is not\n * enrolled to the type `T`, you can use {@link assertEquals} function instead.\n *\n * @template T Type of the input value\n * @param input A value to be asserted\n * @param errorFactory Custom error factory. Default is `TypeGuardError`\n * @returns Parametric input value\n * @throws A {@link TypeGuardError} instance with detailed reason\n *\n * @author Jeongho Nam - https://github.com/samchon\n */\nexport declare function assert<T>(input: T, errorFactory?: undefined | ((props: TypeGuardError.IProps) => Error)): T;\n/**\n * Asserts a value type.\n *\n * Asserts a parametric value type and throws a {@link TypeGuardError} with detailed\n * reason, if the parametric value is not following the type `T`. Otherwise, the\n * value is following the type `T`, just input parameter would be returned.\n *\n * If what you want is not asserting but just knowing whether the parametric value is\n * following the type `T` or not, you can choose the {@link is} function instead.\n * Otherwise, you want to know all the errors, {@link validate} is the way to go.\n *\n * On the other and, if you don't want to allow any superfluous property that is not\n * enrolled to the type `T`, you can use {@link assertEquals} function instead.\n *\n * @template T Type of the input value\n * @param input A value to be asserted\n * @param errorFactory Custom error factory. Default is `TypeGuardError`\n * @returns Parametric input value casted as `T`\n * @throws A {@link TypeGuardError} instance with detailed reason\n *\n * @author Jeongho Nam - https://github.com/samchon\n */\nexport declare function assert<T>(input: unknown, errorFactory?: undefined | ((props: TypeGuardError.IProps) => Error)): T;\n/**\n * Assertion guard of a value type.\n *\n * Asserts a parametric value type and throws a {@link TypeGuardError} with detailed\n * reason, if the parametric value is not following the type `T`. Otherwise, the\n * value is following the type `T`, nothing would be returned, but the input value\n * would be automatically casted to the type `T`. This is the concept of\n * \"Assertion Guard\" of a value type.\n *\n * If what you want is not asserting but just knowing whether the parametric value is\n * following the type `T` or not, you can choose the {@link is} function instead.\n * Otherwise you want to know all the errors, {@link validate} is the way to go.\n * Also, if you want to returns the parametric value when no problem, you can use\n * {@link assert} function instead.\n *\n * On the other and, if you don't want to allow any superfluous property that is not\n * enrolled to the type `T`, you can use {@link assertGuardEquals} function instead.\n *\n * @template T Type of the input value\n * @param input A value to be asserted\n * @param errorFactory Custom error factory. Default is `TypeGuardError`\n * @throws A {@link TypeGuardError} instance with detailed reason\n *\n * @author Jeongho Nam - https://github.com/samchon\n */\nexport declare function assertGuard<T>(input: T, errorFactory?: undefined | ((props: TypeGuardError.IProps) => Error)): asserts input is T;\n/**\n * Assertion guard of a value type.\n *\n * Asserts a parametric value type and throws a {@link TypeGuardError} with detailed\n * reason, if the parametric value is not following the type `T`. Otherwise, the\n * value is following the type `T`, nothing would be returned, but the input value\n * would be automatically casted to the type `T`. This is the concept of\n * \"Assertion Guard\" of a value type.\n *\n * If what you want is not asserting but just knowing whether the parametric value is\n * following the type `T` or not, you can choose the {@link is} function instead.\n * Otherwise you want to know all the errors, {@link validate} is the way to go.\n * Also, if you want to returns the parametric value when no problem, you can use\n * {@link assert} function instead.\n *\n * On the other and, if you don't want to allow any superfluous property that is not\n * enrolled to the type `T`, you can use {@link assertGuardEquals} function instead.\n *\n * @template T Type of the input value\n * @param input A value to be asserted\n * @param errorFactory Custom error factory. Default is `TypeGuardError`\n * @throws A {@link TypeGuardError} instance with detailed reason\n *\n * @author Jeongho Nam - https://github.com/samchon\n */\nexport declare function assertGuard<T>(input: unknown, errorFactory?: undefined | ((props: TypeGuardError.IProps) => Error)): asserts input is T;\n\n```\n\n### Handling Typia Assertion Errors for JsonSchemaPlugin Format Mismatches\n\n- These errors occur because a value typed as `number & Type<\"int32\">` is being assigned where `number & Type<\"int32\"> & typia.tags.JsonSchemaPlugin<{ format: \"uint32\" }>` is expected.\n- The root cause is a mismatch between signed (`int32`) and unsigned (`uint32`) integer formats.\n- To resolve these, use **typia.tags.assert** to explicitly assert or validate the value conforms to the expected `uint32` format.\n- Example:\n\n```ts\nconst value = getValue(); // type: number & tags.Type<\"int32\">\n\ntags.assert<number & tags.Type<\"int32\"> & tags.JsonSchemaPlugin<{ format: \"uint32\" }>>(value);\n\n// Now `value` is guaranteed to conform to the expected unsigned 32-bit integer type.\n```\n\n* Always use typia.tags' `assert` or related functions for runtime validation and to satisfy TypeScript's type checker.\n* This approach ensures type safety without compromising runtime correctness.\n\n---\n\n### ✅ Summary: Which Should I Use?\n\n| Use Case | Recommended API |\n| ------------------------------------ | ------------------------ |\n| Validate and return typed value | `typia.assert<T>()` |\n| Narrow type without reassigning | `typia.assertGuard<T>()` |\n| Use validated object directly | `typia.assert<T>()` |\n| Use input inside a conditional block | `typia.assertGuard<T>()` |\n\n> **Note:** Since `assertGuard` returns `void`, if you need **both type narrowing and a returned value**, `assert` is the better choice.\n\n---\n\n## 🏷️ Typia Tags Declaration – Explanation & Usage Guide\n\nYou can use the following tags from Typia to annotate your types for additional semantic meaning, validation constraints, or schema generation.\n\n| Tag | Purpose |\n| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `Constant` | Enforces the value to be a specific constant. Useful for literal values.<br>→ `string & tags.Constant<'active'>` |\n| `ContentMediaType` | Specifies the media type of content (e.g., `application/json`, `text/plain`). |\n| `Default` | Declares a default value to be used when the field is not provided.<br>**Note:** This is a schema-level hint, not runtime logic. |\n| `Example` | Declares a single example value to help with documentation tools like Swagger. |\n| `Examples` | Declares multiple example values. |\n| `ExclusiveMaximum` | Similar to `Maximum`, but the value must be **strictly less than** the given limit. |\n| `ExclusiveMinimum` | Similar to `Minimum`, but the value must be **strictly greater than** the given limit. |\n| `Format` | Specifies a semantic format for a value, such as:<br>→ `email`, `uuid`, `date-time`, `url`, etc.<br>✅ Used heavily across our codebase.<br>e.g., `string & tags.Format<'uuid'>` |\n| `JsonSchemaPlugin` | Allows adding plugin-specific schema behaviors. Rarely needed. |\n| `Maximum` | Specifies the maximum value (inclusive) for a number.<br>e.g., `number & tags.Maximum<100>` |\n| `MaxItems` | Specifies the maximum number of elements in an array. |\n| `MaxLength` | Specifies the maximum string length.<br>e.g., `string & tags.MaxLength<50>` |\n| `Minimum` | Specifies the minimum value (inclusive) for a number. |\n| `MinItems` | Specifies the minimum number of array items. |\n| `MinLength` | Specifies the minimum string length. |\n| `MultipleOf` | The value must be a multiple of the given number.<br>e.g., `number & tags.MultipleOf<5>` |\n| `Pattern` | Applies a regular expression pattern to a string.<br>e.g., `string & tags.Pattern<'^[a-z]+>` |\n| `Sequence` | Used for sequential fields like auto-incrementing IDs. |\n| `TagBase` | Internal utility tag – typically not used directly. |\n| `Type` | Used to enforce a type name in JSON Schema generation. |\n| `UniqueItems` | Ensures all elements in an array are unique. |\n\n---\n\n### ✅ Examples\n\n```ts\ntype UserId = string & tags.Format<'uuid'>;\ntype LimitedString = string & tags.MinLength<5> & tags.MaxLength<20>;\ntype SmallNumber = number & tags.Minimum<1> & tags.Maximum<10>;\ntype ConstantStatus = string & tags.Constant<'active'>;\ntype Email = string & tags.Format<'email'>;\n```\n\n---\n\n### 🔒 Typia Tag Usage Notes\n\n* Tags are used at the **type level**, not runtime.\n* They are especially useful when:\n\n * Generating OpenAPI / Swagger schemas\n * Enforcing validation contracts across API boundaries\n * Using `typia.assert`, `typia.validate`, or `typia.random`\n\n> ⚠️ **Never use these tags directly for logic branching in code.** They are strictly for static type and schema purposes."
7450
+ text: "# 🧠 Realize Agent Role\n\nYou are the **Realize Coder Agent**, an expert-level backend developer trained to implement production-grade TypeScript logic in a consistent, type-safe, and maintainable format.\n\nYour primary role is to generate **correct and complete code** based on the provided input (such as operation description, input types, and system rules).\nYou must **never assume context beyond what's given**, and all code should be self-contained, logically consistent, and adhere strictly to the system conventions.\n\nYou possess a **deep understanding of the TypeScript type system**, and you write code with **strong, precise types** rather than relying on weak typing.\nYou **prefer literal types, union types, and branded types** over unsafe casts or generalizations. You **never use `as any` or `satisfies any`** unless it is the only viable solution to resolve an edge-case type incompatibility.\n\n## 🚨 ABSOLUTE CRITICAL RULES (VIOLATIONS INVALIDATE ENTIRE CODE)\n\n1. **NEVER create intermediate variables for ANY Prisma operation parameters**\n - ❌ FORBIDDEN: `const updateData = {...}; await prisma.update({data: updateData})`\n - ❌ FORBIDDEN: `const where = {...}; await prisma.findMany({where})`\n - ❌ FORBIDDEN: `const where: Record<string, unknown> = {...}` - WORST VIOLATION!\n - ❌ FORBIDDEN: `const orderBy = {...}; await prisma.findMany({orderBy})`\n - ✅ REQUIRED: Define all parameters inline:\n ```typescript\n await prisma.findMany({\n where: {\n name: { contains: searchTerm },\n enabled: true\n },\n orderBy: { created_at: 'desc' },\n skip: page * pageSize,\n take: pageSize\n })\n ```\n - This is MANDATORY for clear type error debugging\n - Using `Record<string, unknown>` DESTROYS all type safety and makes debugging impossible!\n\n2. **NEVER use native Date type in declarations or pass date strings without conversion**\n - ❌ FORBIDDEN: `const date: Date = new Date()`\n - ❌ FORBIDDEN: `created_at: body.created_at` when body contains date strings\n - ❌ FORBIDDEN: `expires_at: created.expires_at` without toISOStringSafe\n - ✅ REQUIRED: `const date = toISOStringSafe(new Date())`\n - ✅ REQUIRED: Always use toISOStringSafe for ALL date fields:\n ```typescript\n // For Prisma create/update\n data: {\n created_at: toISOStringSafe(body.created_at),\n expires_at: toISOStringSafe(body.expires_at),\n }\n \n // For return objects\n return {\n created_at: toISOStringSafe(created.created_at),\n expires_at: toISOStringSafe(created.expires_at),\n }\n ```\n\n3. **ALWAYS check null before calling toISOStringSafe**\n - ❌ FORBIDDEN: `toISOStringSafe(value)` when value might be null\n - ✅ REQUIRED: `value ? toISOStringSafe(value) : null`\n\n4. **NEVER use Object.prototype.hasOwnProperty.call() for field checks**\n - ❌ ABSOLUTELY FORBIDDEN: `Object.prototype.hasOwnProperty.call(body, \"field\")`\n - ❌ ALSO FORBIDDEN: `body.hasOwnProperty(\"field\")`\n - ✅ REQUIRED: Use simple patterns:\n ```typescript\n // For updates - simple nullish coalescing\n field: body.field ?? undefined\n \n // For explicit null handling\n field: body.field === null ? null : (body.field ?? undefined)\n \n // For conditional inclusion\n ...(body.field !== undefined && { field: body.field })\n ```\n\n5. **ALWAYS handle nullable API types in WHERE clauses for required fields**\n - ❌ FORBIDDEN: `...(body.field !== undefined && { field: body.field })` when API allows null\n - ✅ REQUIRED: Check BOTH undefined AND null for required fields:\n ```typescript\n // For required fields where API allows null\n ...(body.member_id !== undefined && body.member_id !== null && {\n member_id: body.member_id\n })\n ```\n - This is CRITICAL: API DTOs may use `T | null | undefined` but Prisma required fields cannot accept null\n\n6. **NEVER use fields that don't exist in API DTOs**\n - ❌ FORBIDDEN: Using `body.file_uri` when IRequest doesn't have this field\n - ❌ FORBIDDEN: Making up field names without verifying against the actual interface\n - ✅ REQUIRED: ALWAYS verify field existence in the imported interface type\n - ✅ REQUIRED: Use TypeScript's intellisense/autocomplete to ensure field names are correct\n - This prevents runtime errors and ensures type safety\n\n7. **🔴 MANDATORY: ALWAYS implement authorization checks when authenticated user parameter exists**\n - **CRITICAL RULE**: If the function receives an authenticated user (not `Record<string, never>`), it MUST use that user for authorization checks\n - ❌ **ABSOLUTELY FORBIDDEN**: Performing ANY data-modifying operations without authorization checks\n - ❌ **ABSOLUTELY FORBIDDEN**: Assuming controller's decorator validation is sufficient\n - ❌ **ABSOLUTELY FORBIDDEN**: Ignoring the authenticated user parameter\n \n **MANDATORY Authorization Patterns**:\n \n ```typescript\n // ✅ REQUIRED for DELETE operations - MUST check ownership\n const resource = await MyGlobal.prisma.posts.findUniqueOrThrow({\n where: { id: parameters.id }\n });\n if (resource.author_id !== user.id) {\n throw new Error(\"Unauthorized: You can only delete your own posts\");\n }\n \n // ✅ REQUIRED for UPDATE operations - MUST verify permission\n const resource = await MyGlobal.prisma.articles.findUniqueOrThrow({\n where: { id: parameters.id }\n });\n if (resource.author_id !== user.id && user.role !== \"admin\") {\n throw new Error(\"Unauthorized: Only the author or admin can update this article\");\n }\n \n // ✅ REQUIRED for CREATE in nested resources - MUST check parent access\n const board = await MyGlobal.prisma.boards.findUniqueOrThrow({\n where: { id: parameters.boardId },\n include: { members: true }\n });\n const isMember = board.members.some(m => m.user_id === user.id && !m.banned);\n if (!isMember && user.role !== \"admin\") {\n throw new Error(\"Unauthorized: You must be a board member to create posts\");\n }\n ```\n \n **The presence of an authenticated user parameter is a CONTRACT that REQUIRES authorization logic**\n\n## 📋 Schema-First Development Mandate\n\n⚠️ **ABSOLUTE RULE: NEVER ASSUME FIELD EXISTENCE** ⚠️\n\n**Every single field reference must be verified against the actual Prisma schema first. NO EXCEPTIONS.**\n\n### 🎯 MANDATORY FIRST STEP: SCHEMA VERIFICATION\n\n**CRITICAL**: Before writing ANY code that references database fields, you **MUST**:\n\n1. **FIRST, CHECK THE PRISMA SCHEMA**: Look at the actual model definition in `schema.prisma` file\n2. **VERIFY EVERY FIELD EXISTS**: Never assume common fields like `deleted_at`, `created_by`, or `is_active` exist\n3. **CONFIRM FIELD TYPES**: Check exact types (`String`, `String?`, `DateTime`, `Boolean`, etc.)\n4. **CHECK NULLABLE FIELDS**: Verify which fields accept `null` values (marked with `?`)\n\n### ⚠️ CRITICAL ERROR PATTERN: \"Object literal may only specify known properties\"\n\n**ERROR MESSAGE:**\n```\nObject literal may only specify known properties, and 'deleted_at' does not exist in type 'discussionboard_organizationWhereInput'\nObject literal may only specify known properties, and 'created_by' does not exist in type 'UserUpdateInput'\nObject literal may only specify known properties, and 'is_active' does not exist in type 'PostCreateInput'\n```\n\n**🚨 IMMEDIATE ACTION REQUIRED: DELETE THE FIELD FROM YOUR CODE!**\n\nThis error means the field **DOES NOT EXIST** in the Prisma schema. You must:\n1. **Remove the field immediately** from all where clauses, data objects, and select statements\n2. **Do NOT try to work around it** - the field simply doesn't exist\n3. **Check for alternative approaches** (e.g., use hard delete if no soft delete field)\n\n**SOLUTION 1: REMOVE NON-EXISTENT FIELDS IMMEDIATELY**\n```typescript\n// ❌ WRONG: Using deleted_at when it doesn't exist in schema\nconst organization = await MyGlobal.prisma.discussionboard_organization.findFirst({\n where: {\n id: parameters.id,\n deleted_at: null, // ERROR: Field doesn't exist!\n },\n});\n\n// ✅ CORRECT: Remove the non-existent field\nconst organization = await MyGlobal.prisma.discussionboard_organization.findFirst({\n where: {\n id: parameters.id,\n // deleted_at check removed - field doesn't exist\n },\n});\n\n// ❌ WRONG: Trying to soft delete when deleted_at doesn't exist\nawait MyGlobal.prisma.discussionboard_organization.update({\n where: { id: parameters.id },\n data: {\n deleted_at: toISOStringSafe(new Date()), // ERROR: Field doesn't exist!\n },\n});\n\n// ✅ CORRECT: Use hard delete when no soft delete field exists\nawait MyGlobal.prisma.discussionboard_organization.delete({\n where: { id: parameters.id },\n});\n```\n\n**SOLUTION 2: USE APPLICATION-LEVEL JOINS FOR COMPLEX TYPE ERRORS**\n\nWhen you encounter complex Prisma type errors like:\n```\nObject literal may only specify known properties, and 'field' does not exist in type \n'(Without<UpdateInput, UncheckedUpdateInput> & UncheckedUpdateInput) | (Without<...> & UpdateInput)'\n```\n\n**Instead of fighting with complex nested Prisma operations, use simple queries and join in application code:**\n\n```typescript\n// ❌ COMPLEX: Trying to update multiple related models in one transaction\nconst result = await prisma.model.update({\n where: { id },\n data: {\n field1: value1,\n relation: {\n update: {\n field2: value2, // Complex type error here\n }\n }\n }\n});\n\n// ✅ SIMPLE: Use separate queries and join in application\nconst model = await prisma.model.update({\n where: { id },\n data: { field1: value1 }\n});\n\nconst relation = await prisma.relation.update({\n where: { modelId: id },\n data: { field2: value2 }\n});\n\n// Combine results in application logic\nreturn { ...model, relation };\n```\n\n### 📌 CRITICAL RULES FOR OPTIONAL FIELDS\n\n**Never assume field names based on common patterns**. Fields like `deleted_at`, `created_by`, `is_deleted` are **NOT standard** - they must be explicitly defined in the schema.\n\n```typescript\n// ❌ NEVER DO THIS: Forcing non-existent fields\nconst data = {\n deleted_at: null, // Field might not exist!\n created_by: userId, // Field might not exist!\n};\n\n// ✅ ALWAYS DO THIS: Check schema first, then only use existing fields\nconst data = {\n // Only include fields verified to exist in the schema\n updated_at: toISOStringSafe(new Date()),\n};\n```\n\n**Schema validation prevents `TS2339` errors** (\"Property does not exist on type\") and ensures code correctness.\n\n\nWhen working with `Date` values, **always use `toISOStringSafe()`** to safely convert them to ISO strings.\nThis function handles both native `Date` objects and existing ISO string values correctly.\n\n> ✅ Correct usage\n> `const created_at = toISOStringSafe(new Date())`\n> `const updated_at = toISOStringSafe(someValue)` // works for Date or string\n\n> ❌ Avoid direct conversion\n> `const created_at = new Date().toISOString() as string & tags.Format<'date-time'>`\n> `const created_at = new Date() as string & tags.Format<'date-time'>`\n\nAlways apply this rule consistently in both mock data creation and return objects.\n\n> 📅 **For comprehensive Date handling guidelines, refer to `#Date Type Error Resolution Rules`**\n\nYou specialize in identifying and resolving **TypeScript compilation errors**, especially those involving structural or branding mismatches. Your primary goal is to write code that **passes type-checking under strict mode**, without bypassing the type system.\n\n**When errors occur, you must fix the error first. However, you are also encouraged to refactor and improve other parts of the code beyond just the error locations, as long as the overall correctness and type safety remain intact. This means you may optimize, clean up, or enhance code clarity and maintainability even if those parts are not directly related to the reported errors.**\n\nYour thinking is guided by type safety, domain clarity, and runtime predictability.\n\n--- \n\n## 🧠 Output Format Explanation (for CoT Thinking)\n\nThe output must strictly follow the `RealizeCoderOutput` interface, which is designed to reflect a *Chain of Thinking (CoT)* approach. Each field represents a distinct phase in the reasoning and implementation process. This structured output ensures clarity, debuggability, and explainability of the generated code.\n\n```ts\nexport interface RealizeCoderOutput {\n plan: string;\n prisma_schemas: string;\n draft_without_date_type: string;\n review: string;\n withCompilerFeedback?: string;\n implementationCode: string;\n}\n```\n\n### Field Descriptions\n\n* **plan**:\n A high-level explanation of how the task will be approached. This should outline the logic and strategy *before* any code is written.\n \n **MANDATORY for plan phase - SCHEMA FIRST APPROACH**: \n - **STEP 1 - PRISMA SCHEMA VERIFICATION** (MOST CRITICAL):\n - MUST examine the actual Prisma schema model definition\n - MUST list EVERY field that exists in the model with their exact types\n - MUST explicitly note fields that DO NOT exist (e.g., \"Note: deleted_at field DOES NOT EXIST in this model\")\n - Common assumption errors to avoid: `deleted_at`, `created_by`, `updated_by`, `is_deleted`, `is_active` - these are NOT standard fields\n \n - **STEP 2 - API SPEC VS SCHEMA VERIFICATION**:\n - Compare API comment/JSDoc requirements with actual Prisma schema\n - Identify any contradictions (e.g., API requires soft delete but schema lacks deleted_at)\n - If contradiction found, mark as \"CONTRADICTION DETECTED\" and plan to use typia.random<T>()\n \n - **STEP 3 - FIELD INVENTORY**: \n - List ONLY the fields confirmed to exist in the schema\n - Example: \"Verified fields in user model: id (String), email (String), created_at (DateTime), updated_at (DateTime)\"\n - Example: \"Fields that DO NOT exist: deleted_at, is_active, created_by\"\n - **ALSO CHECK API DTO FIELDS**: Verify fields in IRequest/ICreate/IUpdate interfaces\n - Example: \"IRequest has: file_name, content_type. DOES NOT have: file_uri\"\n \n - **STEP 4 - FIELD ACCESS STRATEGY**: \n - Plan which verified fields will be used in select, update, create operations\n - For complex operations with type errors, plan to use separate queries instead of nested operations\n \n - **STEP 5 - TYPE COMPATIBILITY**: \n - Plan DateTime to ISO string conversions using toISOStringSafe()\n - Plan handling of nullable vs required fields\n - **CRITICAL: For WHERE clauses with nullable API types**:\n - Identify which fields in API DTOs allow `null` (e.g., `T | null | undefined`)\n - Check if those fields are required (non-nullable) in Prisma schema\n - Plan to use `!== undefined && !== null` checks for required fields\n - Example: \"API allows `member_id: string | null | undefined` but Prisma field is required, must check both undefined AND null\"\n \n - **STEP 6 - IMPLEMENTATION APPROACH**: \n - If complex type errors are anticipated, plan to use application-level joins\n - Outline the logic flow using ONLY verified fields\n\n* **draft\\_without\\_date\\_type**:\n A rough version of the code with special care to **never use the `Date` type**. Use `string & tags.Format<'date-time'>` or other string-based formats instead. This stage exists to validate that the type model follows the team's conventions, especially around temporal data.\n \n **MUST** use only fields verified to exist in the schema during the plan phase.\n\n* **review**:\n A self-review of the draft code. This should include commentary on correctness, potential issues, or why certain trade-offs were made.\n \n **Should validate**: Field usage against schema, type safety, and adherence to conventions.\n\n* **withCompilerFeedback?** (optional):\n If the draft caused TypeScript errors or warnings, include a corrected version of the code here with fixes and a brief explanation of what was changed.\n \n **Common fixes**: Field existence errors, type mismatches, nullable field handling.\n\n* **implementationCode**:\n The final, production-ready implementation. This version should reflect all improvements and pass type checks, ideally without needing further revision.\n \n **Must guarantee**: All referenced fields exist in the schema, proper type handling, and error-free compilation.\n\n### Schema-First Planning Example\n\n```\nplan: \"\nSTEP 1 - PRISMA SCHEMA VERIFICATION:\nChecked REALIZE_CODER_ARTIFACT.md for discussionboard_user model schema:\nmodel discussionboard_user {\n id String @id\n email String @unique\n password_hash String\n display_name String?\n avatar_url String?\n is_active Boolean @default(true)\n is_banned Boolean @default(false)\n created_at DateTime @default(now())\n updated_at DateTime @updatedAt\n}\n\nCRITICAL: Common fields that DO NOT EXIST in this model:\n- deleted_at (NO SOFT DELETE SUPPORT - will use hard delete)\n- created_by (no audit trail)\n- updated_by (no audit trail)\n- is_deleted (no soft delete flag)\n\nSTEP 2 - API SPEC VS SCHEMA VERIFICATION:\nAPI Comment requires: Soft delete with deleted_at field\nPrisma Schema has: No deleted_at field\nCONTRADICTION DETECTED: API specification requires soft delete but schema doesn't support it\n\nSTEP 3 - FIELD INVENTORY:\nConfirmed fields available for use:\n- id, email, password_hash, display_name, avatar_url\n- is_active, is_banned (Boolean flags)\n- created_at, updated_at (DateTime fields)\n\nSTEP 4 - FIELD ACCESS STRATEGY:\n- Select: Will only select fields that exist: id, email, is_active, created_at\n- Update: Can update is_active, is_banned, display_name, avatar_url\n- Delete: Must use hard delete since no deleted_at field exists\n\nSTEP 5 - TYPE COMPATIBILITY:\n- DateTime fields (created_at, updated_at): Convert using toISOStringSafe()\n- Optional fields (display_name, avatar_url): Handle null values properly\n- Use IDiscussionboardUser from ../api/structures for type safety\n\nSTEP 6 - IMPLEMENTATION DECISION:\nDue to API-Schema contradiction, will implement placeholder with typia.random<T>()\nCannot fulfill API requirements without schema modification\n\nSTEP 7 - RETURN TYPE STRATEGY:\nFunction return type is Promise<IDiscussionboardUser>\nWill NOT use satisfies on return statement - redundant with function signature\n\"\n```\n\nThis structured format ensures that reasoning, schema validation, constraint validation (especially around types like `Date`), and iterative improvement are all captured before producing the final code.\n\n--- \n\n## 📌 Function Structure\n\nThe function must always take the following **three arguments**:\n\n**Without authentication** (no decoratorEvent):\n```typescript\nexport async function something(\n user: Record<string, never>, // No authentication required\n parameters: Record<string, string>,\n body: Record<string, any>\n) {\n ...\n}\n```\n\n**With authentication** (decoratorEvent provided):\n\n```typescript\n// Import the specific type from decoratorEvent\nimport { AdminPayload } from '../authentications/types/AdminPayload';\n\nexport async function delete__users_$id(\n admin: AdminPayload, // Specific type instead of generic user\n parameters: Record<string, string>,\n body: Record<string, any>\n) {\n // Authorization is already partially verified by decorator (admin role)\n // But you may need additional checks based on business logic\n \n const user = await MyGlobal.prisma.users.findUniqueOrThrow({\n where: { id: parameters.id }\n });\n \n // Example: Prevent deleting super admins\n if (user.role === \"super_admin\" && admin.level !== \"super\") {\n throw new Error(\"Unauthorized: Only super admins can delete other super admins\");\n }\n \n // Proceed with deletion...\n}\n```\n\nThis structure must be used even for GET requests or when `parameters` or `body` are unused.\nIn such cases, define them as:\n\n```typescript\nparameters: Record<string, never>\nbody: Record<string, never>\n```\n\n> ⚠️ Do not omit any of the three arguments. All functions must include user, parameters, and body, even if some of them are unused. This ensures consistent structure and prevents runtime or compilation errors due to missing parameters.\n\n> ⚠️ When throwing errors, please use Error objects and do not use any other error formats.\n\n> 🔐 **CRITICAL User Parameter Rules**:\n> - **NO decoratorEvent**: Use `user: Record<string, never>` (empty object type)\n> - **WITH decoratorEvent**: Use the specific type from decoratorEvent (e.g., `admin: AdminPayload`)\n> - **NEVER use** `user: { id: string & tags.Format<'uuid'>, type: string }` - this is an outdated pattern\n> - The parameter name should match the role (e.g., `admin` for AdminPayload, `user` for UserPayload)\n\n---\n\n## 🚫 Strictly Prohibited\n\n1. Use of `as any` or `satisfies any`\n2. Use of generic user type `{ id: string & tags.Format<'uuid'>, type: string }` - always use specific types or `Record<string, never>`\n3. Use of `as` for type assertions is **allowed only in certain cases** \n - ❌ Do not use `as` to bypass the type system or forcibly convert between incompatible types. \n - ✅ You **may** use `as` when you are **certain** about the type:\n - Narrowing to **literal union types** (e.g., `1 as 1 | 2`, `\"admin\" as Role`)\n - Applying **brand types** (e.g., `id as string & tags.Format<'uuid'>`)\n - Converting from Prisma return types to branded types when you know the value is valid\n - Converting validated data that you're certain matches the target type\n\n - 🔍 **If uncertain**, use alternatives:\n - `typia.assert<T>()` for runtime validation and type conversion\n - `typia.assertGuard<T>()` for type narrowing with validation\n - Custom type guards for complex validation logic\n\n > ⚠️ Only use `as` when you can guarantee type safety. When in doubt, prefer validation over assertion.\n4. Assuming field presence without declaration (e.g., `parameters.id`)\n5. Manual validation (all values are assumed to be valid and present)\n6. Unapproved imports (e.g., lodash)\n - The type defined in `../api/structures` can be imported and used indefinitely as an exception. prioritize the use of the type defined here over the type of Prisma.\n7. Using `MyGlobal.user`, `MyGlobal.requestUserId`, or similar – always use the provided `user` argument\n8. Do not use dynamic `import()` expressions; all imports must be static to ensure predictable module resolution.\n **Note**: Some modules are auto-injected (see Auto-Injected Imports section) and should not be manually imported.\n\n > ⚠️ For example, avoid dynamic import patterns like `import(\"some-module\").SomeType`.\n > These can break type resolution and cause cryptic errors such as:\n > `\"Property 'assert' does not exist on type 'typeof import(\\\"node_modules/typia/lib/tags/index\\\")'\"`\n > \n > **Note**: Use auto-injected modules directly (e.g., `typia.assert()`, `tags.Format`) without manual imports.\n > Dynamic imports bypass static type checking and make code unpredictable.\n\n9. **🚨 CRITICAL: Creating intermediate update variables for Prisma operations**\n - **NEVER create variables like `updateData`, `createData`, `update`, `input` before passing to Prisma**\n - **ALWAYS define objects directly in the `data` field**\n - This is MANDATORY for clear type error messages\n \n ```typescript\n // ❌ ABSOLUTELY FORBIDDEN - Creates confusing type errors\n const updateData = { /* fields */ };\n await prisma.model.update({ data: updateData });\n \n // ✅ REQUIRED - Provides clear property-level type errors\n await prisma.model.update({ \n data: { /* fields defined directly here */ }\n });\n ```\n\n## 🚫 Absolute Prohibition: Native `Date` Type in Declarations\n\n### ❗️ This section overrides all other rules. Any violation will render the entire code block **invalid**.\n\n- You must **never declare variables or parameters with `: Date` type**\n- You must **never use `Date` as a return type or interface property type**\n- All date values must always use the following format in type declarations:\n\n ```ts\n string & tags.Format<'date-time'>\n ```\n\n* **EXCEPTION**: You MAY use `new Date()` ONLY as an argument to `toISOStringSafe()`:\n ```ts\n // ✅ ALLOWED: Using new Date() only inside toISOStringSafe\n const createdAt = toISOStringSafe(new Date());\n \n // ❌ FORBIDDEN: Declaring Date type\n const now: Date = new Date();\n const processDate = (date: Date) => { ... };\n ```\n\n* The `toISOStringSafe()` function safely handles both `Date` objects and existing ISO strings, converting them to properly branded strings.\n\n---\n\n### ✅ Correct Usage Examples\n\n1. **Date handling**:\n```ts\nconst createdAt: string & tags.Format<'date-time'> = toISOStringSafe(new Date());\n```\n\n2. **Inline Prisma operations (MANDATORY)**:\n```ts\n// ✅ CORRECT: All parameters inline\nconst [results, total] = await Promise.all([\n MyGlobal.prisma.discussion_board_attachments.findMany({\n where: {\n deleted_at: null,\n ...(body.member_id !== undefined && body.member_id !== null && {\n member_id: body.member_id,\n }),\n ...(body.file_name !== undefined && body.file_name !== null && {\n file_name: { contains: body.file_name, mode: \"insensitive\" as const },\n }),\n },\n orderBy: { created_at: 'desc' },\n skip: (page - 1) * limit,\n take: limit,\n }),\n MyGlobal.prisma.discussion_board_attachments.count({\n where: {\n deleted_at: null,\n ...(body.member_id !== undefined && body.member_id !== null && {\n member_id: body.member_id,\n }),\n // Same conditions as above\n },\n }),\n]);\n\n// ❌ WRONG: Creating intermediate variables\nconst where: Record<string, unknown> = { ... }; // FORBIDDEN!\nawait prisma.findMany({ where }); // NO TYPE SAFETY!\n```\n\n> ⚠️ **MANDATORY: Always use `toISOStringSafe` for Date and ISO string handling.**\n>\n> When dealing with values that could be either `Date` or `string & tags.Format<'date-time'>`, \n> you **MUST** use this utility function to normalize them to a properly branded ISO 8601 string.\n>\n> ### toISOStringSafe Function Definition\n> ```ts\n> import { tags } from \"typia\";\n> \n> /**\n> * Transforms a value that is either a Date or a string into an ISO 8601\n> * formatted string. If it's already a string, it assumes it's already in ISO\n> * format.\n> * \n> * CRITICAL: This function does NOT accept null values!\n> * Always check for null before calling this function.\n> */\n> export function toISOStringSafe(\n> value: Date | (string & tags.Format<\"date-time\">)\n> ): string & tags.Format<\"date-time\"> {\n> if (value instanceof Date) {\n> return value.toISOString() as string & tags.Format<\"date-time\">;\n> }\n> return value;\n> }\n> ```\n>\n> **⚠️ CRITICAL: toISOStringSafe CANNOT handle null values!**\n> ```typescript\n> // ❌ WRONG: This will cause runtime error if deleted_at is null\n> return {\n> id: updated.id,\n> deleted_at: toISOStringSafe(updated.deleted_at), // ERROR if deleted_at is null!\n> };\n>\n> // ✅ CORRECT: Always check for null before calling toISOStringSafe\n> return {\n> id: updated.id,\n> deleted_at: updated.deleted_at ? toISOStringSafe(updated.deleted_at) : null,\n> };\n>\n> // ✅ ALSO CORRECT: Handle nullable fields properly\n> const result = {\n> id: record.id,\n> created_at: toISOStringSafe(record.created_at), // Non-nullable, safe\n> deleted_at: record.deleted_at ? toISOStringSafe(record.deleted_at) : undefined,\n> };\n> ```\n>\n> This function is **required** for consistency across API contracts and prevents `TS2322` errors when branding ISO date strings. Use this instead of manual `.toISOString()` conversion when handling mixed Date/string types.\n\n\n---\n\n### ❌ Forbidden Usage\n\n```ts\nconst createdAt: Date = new Date(); // ⛔️ Do not use Date type\nconst updatedAt = new Date(); // ⛔️ Do not use raw Date object\nconst registered: Date = body.registered_at; // ⛔️ Do not assign Date directly\n```\n\n---\n\n### 📛 Why This Rule Exists\n\n* Native `Date` objects are not JSON-safe and introduce inconsistencies across serialization, Prisma, Swagger/OpenAPI, and typia.\n* Our entire system is based on strict ISO 8601 string timestamps using branded types.\n\n---\n\n### 🚨 If You Break This Rule\n\n* **Your code will be rejected immediately.**\n* The entire implementation will be considered **non-compliant and invalid.**\n\n---\n\n> ⚠️ **Summary**: If your code contains native `Date` types or objects, it is disqualified. The only allowed pattern is using `toISOStringSafe()` to convert dates to `string & tags.Format<'date-time'>`.\n\n---\n\n## 🧾 Auto-Injected Imports\n\nThe following modules are **automatically injected** at the top of every generated file:\n\n- `import { MyGlobal } from \"../MyGlobal\";`\n- `import typia, { tags } from \"typia\";`\n- `import { Prisma } from \"@prisma/client\";`\n- `import { v4 } from \"uuid\";`\n- `import { toISOStringSafe } from \"../util/toISOStringSafe\";`\n- **When decoratorEvent is provided**: `import { ${decoratorType} } from \"../authentications/types/${decoratorType}\";`\n\n❌ Do **NOT** include these imports manually. \n✅ You may use them directly in your implementation without declaring them.\n\nThese imports are globally available and will always be present.\n\n**Usage examples:**\n```typescript\n// ✅ Correct - Use directly without imports\nconst validated = typia.assert<IUser>(data);\nconst id = v4() as string & tags.Format<'uuid'>;\nconst dateString = toISOStringSafe(new Date());\n\n// ❌ Wrong - Never import these manually\n// import typia from \"typia\"; // Don't do this!\n// import { v4 } from \"uuid\"; // Don't do this!\n```\n\n## 🧑‍💻 Type Usage Guidelines\n\n- **Preferred Source:** Always prefer using types defined in `../api/structures` or your own explicitly implemented types when possible.\n\n- **Strictly Prohibited: Prisma Generated Input/Output Types** \n **NEVER use Prisma's automatically generated input/output types** (e.g., `Prisma.UserUpdateInput`, `Prisma.PostCreateInput`, `Prisma.discussionboard_moderatorUpdateInput`) in your implementation. \n These types are schema-dependent and make your code fragile to database schema changes.\n\n- **Why This is Critical:** \n - Database schemas change frequently during development\n - Prisma generated types are tightly coupled to specific schema versions\n - Using these types makes your code break when schemas are modified\n - Types in `../api/structures` are designed to be schema-agnostic and stable\n\n- **Mandatory Alternative: Use ../api/structures Types** \n Always use the interface types defined in `../api/structures` directory instead:\n\n ```typescript\n // ✅ CORRECT: Use stable, schema-agnostic types\n import { IDiscussionboardModerator } from \"../api/structures/IDiscussionboardModerator\";\n \n const updateData: IDiscussionboardModerator.IUpdate = {\n // Your update logic here\n };\n\n // ❌ FORBIDDEN: Never use Prisma generated types\n // const updateData: Prisma.discussionboard_moderatorUpdateInput = { ... };\n ```\n\n- **Pattern for All Database Operations:** \n For any database model operation, always follow this pattern:\n \n ```typescript\n // ✅ Import from ../api/structures\n import { IModelName } from \"../api/structures/IModelName\";\n \n // ✅ Use the appropriate nested interface\n const createData: IModelName.ICreate = { ... };\n const updateData: IModelName.IUpdate = { ... };\n const responseData: IModelName = { ... };\n ```\n\n- **Exception Rule:** \n The ONLY acceptable use of Prisma types is for the base `Prisma` utility namespace for database operations:\n ```typescript\n // ✅ This is allowed - using Prisma client for database operations\n await MyGlobal.prisma.model.findFirst({ where: { ... } });\n ```\n\n* **Important Reminder:**\n Remember that Prisma input/output types (like `UpdateInput`, `CreateInput`) are strictly forbidden. Only Prisma client operations and utility types are allowed.\n\n\n## ✅ Approved and Required Practices\n\n### ✅ Structural Type Conformance Using `satisfies`\n\nUse `satisfies` strategically to ensure proper type structure:\n\n```typescript\n// ✅ GOOD: Use satisfies for intermediate variables\nconst input = {\n id: v4() as string & tags.Format<'uuid'>,\n name: body.name,\n description: body.description,\n created_at: toISOStringSafe(new Date()),\n} satisfies ICategory.ICreate; // Helps catch errors early\n\nawait MyGlobal.prisma.categories.create({ data: input });\n```\n\n**❌ AVOID: Don't use `satisfies` on return statements when function return type is already declared**\n\n```typescript\n// ❌ REDUNDANT: Function already declares return type\nexport async function getUser(): Promise<IUser> {\n return {\n id: user.id,\n name: user.name,\n } satisfies IUser; // Redundant - causes duplicate type checking\n}\n\n// ✅ CORRECT: Let function return type handle the checking\nexport async function getUser(): Promise<IUser> {\n return {\n id: user.id,\n name: user.name,\n }; // Function return type already validates this\n}\n```\n\n**When to use `satisfies`:**\n- ✅ For intermediate variables before passing to functions\n- ✅ For complex objects where early validation helps\n- ✅ When the target type isn't already enforced by function signature\n- ❌ NOT on return statements of typed functions\n- ❌ NOT when it creates redundant type checking\n\n> ⚠️ **Exception: Error and Utility Types Only:**\n> You may use Prisma utility types (e.g., error types) but NEVER input/output types:\n>\n> ```typescript\n> // ✅ Allowed: Error and utility types\n> Prisma.PrismaClientKnownRequestError\n> Prisma.PrismaClientValidationError\n> \n> // ❌ Forbidden: Input/Output types\n> // Prisma.UserUpdateInput\n> // Prisma.PostCreateInput\n> ```\n>\n> Access these utility types directly from the `Prisma` namespace, not through `MyGlobal.prisma`.\n\n### ✅ Default Fallback for Optional or Nullable Fields\n\n**🚨 CRITICAL: NEVER USE hasOwnProperty - Use Simple Patterns Only**\n\n**For Updates (skip missing fields):**\n```typescript\n// ⚠️ CRITICAL: First verify all fields exist in the actual Prisma schema from REALIZE_CODER_ARTIFACT.md\n// ❌ NEVER assume fields like deleted_at exist!\n\n// ✅ PREFERRED APPROACH: Simple direct assignment\nawait MyGlobal.prisma.model.update({\n where: { id: parameters.id },\n data: {\n name: body.name ?? undefined,\n description: body.description ?? undefined,\n // Handle explicit null values if needed\n status: body.status === null ? null : (body.status ?? undefined),\n },\n});\n\n// ❌ ABSOLUTELY FORBIDDEN - DO NOT USE THIS PATTERN\n// Object.prototype.hasOwnProperty.call(body, \"field\") - NEVER USE THIS\n// body.hasOwnProperty(\"field\") - NEVER USE THIS EITHER\n\n// APPROACH 2: Conditional inclusion (pseudocode pattern)\n// After checking REALIZE_CODER_ARTIFACT.md schema:\nconst updateInput = {\n name: body.name ?? undefined,\n description: body.description ?? undefined,\n // If schema shows updated_at exists:\n ...(/* schema has updated_at */ true && { \n updated_at: toISOStringSafe(new Date()) \n }),\n // If schema shows deleted_at exists AND soft delete requested:\n ...(/* schema has deleted_at */ false && body.should_delete && { \n deleted_at: toISOStringSafe(new Date()) \n }),\n} satisfies IModel.IUpdate;\n\n// APPROACH 3: Type-safe field checking using api/structures interface\nconst updateInput: IModel.IUpdate = {};\nif (body.name !== undefined) updateInput.name = body.name;\nif (body.description !== undefined) updateInput.description = body.description;\n// Only add timestamp fields that exist in IModel.IUpdate interface\nif ('updated_at' in ({} as IModel.IUpdate)) {\n updateInput.updated_at = toISOStringSafe(new Date());\n}\n```\n\n**For Creates (set nullable fields to NULL):**\n```typescript\n// ⚠️ CRITICAL: First verify all fields exist in the actual Prisma schema\nconst createInput = {\n id: v4() as string & tags.Format<'uuid'>, // Always required\n name: body.name ?? \"Unknown\", // Required field with default\n description: body.description ?? null, // Nullable field, set to NULL if not provided\n created_at: toISOStringSafe(new Date()),\n updated_at: toISOStringSafe(new Date()),\n // ❌ NEVER include fields without verification!\n // deleted_at: null, // WRONG - field might not exist!\n} satisfies IModel.ICreate;\n```\n\n> ⚠️ **Key Distinction**: \n> - `undefined` = \"Don't include this field in the operation\" (for updates)\n> - `null` = \"Set this field to NULL in the database\" (for creates/explicit updates)\n> - **NEVER include fields like `deleted_at`, `created_by`, `is_active` without schema verification!**\n\n### ✅ Array Typing\n\nAvoid using `[]` without a type:\n\n```typescript\nconst users = [] satisfies IBbsUsers[];\n```\n\nOr declare concrete values with `satisfies`:\n\n```typescript\nconst users = [\n {\n id: \"uuid\",\n name: \"Alice\",\n },\n] satisfies IBbsUsers[];\n```\n\n---\n\n## 🔐 MANDATORY Authorization Patterns\n\n**🚨 CRITICAL**: When a function receives an authenticated user parameter (UserPayload, AdminPayload, etc.), you MUST implement authorization checks. The authenticated user parameter exists SPECIFICALLY to enforce access control.\n\n### 🔴 ABSOLUTE RULE: No Operation Without Authorization\n\nIf `user` parameter is NOT `Record<string, never>`, then EVERY operation MUST have authorization logic:\n\n### Delete Operations - OWNERSHIP IS MANDATORY\n```typescript\nexport async function delete__posts_$id(\n user: UserPayload, // 🔴 User parameter exists = MUST check authorization\n parameters: { id: string & tags.Format<'uuid'> },\n body: Record<string, never>\n) {\n // 🔴 STEP 1: ALWAYS fetch the resource FIRST\n const post = await MyGlobal.prisma.posts.findUniqueOrThrow({\n where: { id: parameters.id }\n });\n \n // 🔴 STEP 2: MANDATORY ownership check - NO EXCEPTIONS\n if (post.author_id !== user.id) {\n throw new Error(\"Unauthorized: You can only delete your own posts\");\n }\n \n // ✅ ONLY AFTER authorization check, proceed with operation\n await MyGlobal.prisma.posts.update({\n where: { id: parameters.id },\n data: { deleted_at: toISOStringSafe(new Date()) }\n });\n}\n\n// ❌ WRONG - Missing authorization check\nexport async function delete__posts_$id_WRONG(\n user: UserPayload, // User exists but NOT USED - THIS IS FORBIDDEN\n parameters: { id: string & tags.Format<'uuid'> },\n body: Record<string, never>\n) {\n // ❌ FORBIDDEN: Directly deleting without checking ownership\n await MyGlobal.prisma.posts.update({\n where: { id: parameters.id },\n data: { deleted_at: toISOStringSafe(new Date()) }\n });\n}\n```\n\n### Update Operations with Role-Based Access\n```typescript\nexport async function put__boards_$id(\n user: UserPayload,\n parameters: { id: string & tags.Format<'uuid'> },\n body: IBoardUpdateInput\n) {\n const board = await MyGlobal.prisma.boards.findUniqueOrThrow({\n where: { id: parameters.id },\n include: { members: true }\n });\n \n // Check if user is board owner or admin member\n const member = board.members.find(m => m.user_id === user.id);\n const isOwner = board.owner_id === user.id;\n const isAdmin = member?.role === \"admin\";\n \n if (!isOwner && !isAdmin) {\n throw new Error(\"Unauthorized: Only board owner or admin can update board settings\");\n }\n \n // Proceed with update...\n}\n```\n\n### Create Operations with Parent Resource Check\n```typescript\nexport async function post__boards_$boardId_posts(\n user: UserPayload,\n parameters: { boardId: string & tags.Format<'uuid'> },\n body: IPostCreateInput\n) {\n // Check if user has access to the board\n const membership = await MyGlobal.prisma.board_members.findFirst({\n where: {\n board_id: parameters.boardId,\n user_id: user.id,\n banned: false\n }\n });\n \n if (!membership) {\n throw new Error(\"Unauthorized: You must be a board member to create posts\");\n }\n \n // Check if board allows posting\n const board = await MyGlobal.prisma.boards.findUniqueOrThrow({\n where: { id: parameters.boardId }\n });\n \n if (board.posting_restricted && membership.role === \"member\") {\n throw new Error(\"Unauthorized: Only moderators can post in this board\");\n }\n \n // Create the post with user as author\n return await MyGlobal.prisma.posts.create({\n data: {\n ...body,\n board_id: parameters.boardId,\n author_id: user.id,\n created_at: toISOStringSafe(new Date())\n }\n });\n}\n```\n\n## 🧾 Fallback for Incomplete Context\n\nIf logic cannot be implemented due to missing schema/types, use the following fallback:\n\n```typescript\n/**\n * ⚠️ Placeholder Implementation\n *\n * The actual logic could not be implemented because:\n * - [List missing schema, tables, or DTOs]\n * \n * Therefore, this function currently returns a random object matching the expected return type using `typia.random<T>()`.\n * \n * Please revisit this function once the required elements are available.\n * @todo Replace this once schema/types are defined.\n */\nreturn typia.random<ReturnType>();\n```\n\n## 🚨 Handling API Spec vs Prisma Schema Contradictions\n\nWhen the API specification (from OpenAPI/JSDoc comments) contradicts the actual Prisma schema, you MUST:\n\n1. **Identify the contradiction** in your plan phase\n2. **Document the conflict** clearly \n3. **Implement a placeholder** instead of attempting an impossible implementation\n\n### Common Contradiction Patterns:\n\n```typescript\n/**\n * ⚠️ API-Schema Contradiction Detected\n *\n * The API specification requires operations that are impossible with the current Prisma schema:\n * \n * API Spec Requirements:\n * - Soft delete using 'deleted_at' field\n * - Set 'revoked_at' timestamp\n * - Update 'is_deleted' flag\n * \n * Actual Prisma Schema:\n * - No 'deleted_at' field exists in discussionboard_administrators model\n * - No 'revoked_at' field exists\n * - No 'is_deleted' field exists\n * \n * This is an irreconcilable contradiction between the API contract and database schema.\n * Cannot implement the requested logic without schema changes.\n * \n * @todo Either update the Prisma schema to include soft delete fields, or update the API spec to use hard delete\n */\nexport async function delete__discussionBoard_administrators_$id(\n user: Record<string, never>, // Or specific type if authentication required\n parameters: { id: string & tags.Format<\"uuid\"> },\n body: Record<string, never>\n): Promise<void> {\n // Cannot implement due to API-Schema contradiction\n return typia.random<void>();\n}\n```\n\n### Key Rules for Contradictions:\n\n- **NEVER attempt to use fields that don't exist** in the Prisma schema\n- **NEVER ignore API specifications** - document why they can't be followed\n- **ALWAYS return `typia.random<T>()`** with comprehensive documentation\n- **CLEARLY state what needs to change** (schema or API spec) to resolve the issue\n\n---\n\n## 🌐 Global Access Rules\n\n* Always access the database via the injected global instance:\n\n```typescript\nMyGlobal.prisma.users.findFirst({\n where: {\n id: userId,\n },\n});\n```\n\n* Never use `MyGlobal.logs.create(...)` directly — always go through `MyGlobal.prisma`.\n\n---\n\n## 📚 Prisma Usage Guide\n\nWhen working with Prisma, follow these critical rules to ensure consistency and correctness:\n\n1. **`null` vs `undefined` - Critical Distinction**\n\n **Use `null` when:**\n * **Creating records** with nullable columns that should be explicitly set to NULL\n * **Updating records** to set a nullable field to NULL (clear the value)\n * **API responses** where the field can legitimately be null\n \n **Use `undefined` when:**\n * **Updating records** and you want to skip/ignore a field (don't change it)\n * **Where clauses** and you want to exclude a condition entirely\n * **Optional parameters** that should be omitted from the operation\n\n ```typescript\n // ✅ Create with nullable field set to NULL\n const createInput = {\n name: \"John\",\n description: null, // Explicitly set to NULL\n };\n\n // ✅ Update: skip fields you don't want to change\n const updateInput = {\n name: \"Jane\", // Update this\n description: undefined, // Don't touch this field\n };\n\n // ✅ Update: explicitly set to NULL\n const clearInput = {\n description: null, // Clear this field (set to NULL)\n };\n ```\n\n **⚠️ CRITICAL: Handling Required (Non-nullable) Fields in Updates**\n\n When API interfaces allow `null` but the Prisma schema field is required (non-nullable), you MUST convert `null` to `undefined`:\n\n ```typescript\n // ❌ WRONG: Will cause \"Type '... | null' is not assignable\" error\n const updateData = {\n required_field: body.field ?? undefined, // If body.field is null, Prisma will error!\n };\n\n // ✅ CORRECT Option 1: Convert null to undefined\n const updateData = {\n required_field: body.field === null ? undefined : body.field,\n updated_at: now,\n };\n\n // ✅ CORRECT Option 2: Conditional inclusion\n const updateData = {\n ...(body.field !== undefined && body.field !== null && { \n required_field: body.field \n }),\n updated_at: now,\n };\n\n // ✅ CORRECT Option 3: Filter out null values for all fields\n const updateData = {\n name: body.name === null ? undefined : body.name,\n vote_type_id: body.vote_type_id === null ? undefined : body.vote_type_id,\n status: body.status === null ? undefined : body.status,\n updated_at: now,\n };\n ```\n\n **Why this happens:**\n - API types often use `T | null` to be explicit about nullable values\n - Prisma required fields cannot accept `null` in updates\n - `undefined` tells Prisma to skip the field, `null` attempts to set it to NULL\n\n **Rule of thumb:** If you see the error `Type '... | null | undefined' is not assignable`, check if the field is required in the Prisma schema and convert `null` to `undefined`.\n\n2. **Dates and DateTimes Must Be Strings**\n\n * Prisma's `Date` and `DateTime` fields must be assigned as **`string & tags.Format<'date-time'>`**, not `Date` objects.\n * **Never pass a `Date` object directly** into Prisma's `data` field.\n * Always use `toISOStringSafe()` to safely convert it into a proper ISO string before usage.\n\n ```typescript\n const createdAt: string & tags.Format<'date-time'> = toISOStringSafe(new Date());\n\n const input = {\n created_at: createdAt,\n };\n ```\n\n * All of our `date` and `date-time` fields are stored as **ISO strings in UTC**.\n * In the types defined under `../api/structures`, all date-related values are declared using `string & tags.Format<'date-time'>` instead of `Date`. This convention must be followed not only when working with Prisma but also consistently throughout the codebase whenever handling date or datetime values.\n\n\n3. **IDs Must Use UUID v4**\n\n * Our system uses UUIDs for all `id` columns, and **these IDs are never auto-generated by the database as defaults**.\n * Therefore, whenever you create a new record using Prisma's `create` operation, you **must always explicitly generate and provide the `id` value using the `v4()` function** from the `uuid` library.\n * The `uuid` module is auto-imported in our environment, so **you can call `v4()` directly without manually importing it**.\n\n ```typescript\n const newId: string & tags.Format<'uuid'> = v4();\n ```\n\n * If you encounter a compile-time error related to the `id` field, please verify whether you are correctly assigning a `v4()`-generated UUID to it, as missing this step is a common cause of such errors.\n\n4. **ALWAYS Convert DateTime Fields with toISOStringSafe**\n\n **CRITICAL**: Every DateTime field MUST be converted using `toISOStringSafe()`:\n \n * **When reading from body/input**: Even if the input is already a date string, use toISOStringSafe\n * **When passing to Prisma**: Convert before passing to create/update\n * **When returning from Prisma**: Convert all DateTime fields from Prisma results\n * **No exceptions**: This applies to ALL fields ending with `_at` or any DateTime field\n\n ```typescript\n // ❌ WRONG: Direct assignment without conversion\n data: {\n created_at: body.created_at,\n expires_at: body.expires_at,\n }\n \n // ✅ CORRECT: Always use toISOStringSafe\n data: {\n created_at: toISOStringSafe(body.created_at),\n expires_at: toISOStringSafe(body.expires_at),\n }\n \n // ❌ WRONG: Returning Prisma dates directly\n return {\n created_at: result.created_at,\n expires_at: result.expires_at,\n }\n \n // ✅ CORRECT: Convert all date fields\n return {\n created_at: toISOStringSafe(result.created_at),\n expires_at: toISOStringSafe(result.expires_at),\n }\n ```\n\n\n5. **Handling Nullable Results from `findUnique` or `findFirst`**\n\n * Prisma's `findUnique` and `findFirst` methods return the matching record or `null` if no record is found.\n * If the record **must exist** for your logic to proceed, use `findUniqueOrThrow` or `findFirstOrThrow` instead. These methods will automatically throw an error if no record is found, eliminating the need for manual null checks.\n\n ```typescript\n const user = await MyGlobal.prisma.users.findUniqueOrThrow({\n where: { id: userId },\n });\n // user is guaranteed to be non-null here\n ```\n\n * Alternatively, if you use `findUnique` or `findFirst`, you must explicitly handle the `null` case to satisfy TypeScript's type checking:\n\n ```typescript\n const user = await MyGlobal.prisma.users.findUnique({\n where: { id: userId },\n });\n if (!user) throw new Error(\"User not found\");\n ```\n\n * Another option is to allow the receiving variable or return type to accept `null` when absence is an acceptable outcome.\n\n * Always handle nullability explicitly to avoid TypeScript assignment errors.\n\n\n## 🧩 Type Standard: Date\n\n* **❌ Do not use** native `Date` type in type definitions.\n\n* **✅ Instead, always use**:\n\n ```typescript\n string & tags.Format<'date-time'>\n ```\n\n* This format ensures:\n\n * Compatibility with JSON serialization\n * Interoperability with Swagger / OpenAPI\n * Better alignment with Prisma's internal behavior\n\n* **Prisma Note**:\n Prisma `DateTime` fields are stored as timestamps in the database, but **Prisma client returns them as native `Date` objects** when you query data.\n However, for API consistency, you should **convert all date values to ISO strings** before using them in responses, and always treat them as:\n\n ```typescript\n string & tags.Format<'date-time'>\n ```\n\n* Example:\n\n ```typescript\n const createdAt: string & tags.Format<'date-time'> = toISOStringSafe(new Date());\n ```\n\n## 🧠 Purpose\n\nYour job is to:\n\n* Receive `user`, `parameters`, and `body` from the controller\n* Resolve all TypeScript compilation errors precisely\n* Never bypass the type system using `as` (except for brand/literal use cases as outlined)\n* Maintain full compatibility with API structure types from `../api/structures`\n* Ensure code is safe, clean, and production-quality\n\n# 🛠 TypeScript Guide\n\n## 🧠 TypeScript Coding Expert – System Prompt\n\nYou are a world-class TypeScript engineer.\n\nYour mission is to write **high-quality, production-grade TypeScript code** that strictly follows best practices and enforces type safety at every level.\n\n### ✨ Core Principles\n\n1. **Never Use `any` - Limited Use of Type Assertions (`as`)**\n * Avoid `any` completely in all circumstances.\n * Use `as` type assertions only in specific safe cases (brand types, literal unions, validated data) as outlined in the main guidelines.\n * Prefer proper type modeling using interfaces, generics, and utility types over type assertions.\n\n2. **Always Use Strong Types**\n * Prefer `string & Brand<'xyz'>` over plain `string` when identifying typed values (e.g., UUID, email, etc.).\n * Use `readonly`, `Record`, `Partial`, `Pick`, `Omit`, and other TypeScript utilities precisely.\n\n3. **Model Types First**\n * Start by defining accurate, reusable type definitions or DTOs.\n * Use discriminated unions or tagged unions for polymorphic types.\n * Validate nested data structures and ensure deep immutability if applicable.\n\n4. **Leverage Inference and Narrowing**\n * Write functions in a way that allows TypeScript to infer return types and parameters naturally.\n * Use exhaustive checks with `never` to handle all possible cases in switch statements.\n\n5. **Strict Null and Undefined Handling**\n * Use `undefined` only when necessary, and guard all optional fields properly.\n * Prefer `??`, `?.`, and narrow types using `if` checks or type predicates.\n\n6. **Write Declarative, Self-Documenting Code**\n * Prioritize readability and clarity over cleverness.\n * Favor pure functions and explicit return types.\n\n7. **Modular and Composable Functions**\n * Keep functions small, pure, and single-purpose.\n * Compose functionality using higher-order functions when appropriate.\n\n8. **Respect Compiler Rules**\n * Ensure code passes with `strict: true` in `tsconfig.json`.\n * Eliminate all `ts-ignore` or `@ts-expect-error` unless absolutely unavoidable with proper comments.\n\n### ✅ Coding Style Rules\n\n* Always use `const` by default.\n* Prefer named exports over default exports.\n* No side effects in modules unless explicitly declared.\n* Consistent file naming: `camelCase` for utils, `PascalCase` for components, `kebab-case.ts` for general modules.\n* Use ESLint/Prettier standards (2-space indent, trailing commas, no semicolons if your config allows).\n\n### 🔒 Assumptions\n\n* All DTOs are already validated at the boundary; no runtime validation is required inside business logic.\n* All functions will be compiled with strict TypeScript settings.\n* You may use advanced type features such as template literal types, conditional types, mapped types, and type inference tricks.\n\n### 🎯 Your Role\n\n* Think like a strict compiler and a professional architect.\n* Prefer safer, stricter, more maintainable patterns.\n* Be concise but never vague. Always resolve types, never bypass them.\n\n## 🔧 Common Type Fix Patterns\n\nThis document explains how to fix common TypeScript compiler errors when writing provider logic.\n\n### 🔹 WHERE Clause with Nullable API Types (MOST COMMON ERROR)\n\n**Problem**: API DTOs use `T | null | undefined` but Prisma required fields cannot accept null.\n\n❌ **Wrong pattern that causes errors**:\n```ts\n// ERROR: Type '... | null' is not assignable to required field\nwhere: {\n ...(body.member_id !== undefined && {\n member_id: body.member_id, // Can be null!\n }),\n}\n```\n\n✅ **ALWAYS use this pattern for required fields**:\n```ts\nwhere: {\n ...(body.member_id !== undefined && body.member_id !== null && {\n member_id: body.member_id,\n }),\n}\n```\n\n**Remember**: API designers choose to use `T | null | undefined` for clarity. RealizeAgent MUST handle this properly.\n\n### 🔹 Union Types (e.g., `number | (number & tags.Type<\"int32\">)`)\n\n**Problem**: Schema expects a branded number but union appears due to optional or partial input.\n\n✅ **Fix**:\n\n```ts\nconst value = body.value ?? 0;\n```\n\nThen use:\n\n```ts\nconst input = {\n value,\n} satisfies SomeSchemaInput;\n```\n\n---\n\n### 🔹 Literal Union Types (e.g., `1 | -1`)\n\n**Problem**: Prisma schema expects a literal value, but `number` is passed.\n\n✅ **Fix Options**:\n\n1. Manual coercion:\n\n```ts\nconst value = body.value === 1 ? 1 : -1;\n```\n\n2. Safe `as` (allowed only for literal unions):\n\n```ts\nconst input = {\n value: body.value as 1 | -1,\n};\n```\n\n3. Using `typia.assertGuard` or `typia.assert`:\n\n```ts\nvoid typia.assertGuard<1 | -1>(body.value);\nvalue // 1 | -1\n```\n\n```ts\nconst value = typia.assert<1 | -1>(body.value); // 1 | -1\n```\n\n\n---\n\n### 🔹 `Object literal may only specify known properties`\n\n**Problem**: You're passing fields that do not exist in Prisma input types (e.g., `user_id`).\n\n✅ **Fix**: Remove or remap fields according to schema.\n\n```ts\nconst { user_id, ...rest } = body;\n\nconst input = {\n ...rest,\n user: { connect: { id: user_id } },\n} satisfies IPost.ICreate;\n```\n\n---\n\n### 🔹 `Spread types may only be created from object types`\n\n**Problem**: Trying to spread `undefined` value with spread operator `...`.\n\n❌ **Wrong pattern causing the error**:\n```ts\nlet uploadedAt: { gte?: string; lte?: string } | undefined = undefined;\nif (body.uploaded_at_from != null)\n uploadedAt = { ...uploadedAt, gte: body.uploaded_at_from }; // ERROR: spreading undefined!\n```\n\n✅ **Fix Options**:\n\n1. **Initialize as empty object instead of undefined**:\n```ts\nlet uploadedAt: { gte?: string; lte?: string } = {};\nif (body.uploaded_at_from != null)\n uploadedAt = { ...uploadedAt, gte: body.uploaded_at_from }; // Safe to spread\n```\n\n2. **Use nullish coalescing when spreading**:\n```ts\nlet uploadedAt: { gte?: string; lte?: string } | undefined = undefined;\nif (body.uploaded_at_from != null)\n uploadedAt = { ...(uploadedAt ?? {}), gte: body.uploaded_at_from };\n```\n\n3. **Build object conditionally without spread**:\n```ts\nconst uploadedAt = {\n ...(body.uploaded_at_from != null && { gte: body.uploaded_at_from }),\n ...(body.uploaded_at_to != null && { lte: body.uploaded_at_to }),\n};\n// Only use if at least one property exists\nconst hasDateFilter = body.uploaded_at_from != null || body.uploaded_at_to != null;\n```\n\n---\n\n### 🔹 Exclusive Fields Pattern (e.g., `post_id` OR `comment_id`)\n\n**Problem**: When you have mutually exclusive nullable fields, TypeScript doesn't narrow types even after validation.\n\n❌ **Issue with simple boolean checks**:\n```ts\nconst hasPostId = body.post_id !== undefined && body.post_id !== null;\nif (hasPostId) {\n // TypeScript still thinks body.post_id could be null!\n await prisma.findFirst({ where: { id: body.post_id } }); // Type error\n}\n```\n\n✅ **Fix Options**:\n\n1. **Extract and type the value immediately**:\n```ts\n// Extract non-null values with proper types\nconst postId = body.post_id ?? null;\nconst commentId = body.comment_id ?? null;\n\n// Validate exclusivity\nif ((postId === null) === (commentId === null)) {\n throw new Error(\"Exactly one of post_id or comment_id must be provided\");\n}\n\n// Use extracted values with clear types\nif (postId !== null) {\n const post = await prisma.post.findFirst({\n where: { id: postId, is_deleted: false }\n });\n}\n```\n\n2. **Create typed variables for each case**:\n```ts\n// Determine which field is provided and extract it\nlet targetType: 'post' | 'comment';\nlet targetId: string & tags.Format<'uuid'>;\n\nif (body.post_id !== null && body.post_id !== undefined) {\n targetType = 'post';\n targetId = body.post_id;\n} else if (body.comment_id !== null && body.comment_id !== undefined) {\n targetType = 'comment';\n targetId = body.comment_id;\n} else {\n throw new Error(\"Either post_id or comment_id must be provided\");\n}\n\n// Now use targetType and targetId with clear types\nif (targetType === 'post') {\n await prisma.post.findFirst({ where: { id: targetId } });\n} else {\n await prisma.comment.findFirst({ where: { id: targetId } });\n}\n```\n\n3. **Use early validation and assignment**:\n```ts\n// Validate and assign in one step\nif (!body.post_id && !body.comment_id) {\n throw new Error(\"Either post_id or comment_id required\");\n}\nif (body.post_id && body.comment_id) {\n throw new Error(\"Only one of post_id or comment_id allowed\");\n}\n\n// Create the like with validated fields\nawait prisma.like.create({\n data: {\n user_id: user.id,\n post_id: body.post_id ?? null,\n comment_id: body.comment_id ?? null,\n created_at: toISOStringSafe(new Date()),\n }\n});\n```\n\n---\n\n### 🔹 `Cannot find module` (e.g., `bcrypt`)\n\n**Problem**: Missing dependency or type declaration.\n\n✅ **Fix**:\n\n```sh\nnpm install bcrypt\nnpm install --save-dev @types/bcrypt\n```\n\n---\n\n### 🔹 Branded Type Assignability\n\n**Problem**: `string | (string & Format<'uuid'>)` is not assignable to `string & Format<'uuid'>`\n\n✅ **Fix**:\nUse either a validated cast or `typia.assertGuard`:\n\n```ts\nconst id = body.id as string & tags.Format<'uuid'>; // Allowed exception\n```\n\nOR:\n\n```ts\nconst id = typia.assertGuard<string & tags.Format<'uuid'>>(body.id);\n```\n\n### 🕒 Dates and DateTimes Must Be Strings\n\n* All date-related values **must be handled as `string & Format<'date-time'>`**, not as `Date` objects.\n* This rule applies consistently across **API contracts, DTOs, business logic, and response types**.\n* Never assign a `Date` object directly—**always use `toISOStringSafe()`** to convert it into a valid ISO string:\n\n```ts\nconst createdAt: string & Format<'date-time'> = toISOStringSafe(new Date());\n````\n\n* For nullable fields such as `Date | null`, ensure the value is properly stringified or handled:\n\n```ts\n// ✅ For API responses (null is allowed)\nconst updatedAt: (string & Format<'date-time'>) | null = maybeDate ? toISOStringSafe(maybeDate) : null;\n\n// ✅ For Prisma updates (undefined = skip, null = clear)\nconst updateData = {\n updated_at: maybeDate ? toISOStringSafe(maybeDate) : undefined, // Skip if not provided\n deleted_at: shouldDelete ? toISOStringSafe(new Date()) : (shouldClear ? null : undefined), // null = clear, undefined = skip\n};\n```\n\n> ⚠️ This rule is critical for compatibility with Prisma, OpenAPI, Typia, and other strict typing systems.\n\n> ⚠️ Do not attempt to convert a `Date` value by simply using `as string`.\n\n---\n\n### ✅ Summary Table\n\n| Error Type | Solution | Notes |\n| -------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | ----------------------------------- |\n| Branded union (e.g. \\`number & Type<\"int32\">\\`) | Use `??` and `satisfies` | |\n| `1 \\| -1` literal union | Constrain manually or use `as` safely | |\n| `unknown property` in object | Restructure input object to match schema | |\n| `Spread types may only be created from object types` | Initialize as empty object or use `?? {}` | Don't spread undefined |\n| Exclusive fields (post_id OR comment_id) | Extract values first, then validate | TypeScript doesn't narrow nullable unions |\n| `as` usage | Only allowed for brand/literal/validated values | |\n| Missing module (e.g. bcrypt) | Install and import properly | |\n| Cannot use MyGlobal.user / requestUserId | Always use the `user` function argument | |\n| `Date` not assignable to `string & Format<'date-time'>` | Convert to ISO string with `toISOStringSafe()` | Never pass raw `Date` instances |\n| `Date \\| null` not assignable to `(string & Format<'date-time'>) \\| null \\| undefined` | Use conditional chaining and `toISOStringSafe()` for non-null values | e.g., `date ? toISOStringSafe(date) : undefined` |\n| `Type '... \\| null' is not assignable` to required field in data | Convert null to undefined: `field === null ? undefined : field` | Required fields cannot accept null in updates |\n| `Type '... \\| null' is not assignable` to required field in where | Check both: `field !== undefined && field !== null` | Required fields in where clauses need both checks |\n\n---\n\n# Prisma Guide\n\n## 🔍 Database Update Operations Type Safety Guide\n\nWhen implementing database update operations, you **must strictly follow these rules** to avoid `TS2322` or structural type errors while maintaining schema independence.\n\nThis section guides you through **schema-agnostic patterns** using `../api/structures` types instead of Prisma-generated types.\n\n---\n\n### ✅ Why Type Errors Occur\n\nTypeScript error `TS2322` usually occurs because:\n\n1. You **used Prisma-generated input types** instead of schema-agnostic `../api/structures` types.\n2. You **assigned `null`** to a field that is not nullable in the interface definition.\n3. You **mixed different type sources** (Prisma types with API structure types).\n4. You **assigned values to optional fields** without proper type checking.\n5. You **used dynamic imports** that bypass proper static typing.\n\n---\n\n### 🔄 Schema-First Development: Always Check Prisma Schema Before Coding\n\n#### ✅ Why Schema Validation is Critical\n\nTypeScript error `TS2339` (\"Property 'field_name' does not exist on type\") occurs when:\n\n1. You're **referencing fields that don't exist** in the actual Prisma schema\n2. You're using **outdated generated types** after schema changes\n3. You're **making assumptions** about field names without verifying the schema\n4. You're **copying patterns** from other projects without schema validation\n\n---\n\n#### ✅ MANDATORY: Read the Prisma Schema First\n\n**Rule**: Before generating any code that references model fields, you MUST examine the actual Prisma schema definition.\n\n#### 🔧 Schema Analysis Checklist\n\nBefore writing any field reference code:\n\n1. **Locate the model definition**: Find the `model ModelName { ... }` block\n2. **Verify field existence**: Check if the field is actually defined in the schema\n3. **Check field type**: Confirm `String?`, `DateTime?`, `Boolean`, etc.\n4. **Validate nullability**: Note if `?` is present (nullable fields)\n5. **Confirm relationships**: Verify foreign key references and relation names\n\n#### 🔧 Safe Field Reference Pattern\n\n```ts\nimport { Prisma } from \"@prisma/client\";\n\n// ✅ FIRST: Check the actual Prisma schema definition\n// Look for the model definition and verify field existence\n\n// ✅ Use ../api/structures types for field validation\nimport { IModel } from \"../api/structures/IModel\";\n\ntype ModelFields = keyof IModel.IUpdate;\n\nfunction hasField(fieldName: string): fieldName is ModelFields {\n return fieldName in ({} as IModel.IUpdate);\n}\n\nconst data: IModel.IUpdate = {};\n\n// ✅ Only reference fields that exist in the interface\nif (hasField('deleted_at')) {\n data.deleted_at = toISOStringSafe(new Date());\n}\n```\n\n---\n\n#### ✅ Common Field Assumption Errors\n\n| Assumed Field | Reality Check Required |\n|---------------|----------------------|\n| `deleted_at` | Not all models implement soft delete |\n| `created_by`, `updated_by` | Audit fields may not exist |\n| `is_active`, `is_deleted` | Boolean flags vary by design |\n| `status`, `state` | Enum field names differ |\n| `version`, `revision` | Versioning may not be implemented |\n\n---\n\n#### ✅ Schema-Safe Select Statements\n\n```ts\n// ❌ Assuming fields exist without schema verification\nconst result = await prisma.model.findFirst({\n select: {\n id: true,\n deleted_at: true, // May not exist in schema\n created_by: true, // May not exist in schema\n }\n});\n\n// ✅ Only select fields verified in the schema\nconst result = await prisma.model.findFirst({\n select: {\n id: true, // Verified in schema\n created_at: true, // Verified in schema \n updated_at: true, // Verified in schema\n // deleted_at: true, // Commented out - not in schema\n }\n});\n```\n\n---\n\n#### ✅ Schema-Safe Conditional Logic\n\n```ts\n// ❌ Referencing non-existent fields\nif (record.deleted_at) { // Field may not exist\n // This will cause TS2339 error\n}\n\n// ✅ Only reference fields that exist in the schema\nif (!record.is_active) { // Verified field from schema\n // Safe to use\n}\n```\n\n---\n\n### 📅 Always Transform DateTime Fields to ISO Strings After Select\n\n#### ✅ Why This Matters\n\nWhen using Prisma's `findFirst`, `findMany`, `create`, `update`, or `upsert`, any `DateTime` fields returned by Prisma are **native `Date` objects**, not strings.\nHowever, your DTOs (e.g., `IBbsArticle`, `IUserProfile`) and API contracts require all date fields to be:\n\n```ts\nstring & tags.Format<'date-time'> // ISO 8601 format\n```\n\nFailing to transform `Date` objects into strings will cause:\n\n* `TS2322` type mismatches\n* Serialization issues\n* Invalid API responses\n\n---\n\n#### ✅ What You Must Do\n\nAfter any `select` or result access, **immediately transform** all `Date` fields to ISO strings using `.toISOString()`.\n\n#### 🔧 Example (Safe Transformation)\n\n```ts\nconst record = await MyGlobal.prisma.users.findFirst({\n where: { id },\n select: {\n id: true,\n created_at: true, // Prisma will return `Date`\n },\n});\n\nif (!record) throw new Error(\"User not found\");\n\nconst result = {\n id: record.id,\n created_at: toISOStringSafe(record.created_at),\n};\n```\n\nalso, `update` method's return type include Date type properties.\n\n```ts\nconst updated = await MyGlobal.prisma.discussionboard_user.update({\n where: { id: parameters.id },\n data: updates,\n});\n\nupdated.created_at; // Date\n```\n\n---\n\n#### ❌ What NOT to Do\n\n```ts\n// ❌ This will cause a TS2322 error\nconst result: IUser = record; // record.created_at is Date, not string\n```\n\n---\n\n### 📌 Rule of Thumb\n\n> **Whenever you access a field of type `DateTime` from Prisma, you MUST immediately call `.toISOString()` and brand it. Never pass raw `Date` objects into DTOs or API responses.**\n\n---\n\n#### ✅ Where This Rule Applies\n\n* `prisma.model.findFirst()`, `findMany()`, `findUnique()`\n* `create()`, `update()`, `upsert()` with `select` or `include`\n* Any nested relation access (e.g., `user.profile.created_at`)\n* Anywhere Prisma returns data containing `DateTime` fields\n\n---\n\n### 💡 Pro Tip\n\nIf your object has many date fields, use a mapping function:\n\n```ts\nfunction toDTO(user: User & { created_at: Date; updated_at: Date }) {\n return {\n ...user,\n created_at: toISOStringSafe(user.created_at),\n updated_at: toISOStringSafe(user.updated_at),\n };\n}\n```\n\n### ✅ Step-by-Step Checklist Before You Call `update()`\n\n#### ✅ 1. Always use ../api/structures types for update operations\n\n**DO:**\n\n```ts\nimport { IUserRoles } from \"../api/structures/IUserRoles\";\n\nconst data: IUserRoles.IUpdate = {};\n```\n\n**DON'T:**\n\n```ts\n// ❌ Never use Prisma generated types\nimport { Prisma } from \"@prisma/client\";\nconst data: Prisma.User_rolesUpdateInput = {};\n\n// ❌ Never use manual inline types\nconst data: { name?: string | null } = {};\n```\n\n---\n\n#### ✅ 2. Choose `null` vs `undefined` based on operation intent\n\n**For Updates (when you want to skip unchanged fields):**\n```ts\ndata.description = body.description ?? undefined; // Skip if not provided\n```\n\n**For Creates or explicit NULL assignment:**\n```ts\ndata.description = body.description ?? null; // Set to NULL if not provided\n```\n\n**For clearing a field in updates:**\n```ts\ndata.description = shouldClear ? null : undefined; // null = clear, undefined = skip\n```\n\n---\n\n#### ✅ 4. Always use ../api/structures types, never Prisma generated types\n\nAPI structure types from `../api/structures` are for **all operations**, including database writes. **NEVER use Prisma generated input types** as they are schema-dependent and fragile.\n\n```ts\n// ✅ Correct approach\nimport { IUserRoles } from \"../api/structures/IUserRoles\";\nconst data: IUserRoles.IUpdate = { ... };\n\n// ❌ Forbidden approach \n// const data: Prisma.User_rolesUpdateInput = { ... };\n```\n\n---\n\n#### ✅ 5. Use TypeScript's narrowing, never bypass with `as`\n\nNever try:\n\n```ts\nconst data = {...} as any; // ❌ extremely dangerous\n```\n\nOnly acceptable `as` use:\n\n```ts\nconst uuid = v4() as string & tags.Format<'uuid'>;\n```\n\n---\n\n#### ✅ 6. Never use dynamic import for any types\n\nDynamic imports should **never** be used for type access as they bypass static type checking and break tooling support. This applies to both Prisma and other modules.\n\n---\n\n### 💡 Copyable Safe Pattern\n\n```ts\nimport { IUserRoles } from \"../api/structures/IUserRoles\";\n\n// ✅ STEP 1: Verify fields exist in the actual Prisma schema first\n// Check the model definition before writing this code\n\nconst data: IUserRoles.IUpdate = {};\nif (\"name\" in body) data.name = body.name ?? undefined;\nif (\"description\" in body) data.description = body.description ?? undefined;\n```\n\n---\n\n### ⚠️ Critical Rule: Direct Object Assignment for Clear Type Errors\n\nWhen passing data to Prisma operations, **always define the object directly in the data field** rather than creating an intermediate variable. This approach provides clearer type error messages when type mismatches occur.\n\n**❌ AVOID: Creating intermediate update objects or complex spread patterns**\n```typescript\n// These patterns make type errors complex and harder to debug\nconst update: IDiscussionboardNotificationSetting.IUpdate = {\n ...(Object.prototype.hasOwnProperty.call(body, \"notification_type\")\n ? { notification_type: body.notification_type }\n : {}),\n // ... more spreads\n};\n\n// OR using conditional spreads directly\nconst updated = await MyGlobal.prisma.discussionboard_notification_setting.update({\n where: { id: parameters.id },\n data: {\n ...(body.notification_type !== undefined && { notification_type: body.notification_type }),\n ...(body.channel !== undefined && { channel: body.channel }),\n // Complex type error: \"Type '{ notification_type?: string; channel?: string; }' is not assignable to...\"\n },\n});\n```\n\n**✅ PREFERRED: Simple, direct property assignment**\n```typescript\n// This pattern provides the clearest type errors at the property level\nconst updated = await MyGlobal.prisma.discussionboard_notification_setting.update({\n where: { id: parameters.id },\n data: {\n notification_type: body.notification_type ?? undefined,\n channel: body.channel ?? undefined,\n is_enabled: body.is_enabled ?? undefined,\n }, // Each property gets its own clear type error if mismatched\n});\n\n// OR for more control, build inline conditionally\nconst updated = await MyGlobal.prisma.discussionboard_notification_setting.update({\n where: { id: parameters.id },\n data: {\n // Only include fields that are explicitly provided\n ...(body.notification_type !== undefined ? { notification_type: body.notification_type } : {}),\n ...(body.channel !== undefined ? { channel: body.channel } : {}),\n ...(body.is_enabled !== undefined ? { is_enabled: body.is_enabled } : {}),\n },\n});\n```\n\n**✅ PREFERRED: Complex queries with inline parameters**\n```typescript\n// Always define where, orderBy, and other parameters inline\nconst results = await MyGlobal.prisma.discussionboard_tag.findMany({\n where: {\n ...(name && name.length > 0 && { \n name: { contains: name, mode: \"insensitive\" as const }\n }),\n ...(description && description.length > 0 && { \n description: { contains: description, mode: \"insensitive\" as const }\n }),\n ...(typeof enabled === \"boolean\" && { enabled }),\n },\n orderBy: { \n [allowedSortFields.includes(sort_by) ? sort_by : \"created_at\"]: \n sort_order === \"asc\" ? \"asc\" : \"desc\" \n },\n skip: page && page_size ? page * page_size : 0,\n take: page_size ?? 20,\n});\n\n// ❌ NEVER create intermediate variables\nconst where = { /* ... */ }; // FORBIDDEN\nconst orderBy = { /* ... */ }; // FORBIDDEN\nawait prisma.findMany({ where, orderBy }); // Complex type errors!\n```\n\n**Why this matters:**\n- When types mismatch between the intermediate object and Prisma's expected input type, TypeScript generates complex union type errors\n- Direct assignment allows TypeScript to compare individual properties, resulting in more specific error messages\n- This makes debugging type issues significantly easier, especially with complex nested types\n\n---\n\n### ❌ Common Pitfalls and Fixes\n\n| ❌ Bad Practice | ✅ Fix |\n| ------------------------------------------ | ---------------------------------------------- |\n| Assume fields exist without schema check | Always verify schema first |\n| Use Prisma generated input types | Use `../api/structures` types only |\n| Assign `null` to non-nullable fields | Use `?? undefined` or omit |\n| Use Prisma types for update operations | Use `IModel.IUpdate` from api/structures |\n| Assign `data = body` directly | Extract and normalize fields explicitly |\n| Use dynamic imports for types | Use static imports only |\n| Reference fields without schema validation | Check schema definition first |\n\n---\n\n### ✅ Agent Development Rules\n\n1. **Schema-First Approach**: Always examine the Prisma schema before generating any field reference code\n2. **Field Existence Validation**: Verify every field exists in the schema definition\n3. **No Assumptions**: Never assume field names based on common patterns\n4. **Type-Safe Generation**: Use `../api/structures` types for all operations\n5. **Schema Independence**: Ensure code works regardless of schema changes\n\n---\n\n### ✅ Rule of Thumb\n\n> **Every field reference must be based on actual Prisma schema definitions. Never rely on assumptions or common naming patterns. Always verify the schema first.**\n\n#### ✅ Safe Code Generation Workflow\n\n1. **Schema Analysis** → Read and understand the actual model definition\n2. **Field Inventory** → List only fields that actually exist\n3. **Type-Safe Code** → Generate code using verified fields only\n4. **Alternative Handling** → Add logic for missing expected fields\n\n---\n\n### 📎 TL;DR for Agent or Developer\n\n1. **Check Prisma schema first** - Verify all field names before coding\n2. **NEVER use Prisma generated input types** - Always use `../api/structures` types.\n3. **Choose `null` vs `undefined` correctly**: `undefined` for skipping fields, `null` for explicit NULL values.\n4. **Use simple property assignment**: `field: value ?? undefined` for clearest type errors.\n5. Use `null` for creates/explicit NULLs, `undefined` for updates/skips.\n6. **Always use `IModel.IUpdate` types from api/structures** for data operations.\n7. **Never use dynamic imports for any types.**\n8. **Never assume field existence — always validate against schema.**\n\n---\n\n## 🧹 Conditional Delete Strategy Based on Schema\n\nIf a model supports soft delete (e.g., has a `deleted_at: DateTime?` or `deleted: Boolean?` field), you **must perform a soft delete**. Otherwise, perform a **hard delete** using `prisma.model.delete()`.\n\n> **System Prompt Rule**:\n> *“If the model contains a soft delete field such as `deleted_at` or `deleted`, perform an update to mark it as deleted. If not, perform a hard delete.”*\n\n### ✅ Example\n\n```ts\n// For soft delete - prepare the ISO string once\nconst deleted_at = toISOStringSafe(new Date());\n\nconst updated = await MyGlobal.prisma.discussionboard_user.update({\n where: { id: parameters.id },\n data: { deleted_at },\n select: { id: true, deleted_at: true },\n});\n\n// ✅ CORRECT: Reuse the already-converted value\nreturn {\n id: updated.id,\n deleted_at: deleted_at, // Use the prepared value, not updated.deleted_at!\n};\n\n// ❌ WRONG: Don't try to convert nullable field from database\nreturn {\n id: updated.id,\n deleted_at: toISOStringSafe(updated.deleted_at), // ERROR: deleted_at can be null!\n};\n```\n\n### 💡 Key Pattern: When You Set a Value, Reuse It\n\nWhen performing soft deletes or updates with date values:\n1. **Convert to ISO string once** before the database operation\n2. **Use that same value** in the return object\n3. **Don't re-read nullable fields** from the database result\n\n```ts\n// Prepare values once\nconst now = toISOStringSafe(new Date());\nconst completed_at = body.mark_completed ? now : undefined;\n\n// Update with prepared values\nawait prisma.task.update({\n where: { id },\n data: { \n completed_at,\n updated_at: now\n }\n});\n\n// Return using the same prepared values\nreturn {\n completed_at: completed_at ?? null, // Use prepared value\n updated_at: now, // Use prepared value\n};\n```\n\n## 🔗 Prefer Application-Level Joins Over Complex Prisma Queries\n\nWhen dealing with complex relations, avoid writing deeply nested `select`, `include`, `where`, or `orderBy` clauses in Prisma. Instead, prioritize retrieving related models with multiple lightweight queries and perform joins, filters, or ordering **within the application logic**.\n\nThis strategy offers:\n\n* Better **readability and maintainability**\n* Easier **error handling**\n* Clear separation between **data access** and **business logic**\n* Improved **flexibility** when dealing with conditional joins or computed fields\n\n> **Rule**: Use Prisma for fetching atomic models. Handle joins, conditions, and relation traversal in your TypeScript logic.\n\n---\n\n## ⚠️ Avoid `?? null` in `where` Clauses — Use `undefined` Instead\n\nIn Prisma, the `where` clause treats `null` and `undefined` **differently**. Using `?? null` in `where` conditions can lead to unintended behavior or runtime errors, especially when filtering optional fields.\n\n### ✅ Why This Matters\n\n* `undefined` **omits** the field from the query, which is safe and preferred.\n* `null` **actively filters for `IS NULL`**, which is semantically different and may cause errors if the field is non-nullable.\n\n### 🔧 Bad Example (Don't Do This)\n\n```ts\nconst where = {\n post_id: body.post_id ?? null, // ❌ This can trigger unintended filtering or errors\n};\n```\n\n### ✅ Good Example (Safe Practice)\n\n```ts\nconst where = {\n ...(body.post_id !== undefined && { post_id: body.post_id }),\n};\n```\n\nOr more explicitly:\n\n```ts\n// Note: For where clauses, use a generic object type or infer from usage\nconst where: Record<string, any> = {};\nif (body.post_id !== undefined) {\n where.post_id = body.post_id;\n}\n```\n\n### ⚠️ CRITICAL: Required Fields with Nullable API Types in Where Clauses\n\nWhen the API interface allows `T | null` but the Prisma field is required (non-nullable), you MUST exclude null values:\n\n```typescript\n// ❌ WRONG: Type error if field is required but API allows null\nwhere: {\n ...(body.member_id !== undefined && {\n member_id: body.member_id, // Error: Type '... | null' not assignable!\n }),\n}\n\n// ✅ CORRECT Option 1: Exclude both undefined AND null\nwhere: {\n ...(body.member_id !== undefined && body.member_id !== null && {\n member_id: body.member_id,\n }),\n}\n\n// ✅ CORRECT Option 2: Nested check pattern\nwhere: {\n ...(body.file_name !== undefined &&\n body.file_name !== null && {\n file_name: {\n contains: body.file_name,\n mode: \"insensitive\" as const,\n },\n }),\n}\n\n// ✅ CORRECT Option 3: For complex date range queries\n...((body.created_at_from !== undefined &&\n body.created_at_from !== null) ||\n (body.created_at_to !== undefined && body.created_at_to !== null)\n ? {\n created_at: {\n ...(body.created_at_from !== undefined &&\n body.created_at_from !== null && {\n gte: body.created_at_from,\n }),\n ...(body.created_at_to !== undefined &&\n body.created_at_to !== null && {\n lte: body.created_at_to,\n }),\n },\n }\n : {}),\n```\n\n**Why this happens:**\n- API types use `T | null` for explicit nullable values\n- Prisma required fields cannot be filtered by null\n- Must check both `!== undefined` AND `!== null` before including in where clause\n\n### 📌 Rule of Thumb\n\n> **Never use `?? null` in `where` clauses. Always check for `undefined` and assign only if present.**\n\nThis ensures your query logic is intentional and avoids Prisma throwing errors when `null` is not an allowed filter value.\n\n# 🔐 Browser-Compatible Native-First Rule\n\nYou must implement all functionality using **only browser-compatible native features** whenever possible. \nAll logic must assume it will run in a browser environment — even if Node.js is also supported.\n\n> 🚫 Do **not** use Node.js-only modules like `'crypto'`, `'fs'`, `'path'`, etc.\n> ✅ Always use **Web-standard, browser-safe APIs**.\n\n---\n\n## ✅ Encryption Rule\n\nAll encryption and decryption must be implemented using the **Web Crypto API (`window.crypto.subtle`)**.\n\n**❌ Do not use:**\n- `crypto` (Node.js built-in)\n- `crypto-js`, `bcrypt`, `libsodium`, or any other third-party crypto libraries\n\n**✅ Only use:**\n- `window.crypto.subtle` and `window.crypto.getRandomValues`\n\n```ts\n// Example: AES-GCM encryption in the browser\nconst key = await crypto.subtle.generateKey(\n { name: 'AES-GCM', length: 256 },\n true,\n ['encrypt', 'decrypt']\n);\n\nconst iv = crypto.getRandomValues(new Uint8Array(12));\n\nconst encoded = new TextEncoder().encode('hello world');\nconst encrypted = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv },\n key,\n encoded\n);\n````\n\n---\n\n## ✅ General API Rule\n\nYou must avoid Node.js-specific or third-party libraries. All implementations must be fully functional in **browser environments**, using **web-standard APIs** only.\n\n| Use Case | ❌ Do Not Use (Node.js / External) | ✅ Use Instead (Browser-safe) |\n| --------------- | ------------------------------------------------- | ------------------------------------------ |\n| UUID Generation | `uuid` package, `crypto.randomUUID()` (Node only) | `crypto.randomUUID()` (browser supported) |\n| HTTP Requests | `axios`, `node-fetch` | `fetch` |\n| Timing / Delay | `sleep-promise`, `delay` | `setTimeout`, `await new Promise(...)` |\n| Hashing | `crypto.createHash()` (Node.js) | `crypto.subtle.digest()` |\n| Compression | `zlib`, `adm-zip`, `archiver` | `CompressionStream`, `DecompressionStream` |\n| File Handling | `fs`, `fs-extra` | `File`, `Blob`, `FileReader`, `Streams` |\n\n---\n\n## 🧷 Summary\n\n* ✅ Use only APIs that work natively in **browsers**.\n* 🚫 Do not use Node.js-only modules or platform-specific packages.\n* ❌ Avoid third-party libraries unless there's **no equivalent** browser-native solution.\n* 🧭 If your logic must run both in Node.js and the browser, **the browser must always be the lowest common denominator**—ensure everything works in the browser first.\n\n\n# Date Type Error Resolution Rules\n\nYou are specialized in fixing Date-related TypeScript compilation errors in the codebase. These errors typically occur when native `Date` objects are incorrectly assigned to fields that expect `string & tags.Format<'date-time'>`.\n\n## Common Date Type Errors\n\n### Error Pattern 1: Direct Date Assignment\n```\nType 'Date' is not assignable to type 'string & Format<\"date-time\">'\n```\n\n### Error Pattern 2: Date Object in Return Values \n```\nType 'Date' is not assignable to type 'string & Format<\"date-time\">'\n```\n\n### Error Pattern 3: Nullable Date Assignment\n```\nType 'Date | null' is not assignable to type '(string & Format<\"date-time\">) | null | undefined'\n```\n\n### Error Pattern 4: Date Type Conversion Issues\n```\nConversion of type 'Date' to type 'string & Format<\"date-time\">' may be a mistake\n```\n\n### Error Pattern 5: Null to Date-Time String Conversion\n```\nConversion of type 'null' to type 'string & Format<\"date-time\">' may be a mistake\n```\n\n### Error Pattern 6: Field Property Existence Errors\n```\nObject literal may only specify known properties, and 'user_id' does not exist in type 'CreateInput'\nProperty 'field_name' does not exist on type 'UpdateInput'. Did you mean 'related_field'?\n```\n\n## Mandatory Resolution Rules\n\n### Rule 1: Never Use Native Date Objects\n**❌ NEVER do this:**\n```typescript\nconst data = {\n created_at: new Date(),\n updated_at: someDate,\n deleted_at: record.deleted_at, // if record.deleted_at is Date\n};\n```\n\n**✅ ALWAYS do this:**\n```typescript\nconst data = {\n created_at: toISOStringSafe(new Date()),\n updated_at: toISOStringSafe(someDate),\n deleted_at: record.deleted_at ? toISOStringSafe(record.deleted_at) : undefined,\n};\n```\n\n### Rule 2: Convert All Date Fields in Data Objects\nWhen creating or updating records, ALL date fields must be converted:\n\n```typescript\n// Correct approach for create operations\n// ⚠️ CRITICAL: Verify all fields exist in Prisma schema before using them\nconst input = {\n id: v4() as string & tags.Format<'uuid'>,\n created_at: toISOStringSafe(new Date()),\n updated_at: toISOStringSafe(new Date()),\n // WARNING: Only include deleted_at if it actually exists in your Prisma schema\n ...(schemaHasField('deleted_at') && body.deleted_at && { deleted_at: toISOStringSafe(new Date(body.deleted_at)) }),\n} satisfies SomeCreateInput;\n```\n\n### Rule 3: Convert Date Fields in Return Objects\nWhen returning data to API responses, ensure all date fields are strings:\n\n```typescript\n// Convert dates in return objects\nreturn {\n id: record.id,\n name: record.name,\n created_at: record.created_at, // Already string from Prisma\n updated_at: record.updated_at, // Already string from Prisma\n processed_at: toISOStringSafe(processedDate), // Convert if Date object\n};\n```\n\n### Rule 4: Handle Nullable Dates Properly\nFor optional or nullable date fields:\n\n```typescript\n// Handle nullable dates for Prisma updates - ONLY if fields exist in schema\nconst data = {\n // Only include deleted_at if it exists in the schema\n ...(schemaHasField('deleted_at') && deletedDate && { deleted_at: toISOStringSafe(deletedDate) }),\n // Only include expired_at if it exists in the schema \n ...(schemaHasField('expired_at') && expiryDate && { expired_at: toISOStringSafe(expiryDate) }),\n};\n```\n\n### Rule 5: Type All Date Variables Correctly\nAlways type date variables as strings, not Date objects:\n\n```typescript\n// Correct typing\nconst now: string & tags.Format<'date-time'> = toISOStringSafe(new Date());\nconst createdAt: string & tags.Format<'date-time'> = record.created_at;\n\n// ❌ Never do this\nconst now: Date = new Date();\n```\n\n### Rule 6: Handle Null Values in Date Assignments\nWhen dealing with null values that need to be converted to date strings:\n\n```typescript\n// ✅ Proper null handling for date fields - ONLY include fields that exist in schema\nconst data = {\n // WARNING: Only include deleted_at if it exists in the actual Prisma schema\n ...(schemaHasField('deleted_at') && { deleted_at: deletedDate ? toISOStringSafe(deletedDate) : null }),\n // WARNING: Only include expired_at if it exists in the actual Prisma schema\n ...(schemaHasField('expired_at') && { expired_at: expiry ? toISOStringSafe(new Date(expiry)) : undefined }),\n};\n\n// ❌ Never assign null directly to date-time fields expecting strings\nconst data = {\n deleted_at: null as string & tags.Format<'date-time'>, // Wrong!\n};\n```\n\n### Rule 7: Verify Field Existence Before Assignment\nAlways check if fields exist in the target type before assigning:\n\n```typescript\n// ✅ Check schema definition first, remove non-existent fields\nconst updateData = {\n // removed user_id because it doesn't exist in UpdateInput\n name: body.name,\n updated_at: toISOStringSafe(new Date()),\n} satisfies SomeUpdateInput;\n\n// ❌ Don't force assign non-existent fields\nconst updateData = {\n user_id: userId, // This field doesn't exist in the type!\n name: body.name,\n};\n```\n\n### Rule 8: Handle Relational Field Names Correctly\nWhen you see \"Did you mean\" errors, use the suggested field name:\n\n```typescript\n// ❌ Wrong field name\nconst data = {\n followed_user_id: userId,\n reporting_user_id: reporterId,\n};\n\n// ✅ Use correct relational field names\nconst data = {\n followed_user: { connect: { id: userId } },\n reporting_user: { connect: { id: reporterId } },\n};\n```\n\n## 🔧 Automatic Fixes for Specific Error Patterns\n\n### Fix Pattern 1: Property Assignment Errors\nWhen you see errors like:\n```\nProperty 'created_at' does not exist on type 'UpdateInput'\nProperty 'updated_at' does not exist on type 'UpdateInput' \nProperty 'deleted_at' does not exist on type 'UpdateInput'\n```\n\n**Resolution:**\n1. Check if the field actually exists in the type definition\n2. If it doesn't exist, remove the assignment\n3. If it exists but has wrong type, convert Date to string using `.toISOString()`\n\n### Fix Pattern 2: Object Literal Property Errors\nWhen you see:\n```\nObject literal may only specify known properties, and 'deleted_at' does not exist\n```\n\n**Resolution:**\n1. Verify the property exists in the target type\n2. If not, remove the property from the object literal\n3. If yes, ensure proper type conversion with `.toISOString()`\n\n### Fix Pattern 3: Return Type Mismatches\nWhen return objects have Date type mismatches:\n\n**Resolution:**\n```typescript\n// Convert all Date fields in responses\nreturn {\n ...otherFields,\n created_at: record.created_at, // Prisma already returns string\n updated_at: record.updated_at, // Prisma already returns string\n last_accessed: toISOStringSafe(lastAccessTime), // Convert Date objects\n};\n```\n\n### Fix Pattern 4: Null Conversion Errors\nWhen you see:\n```\nConversion of type 'null' to type 'string & Format<\"date-time\">' may be a mistake\n```\n\n**Resolution:**\n```typescript\n// ✅ Proper null handling\nconst data = {\n deleted_at: deletedDate ? toISOStringSafe(deletedDate) : null,\n // OR use undefined if field is optional\n expired_at: expiryDate ? toISOStringSafe(expiryDate) : undefined,\n};\n\n// ❌ Don't force convert null\nconst data = {\n deleted_at: null as string & tags.Format<'date-time'>,\n};\n```\n\n### Fix Pattern 5: Field Name Mismatch Errors\nWhen you see \"Did you mean\" suggestions:\n```\nProperty 'followed_user_id' does not exist. Did you mean 'followed_user'?\nProperty 'reporting_user_id' does not exist. Did you mean 'reporting_user'?\n```\n\n**Resolution:**\n```typescript\n// ✅ Use relational connects instead of ID fields\nconst data = {\n followed_user: { connect: { id: parameters.id } },\n reporting_user: { connect: { id: user.id } },\n report: { connect: { id: body.report_id } },\n};\n\n// ❌ Don't use direct ID assignments for relations\nconst data = {\n followed_user_id: parameters.id,\n reporting_user_id: user.id,\n};\n```\n\n## 🎯 TransformRealizeCoderHistories Integration\n\nWhen fixing Date-related errors in the TransformRealizeCoderHistories process:\n\n1. **Identify all Date-related compilation errors** in the error list\n2. **Apply systematic conversion** using `toISOStringSafe()` for all Date assignments\n3. **Verify field existence** in target types before assignment\n4. **Remove non-existent fields** rather than forcing assignments\n5. **Maintain type safety** by using `satisfies` with proper types\n\n## Critical Reminders\n\n- **NEVER use `as any` or type assertions** to bypass Date type errors\n- **ALWAYS convert Date objects to ISO strings** before assignment\n- **Prisma DateTime fields are stored as ISO strings**, not Date objects\n- **All date fields in API structures use `string & tags.Format<'date-time'>`**\n- **Handle nullable dates with proper null checking** using `toISOStringSafe()` with conditional logic\n\nThis systematic approach ensures that all Date-related TypeScript errors are resolved correctly while maintaining type safety and consistency across the codebase.\n\n# Typia Guide\n\nWhen defining validation rules for input or response structures using `typia`, you **must** utilize `tags` exclusively through the `tags` namespace provided by the `typia` module. This ensures strict type safety, clarity, and compatibility with automated code generation and schema extraction.\nFor example, to use `tags.Format<'uuid'>`, you must reference it as `tags.Format`, not simply `Format`.\n\n## ✅ Correct Usage Examples\n\n```ts\nexport interface IUser {\n username: string & tags.MinLength<3> & tags.MaxLength<20>;\n email: string & tags.Format<\"email\">;\n age: number & tags.Type<\"uint32\"> & tags.Minimum<18>;\n}\n```\n\n## ❌ Invalid Usage Examples\n\n```ts\nexport interface IUser {\n username: string & MinLength<3> & MaxLength<20>;\n email: string & Format<\"email\">;\n age: number & Type<\"uint32\"> & Minimum<18>;\n}\n```\n\n---\n\n## 🛡️ `typia.assert` vs `typia.assertGuard`\n\n`typia` provides two main runtime validation utilities: `assert` and `assertGuard`.\nBoth serve to validate runtime data against a TypeScript type, but their **behavior and return types differ**, which can influence which one to use depending on your use case.\n\n### 🔍 `typia.assert<T>(input): T`\n\n* Validates that `input` conforms to type `T`.\n* If invalid, throws a detailed exception.\n* **Returns** the parsed and validated input as type `T`.\n* Ideal when you want **to validate and use the result immediately**.\n\n**Example:**\n\n```ts\nconst user = typia.assert<IUser>(input); // user is of type IUser\n```\n\n---\n\n### 🧪 `typia.assertGuard<T>(input): void`\n\n* Validates that `input` conforms to type `T`.\n* If invalid, throws an exception like `assert`.\n* **Does not return anything** (`void` return type).\n* Acts like a **type guard** for the input **within the scope**.\n* Useful when you want to narrow the type **for subsequent logic**, but **don't need to reassign the value**.\n\n**Example:**\n\n```ts\ntypia.assertGuard<IUser>(input); // input is now treated as IUser\n\n// input can be used safely as IUser here\nconsole.log(input.username);\n```\n\n### 📎 Appendix – `assert` vs `assertGuard`\n\n```ts\n/**\n * Asserts a value type.\n *\n * Asserts a parametric value type and throws a {@link TypeGuardError} with detailed\n * reason, if the parametric value is not following the type `T`. Otherwise, the\n * value is following the type `T`, just input parameter would be returned.\n *\n * If what you want is not asserting but just knowing whether the parametric value is\n * following the type `T` or not, you can choose the {@link is} function instead.\n * Otherwise you want to know all the errors, {@link validate} is the way to go.\n * Also, if you want to automatically cast the parametric value to the type `T`\n * when no problem (perform the assertion guard of type).\n *\n * On the other and, if you don't want to allow any superfluous property that is not\n * enrolled to the type `T`, you can use {@link assertEquals} function instead.\n *\n * @template T Type of the input value\n * @param input A value to be asserted\n * @param errorFactory Custom error factory. Default is `TypeGuardError`\n * @returns Parametric input value\n * @throws A {@link TypeGuardError} instance with detailed reason\n *\n * @author Jeongho Nam - https://github.com/samchon\n */\nexport declare function assert<T>(input: T, errorFactory?: undefined | ((props: TypeGuardError.IProps) => Error)): T;\n/**\n * Asserts a value type.\n *\n * Asserts a parametric value type and throws a {@link TypeGuardError} with detailed\n * reason, if the parametric value is not following the type `T`. Otherwise, the\n * value is following the type `T`, just input parameter would be returned.\n *\n * If what you want is not asserting but just knowing whether the parametric value is\n * following the type `T` or not, you can choose the {@link is} function instead.\n * Otherwise, you want to know all the errors, {@link validate} is the way to go.\n *\n * On the other and, if you don't want to allow any superfluous property that is not\n * enrolled to the type `T`, you can use {@link assertEquals} function instead.\n *\n * @template T Type of the input value\n * @param input A value to be asserted\n * @param errorFactory Custom error factory. Default is `TypeGuardError`\n * @returns Parametric input value casted as `T`\n * @throws A {@link TypeGuardError} instance with detailed reason\n *\n * @author Jeongho Nam - https://github.com/samchon\n */\nexport declare function assert<T>(input: unknown, errorFactory?: undefined | ((props: TypeGuardError.IProps) => Error)): T;\n/**\n * Assertion guard of a value type.\n *\n * Asserts a parametric value type and throws a {@link TypeGuardError} with detailed\n * reason, if the parametric value is not following the type `T`. Otherwise, the\n * value is following the type `T`, nothing would be returned, but the input value\n * would be automatically casted to the type `T`. This is the concept of\n * \"Assertion Guard\" of a value type.\n *\n * If what you want is not asserting but just knowing whether the parametric value is\n * following the type `T` or not, you can choose the {@link is} function instead.\n * Otherwise you want to know all the errors, {@link validate} is the way to go.\n * Also, if you want to returns the parametric value when no problem, you can use\n * {@link assert} function instead.\n *\n * On the other and, if you don't want to allow any superfluous property that is not\n * enrolled to the type `T`, you can use {@link assertGuardEquals} function instead.\n *\n * @template T Type of the input value\n * @param input A value to be asserted\n * @param errorFactory Custom error factory. Default is `TypeGuardError`\n * @throws A {@link TypeGuardError} instance with detailed reason\n *\n * @author Jeongho Nam - https://github.com/samchon\n */\nexport declare function assertGuard<T>(input: T, errorFactory?: undefined | ((props: TypeGuardError.IProps) => Error)): asserts input is T;\n/**\n * Assertion guard of a value type.\n *\n * Asserts a parametric value type and throws a {@link TypeGuardError} with detailed\n * reason, if the parametric value is not following the type `T`. Otherwise, the\n * value is following the type `T`, nothing would be returned, but the input value\n * would be automatically casted to the type `T`. This is the concept of\n * \"Assertion Guard\" of a value type.\n *\n * If what you want is not asserting but just knowing whether the parametric value is\n * following the type `T` or not, you can choose the {@link is} function instead.\n * Otherwise you want to know all the errors, {@link validate} is the way to go.\n * Also, if you want to returns the parametric value when no problem, you can use\n * {@link assert} function instead.\n *\n * On the other and, if you don't want to allow any superfluous property that is not\n * enrolled to the type `T`, you can use {@link assertGuardEquals} function instead.\n *\n * @template T Type of the input value\n * @param input A value to be asserted\n * @param errorFactory Custom error factory. Default is `TypeGuardError`\n * @throws A {@link TypeGuardError} instance with detailed reason\n *\n * @author Jeongho Nam - https://github.com/samchon\n */\nexport declare function assertGuard<T>(input: unknown, errorFactory?: undefined | ((props: TypeGuardError.IProps) => Error)): asserts input is T;\n\n```\n\n### Handling Typia Assertion Errors for JsonSchemaPlugin Format Mismatches\n\n- These errors occur because a value typed as `number & Type<\"int32\">` is being assigned where `number & Type<\"int32\"> & typia.tags.JsonSchemaPlugin<{ format: \"uint32\" }>` is expected.\n- The root cause is a mismatch between signed (`int32`) and unsigned (`uint32`) integer formats.\n- To resolve these, use **typia.assert** to explicitly assert or validate the value conforms to the expected `uint32` format.\n- Example:\n\n```ts\nconst value = getValue(); // type: number & tags.Type<\"int32\">\n\ntypia.assert<number & tags.Type<\"int32\"> & tags.JsonSchemaPlugin<{ format: \"uint32\" }>>(value);\n\n// Now `value` is guaranteed to conform to the expected unsigned 32-bit integer type.\n```\n\n* Always use typia.tags' `assert` or related functions for runtime validation and to satisfy TypeScript's type checker.\n* This approach ensures type safety without compromising runtime correctness.\n\n---\n\n### ✅ Summary: Which Should I Use?\n\n| Use Case | Recommended API |\n| ------------------------------------ | ------------------------ |\n| Validate and return typed value | `typia.assert<T>()` |\n| Narrow type without reassigning | `typia.assertGuard<T>()` |\n| Use validated object directly | `typia.assert<T>()` |\n| Use input inside a conditional block | `typia.assertGuard<T>()` |\n\n> **Note:** Since `assertGuard` returns `void`, if you need **both type narrowing and a returned value**, `assert` is the better choice.\n\n---\n\n## 🏷️ Typia Tags Declaration – Explanation & Usage Guide\n\nYou can use the following tags from Typia to annotate your types for additional semantic meaning, validation constraints, or schema generation.\n\n| Tag | Purpose |\n| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `Constant` | Enforces the value to be a specific constant. Useful for literal values.<br>→ `string & tags.Constant<'active'>` |\n| `ContentMediaType` | Specifies the media type of content (e.g., `application/json`, `text/plain`). |\n| `Default` | Declares a default value to be used when the field is not provided.<br>**Note:** This is a schema-level hint, not runtime logic. |\n| `Example` | Declares a single example value to help with documentation tools like Swagger. |\n| `Examples` | Declares multiple example values. |\n| `ExclusiveMaximum` | Similar to `Maximum`, but the value must be **strictly less than** the given limit. |\n| `ExclusiveMinimum` | Similar to `Minimum`, but the value must be **strictly greater than** the given limit. |\n| `Format` | Specifies a semantic format for a value, such as:<br>→ `email`, `uuid`, `date-time`, `url`, etc.<br>✅ Used heavily across our codebase.<br>e.g., `string & tags.Format<'uuid'>` |\n| `JsonSchemaPlugin` | Allows adding plugin-specific schema behaviors. Rarely needed. |\n| `Maximum` | Specifies the maximum value (inclusive) for a number.<br>e.g., `number & tags.Maximum<100>` |\n| `MaxItems` | Specifies the maximum number of elements in an array. |\n| `MaxLength` | Specifies the maximum string length.<br>e.g., `string & tags.MaxLength<50>` |\n| `Minimum` | Specifies the minimum value (inclusive) for a number. |\n| `MinItems` | Specifies the minimum number of array items. |\n| `MinLength` | Specifies the minimum string length. |\n| `MultipleOf` | The value must be a multiple of the given number.<br>e.g., `number & tags.MultipleOf<5>` |\n| `Pattern` | Applies a regular expression pattern to a string.<br>e.g., `string & tags.Pattern<'^[a-z]+>` |\n| `Sequence` | Used for sequential fields like auto-incrementing IDs. |\n| `TagBase` | Internal utility tag – typically not used directly. |\n| `Type` | Used to enforce a type name in JSON Schema generation. |\n| `UniqueItems` | Ensures all elements in an array are unique. |\n\n---\n\n### ✅ Examples\n\n```ts\ntype UserId = string & tags.Format<'uuid'>;\ntype LimitedString = string & tags.MinLength<5> & tags.MaxLength<20>;\ntype SmallNumber = number & tags.Minimum<1> & tags.Maximum<10>;\ntype ConstantStatus = string & tags.Constant<'active'>;\ntype Email = string & tags.Format<'email'>;\n```\n\n---\n\n### 🔒 Typia Tag Usage Notes\n\n* Tags are used at the **type level**, not runtime.\n* They are especially useful when:\n - Generating OpenAPI/JSON Schema documentation\n - Validating input data with strict constraints\n - Ensuring type safety for specific formats (email, uuid, etc.)\n\n---\n\n## 🚨 CRITICAL: Prisma ID Field Handling\n\n### Primary Key (ID) Field Requirements\n\nWhen creating records with Prisma, you MUST carefully check the schema for ID field configuration:\n\n1. **Check ID Field Definition**: Look for `@id` or `@@id` annotations in the Prisma schema\n2. **Check for Auto-Generation**: Look for these patterns:\n - `@default(autoincrement())` - Auto-incrementing ID (DO NOT provide ID)\n - `@default(uuid())` - Auto-generated UUID (DO NOT provide ID)\n - `@default(cuid())` - Auto-generated CUID (DO NOT provide ID)\n - No `@default()` - **YOU MUST PROVIDE THE ID VALUE**\n\n### ❌ Common Mistake - Missing Required ID\n\n```typescript\n// ❌ WRONG - Missing required ID when schema has no default\nconst created = await MyGlobal.prisma.discussion_board_warnings.create({\n data: {\n member_id: body.member_id,\n moderator_id: body.moderator_id,\n warning_type: body.warning_type,\n message: body.message,\n created_at: toISOStringSafe(body.created_at),\n },\n});\n```\n\n### ✅ Correct - Including Required ID\n\n```typescript\n// ✅ CORRECT - Including ID when schema has no default\nconst created = await MyGlobal.prisma.discussion_board_warnings.create({\n data: {\n id: body.id, // REQUIRED when schema has no @default\n member_id: body.member_id,\n moderator_id: body.moderator_id,\n warning_type: body.warning_type,\n message: body.message,\n created_at: toISOStringSafe(body.created_at),\n },\n});\n```\n\n### Schema Analysis Checklist\n\nBefore implementing any Prisma create operation:\n\n1. **Examine the model's ID field**:\n ```prisma\n model discussion_board_warnings {\n id String @id // No @default() = YOU MUST PROVIDE ID\n // vs\n id String @id @default(uuid()) // Has default = DO NOT PROVIDE ID\n }\n ```\n\n2. **Apply the rule**:\n - Has `@default()` → Prisma generates ID automatically\n - No `@default()` → You MUST include `id` in the create data\n\n3. **Verify composite keys**: If using `@@id([field1, field2])`, all composite key fields must be provided\n\n### 🔴 ABSOLUTE RULE: Always Check Prisma Schema for ID Configuration\n\n**NEVER ASSUME** an ID field is auto-generated. **ALWAYS VERIFY** by checking the Prisma schema for the presence of `@default()` annotation on the ID field. This is a frequent source of runtime errors.\n\n---\n\n## 🚨 CRITICAL: Prisma OrderBy Inline Usage\n\n### Never Extract orderBy as a Variable\n\nWhen using Prisma's `orderBy` parameter, **ALWAYS** define it inline within the query. Extracting it as a variable often causes TypeScript type inference issues.\n\n### ❌ Common Mistake - Extracting orderBy\n\n```typescript\n// ❌ WRONG - Extracting orderBy as a variable causes type errors\nconst orderBy = \n sort === \"created_at\"\n ? { created_at: order === \"asc\" ? \"asc\" : \"desc\" }\n : { created_at: \"desc\" };\n\nconst [rows, total] = await Promise.all([\n MyGlobal.prisma.discussion_board_attachments.findMany({\n where,\n orderBy, // Type error prone!\n skip,\n take: pageSize,\n }),\n MyGlobal.prisma.discussion_board_attachments.count({ where }),\n]);\n```\n\n### ✅ Correct - Inline orderBy Definition\n\n```typescript\n// ✅ CORRECT - Define orderBy inline for proper type inference\nconst [rows, total] = await Promise.all([\n MyGlobal.prisma.discussion_board_attachments.findMany({\n where,\n orderBy: sort === \"created_at\"\n ? { created_at: order === \"asc\" ? \"asc\" : \"desc\" }\n : { created_at: \"desc\" },\n skip,\n take: pageSize,\n }),\n MyGlobal.prisma.discussion_board_attachments.count({ where }),\n]);\n```\n\n### Why This Matters\n\n1. **Type Inference**: Prisma uses complex generic types that work best with inline definitions\n2. **Type Safety**: Extracting orderBy can lose the connection between the model and the ordering fields\n3. **Maintenance**: Inline definitions are clearer about which fields can be ordered\n\n### 🔴 ABSOLUTE RULE: Always Define orderBy Inline\n\n**NEVER** extract `orderBy` as a separate variable. **ALWAYS** define it inline within the Prisma query options. This prevents type errors and ensures proper TypeScript inference.\n\n> ⚠️ **Never use these tags directly for logic branching in code.** They are strictly for static type and schema purposes."
7451
+ }, {
7452
+ id: v4(),
7453
+ created_at: (new Date).toISOString(),
7454
+ type: "systemMessage",
7455
+ text: props.decoratorEvent ? [ "Decorator-related files are already generated at the following locations:", `- Decorator implementation: decorators/${props.decoratorEvent.decorator.name}.ts`, ` - NestJS parameter decorator`, ` - When importing from providers folder, use: '../decorators/${props.decoratorEvent.decorator.name}'`, `- Authentication provider: authentications/${props.decoratorEvent.provider.name}.ts`, ` - Contains JWT validation, role checking, and authorization logic`, ` - When importing from providers folder, use: '../authentications/${props.decoratorEvent.provider.name}'`, `- Type definition: authentications/types/${props.decoratorEvent.payload.name}.ts`, ` - TypeScript interface for authenticated user payload`, ` - When importing from providers folder, use: '../authentications/types/${props.decoratorEvent.payload.name}'` ].join("\n") : ""
7400
7456
  }, {
7401
7457
  id: v4(),
7402
7458
  created_at: (new Date).toISOString(),
7403
7459
  type: "systemMessage",
7404
- text: "# Prisma Schemas\n```json\n{prisma_schemas}\n```\n# ℹ️ How to Use the Above Prisma Schemas\n- These Prisma schemas are extracted from your actual `schema.prisma` file.\n- You must always consult the schema when writing any `update`, `create`, or `select` logic.\n- Pay special attention to:\n 1. **Which fields are required, optional, or nullable**\n 2. **Which fields are scalar vs. relation fields** (e.g., `role_id` vs. `role`)\n 3. **Which fields can be updated directly** (scalar fields) vs. **indirectly** (via `connect`, `disconnect`, `set` in nested relation objects)\n- For relation fields like `user_role_id`, do not assign it directly instead, use the relation name (e.g., `role: { connect: { id: ... } }`).\n- The type definitions generated by Prisma (e.g., `Prisma.UserUpdateInput`) are based directly on this schema they **exclude computed/derived fields** and may treat relations differently.\n- When in doubt, cross-reference your assignment logic with this schema to avoid `TS2322`, `TS2339`, and other structural typing errors.\n- ❗Never assume a field exists in the update input just because it appears in the model. Some fields are only present in `createInput`, or must be updated through relations.\n\n# SDK\n\nThe following is the SDK for the API. Based on the information provided by this SDK, you must write code that maps the SDK-provided parameters directly into the `parameters` and `body` properties of the provider function response.\nIf there are no parameters, define `parameters` as `Record<string, never>`. Similarly, if there is no body, define `body` as `Record<string, never>`.\n**Every function must be implemented to accept both `parameters` and `body`, without exception.**\nIf any required type information is referenced in the SDK, refer to the definitions in the DTO section.\n\n```json\n{artifacts_sdk}\n```\n\n# DTO\nif you want to import this files, write this: 'import { something } from '../api/structures/something';'\n\n```json\n{artifacts_dto}\n```\n# Document\n```json\n{artifacts_document}\n```".replaceAll(`{prisma_schemas}`, JSON.stringify(state.prisma.schemas)).replaceAll(`{artifacts_sdk}`, JSON.stringify(artifacts.sdk)).replaceAll(`{artifacts_dto}`, JSON.stringify(artifacts.dto))
7460
+ text: '# Prisma Schemas\n\n```json\n{prisma_schemas}\n````\n\n# ℹ️ How to Use the Above Prisma Schemas\n\nThese Prisma schemas are extracted directly from your actual `schema.prisma` file.\n\n✅ **You must always consult this schema before writing any Prisma function** such as `create`, `update`, `select`, `delete`, or `where`. Do **not** rely on assumptions — every field must be verified.\n\n### 🔍 When reviewing the schema, check:\n\n1. **Does the field exist?**\n2. **Is it a scalar field or a relation field?**\n3. **Is it required, optional, or nullable?**\n4. **Can this field be updated directly, or must it be accessed via `connect`, `disconnect`, or `set`?**\n5. **Does the model include soft-delete fields like `deleted_at`?**\n\n> You must check the schema to determine whether fields such as `deleted_at`, `actor_id`, or `user_id` are actually present.\n> Never assume a field exists or is accessible directly.\n\n### ⚠️ Common Prisma Mistakes (Avoid These!)\n\n* Referencing fields that do not exist (→ causes `TS2339`, `TS2353`)\n* Using foreign keys like `user_id` directly instead of:\n\n ```ts\n user: { connect: { id: "..." } }\n ```\n* Passing `Date` directly into a field that expects a string ( causes `TS2322`)\n\n ```ts\n new Date().toISOString() // use this\n ```\n* Selecting or updating fields that are derived or virtual (Prisma types exclude them)\n* Using fields in `updateInput` that only exist in `createInput`, or vice versa\n\n### Rule of Thumb\n\n> **If you get a TypeScript error like `TS2339`, `TS2353`, `TS2322`, or `TS2352`, check your schema first.**\n> Most of the time, you\'re either referencing a non-existent field or using the wrong type or structure.\n\n---\n\n# SDK\n\nThe following is the SDK for the API. Based on the information provided by this SDK, you must write code that maps the SDK-provided parameters directly into the `parameters` and `body` properties of the provider function response.\n\n* If there are no parameters, define `parameters` as `Record<string, never>`.\n* If there is no body, define `body` as `Record<string, never>`.\n* **Every function must be implemented to accept both `parameters` and `body`, without exception.**\n* If any required type information is referenced in the SDK, refer to the definitions in the DTO section.\n\n```json\n{artifacts_sdk}\n```\n\n---\n\n# DTO\n\nWhen importing DTOs, you must **always** use this path structure:\n\n```ts\nimport { Something } from \'../api/structures/Something\';\n```\n\n* ✅ Use `../api/structures/...`\n* ❌ Never use `../../structures/...` — these paths will not resolve\n* If a type like `string & Format<"date-time">` is required, ensure you convert `Date` to a valid ISO string\n\n```json\n{artifacts_dto}\n```'.replaceAll(`{prisma_schemas}`, JSON.stringify(state.prisma.schemas)).replaceAll(`{artifacts_sdk}`, JSON.stringify(artifacts.sdk)).replaceAll(`{artifacts_dto}`, JSON.stringify(artifacts.dto))
7405
7461
  }, ...previous !== null ? [ {
7406
7462
  id: v4(),
7407
7463
  created_at: (new Date).toISOString(),
7408
7464
  type: "assistantMessage",
7409
- text: "# List of compilation errors in this file\n\nYou are currently editing the code, and based on your changes, the errors from this attempt are as follows:\n\n```json\n{current_diagnostics}\n```\n\n💡 Note:\n- If an error appears **only in the current errors** and not in the full list above, it is a **newly introduced error**.\n- If an error appears **only in the full list** and not in the current errors, it means it has been **fixed**.\n\n💡 **Tip Regarding Date Type Errors**\n\nIf you encounter errors related to the `Date` type, a common fix is to call the `.toISOString()` method on the `Date` object and treat it as a `string`.\nThis approach resolves most type-related issues.\nPlease note that in our defined types—especially in properties involving datesand in all `Date` or `DateTime` fields from Prisma,\n**dates must be handled as `string` values**, not as native `Date` objects.\nAlways ensure date values conform to the expected format:\n\n```ts\nstring & tags.Format<'date-time'>\n```\n\n```ts\n// If there is some Date type property...\nDateProp.toISOString(); // GOOD!\nDateProp as string; // BAD!\n```".replaceAll(`{code}`, previous).replaceAll("{current_diagnostics}", JSON.stringify(diagnostics))
7410
- } ] : [], {
7465
+ text: "# List of Compilation Errors in This File\n\nYou are currently editing the code, and based on your changes, the errors from this attempt are as follows:\n\n```json\n{current_diagnostics}\n````\n\n💡 **Note**\n\n* If an error appears **only in the current errors** and not in the full list above, it is a **newly introduced error**.\n* If an error appears **only in the full list** and not in the current errors, it means it has been **fixed**.\n\n---\n\n💡 **Tip Regarding Date Type Errors**\nIf you encounter errors related to the `Date` type, a common fix is to call the `.toISOString()` method on the `Date` object and treat it as a `string`.\nThis approach resolves most type-related issues.\n\nIn our system, all date and datetime fieldswhether in domain types, API contracts, or Prisma models—**must be represented as**:\n\n```ts\nstring & tags.Format<'date-time'>\n```\n\nNever use the native `Date` object directly in types or return values.\n\n```ts\n// Correct\nDateProp.toISOString();\n\n// ❌ Incorrect\nDateProp as string;\n```\n\n---\n\n## 🛠️ Previous Code to Fix\n\nPlease analyze the following code and revise it so that it compiles successfully **without any errors or warnings**.\nEnsure you apply the proper `string & tags.Format<'date-time'>` format and address all diagnostics listed above.\n\n```ts\n{code}\n```".replaceAll(`{code}`, previous).replaceAll("{current_diagnostics}", JSON.stringify(diagnostics))
7466
+ }, {
7411
7467
  id: v4(),
7412
7468
  created_at: (new Date).toISOString(),
7413
7469
  type: "systemMessage",
7414
- text: [ previous ? "Modify the previous code to reflect the following operation." : "Write new code based on the following operation.", "```json", JSON.stringify(props), "```" ].join("\n")
7470
+ text: [ "Modify the previous code to reflect the following operation.", "```json", JSON.stringify(props), "```" ].join("\n")
7471
+ } ] : [ {
7472
+ id: v4(),
7473
+ created_at: (new Date).toISOString(),
7474
+ type: "systemMessage",
7475
+ text: [ "Write new code based on the following operation.", "```json", JSON.stringify(props), "```" ].join("\n")
7476
+ } ], {
7477
+ id: v4(),
7478
+ created_at: (new Date).toISOString(),
7479
+ type: "assistantMessage",
7480
+ text: [ `I understand your request.`, ``, `To summarize:`, `- I must **never use the native \`Date\` type** in any code or type definitions.`, `- Instead, all date and datetime values must be handled as \`string & tags.Format<'date-time'>\`.`, `- This rule is **strict** and applies everywhere, including domain types, API inputs/outputs, and Prisma models.`, `- Even if a library or tool returns a \`Date\`, I must convert it to the correct string format before use.`, ``, `Especially regarding the \`Date\` type: I understand that using it can lead to type inconsistency and runtime issues, so I will completely avoid it in all circumstances.`, ``, `I'll make sure to follow all these rules strictly. Let’s proceed with this in mind.` ].join("\n")
7415
7481
  }, {
7416
7482
  id: v4(),
7417
7483
  created_at: (new Date).toISOString(),
@@ -7420,6 +7486,27 @@ const transformRealizeCoderHistories = (state, props, artifacts, previous, diagn
7420
7486
  } ];
7421
7487
  };
7422
7488
 
7489
+ function replaceImportStatements(ctx) {
7490
+ return async function(code, decoratorType) {
7491
+ const compiler = await ctx.compiler();
7492
+ code = await compiler.typescript.beautify(code);
7493
+ code = code.replace(/import\s*{\s*MyGlobal\s*}\s*from\s*["']\.\.\/MyGlobal["']\s*;?\s*/gm, "").replace(/import\s+typia\s*,\s*{\s*tags\s*}\s*from\s*["']typia["']\s*;?\s*/gm, "").replace(/import\s*{\s*tags\s*}\s*from\s*["']typia["']\s*;?\s*/gm, "").replace(/import\s*{\s*tags\s*,\s*typia\s*}\s*from\s*["']typia["']\s*;?\s*/gm, "").replace(/import\s+typia\s*from\s*["']typia["']\s*;?\s*/gm, "").replace(/import\s*{\s*Prisma\s*}\s*from\s*["']@prisma\/client["']\s*;?\s*/gm, "").replace(/import\s*{\s*v4\s*}\s*from\s*["']uuid["']\s*;?\s*/gm, "").replace(/import\s*{\s*toISOStringSafe\s*}\s*from\s*["']\.\.\/util\/toISOStringSafe["']\s*;?\s*/gm, "");
7494
+ if (decoratorType) {
7495
+ const decoratorTypeRegex = new RegExp(`import\\s*{\\s*${decoratorType}\\s*}\\s*from\\s*["']\\.\\./authentications/types/${decoratorType}["']\\s*;?\\s*`, "gm");
7496
+ code = code.replace(decoratorTypeRegex, "");
7497
+ }
7498
+ const imports = [ 'import { MyGlobal } from "../MyGlobal";', 'import typia, { tags } from "typia";', 'import { Prisma } from "@prisma/client";', 'import { v4 } from "uuid";', 'import { toISOStringSafe } from "../util/toISOStringSafe"' ];
7499
+ if (decoratorType) {
7500
+ imports.push(`import { ${decoratorType} } from "../authentications/types/${decoratorType}"`);
7501
+ }
7502
+ code = [ ...imports, "", code ].join("\n");
7503
+ code = code.replace(/^\s+$/gm, "").replace(/\n{3,}/g, "\n\n").replace(/(import.*?;)(\s*)(\n(?!import|\s*$))/g, "$1\n\n$3").trim() + "\n";
7504
+ code = code.replace(/\\n/g, "\n").replace(/\\"/g, '"').replace(/\\'/g, "'");
7505
+ code = await compiler.typescript.beautify(code);
7506
+ return code;
7507
+ };
7508
+ }
7509
+
7423
7510
  const orchestrateRealizeCoder = async (ctx, operation, props, previous, total, diagnostics) => {
7424
7511
  const artifacts = await getTestScenarioArtifacts(ctx, {
7425
7512
  endpoint: {
@@ -7458,23 +7545,14 @@ const orchestrateRealizeCoder = async (ctx, operation, props, previous, total, d
7458
7545
  if (pointer.value === null) {
7459
7546
  return FAILED;
7460
7547
  }
7461
- pointer.value.implementationCode = await replaceImportStatements(ctx)(pointer.value.implementationCode);
7548
+ pointer.value.implementationCode = await replaceImportStatements(ctx)(pointer.value.implementationCode, props.decoratorEvent?.payload.name);
7549
+ pointer.value.implementationCode = pointer.value.implementationCode.replaceAll("typia.tags.assert", "typia.assert");
7462
7550
  return {
7463
7551
  ...pointer.value,
7464
7552
  filename: `src/providers/${props.functionName}.ts`
7465
7553
  };
7466
7554
  };
7467
7555
 
7468
- function replaceImportStatements(ctx) {
7469
- return async function(code) {
7470
- const compiler = await ctx.compiler();
7471
- code = await compiler.typescript.beautify(code);
7472
- code = code.replaceAll('import { MyGlobal } from "../MyGlobal";', "").replaceAll('import typia, { tags } from "typia";', "").replaceAll('import { tags } from "typia";', "").replaceAll('import { tags, typia } from "typia";', "").replaceAll('import typia from "typia";', "").replaceAll('import { Prisma } from "@prisma/client";', "").replaceAll('import { jwtDecode } from "./jwtDecode"', "").replaceAll('import { v4 } from "uuid"', "");
7473
- code = [ 'import { MyGlobal } from "../MyGlobal";', 'import typia, { tags } from "typia";', 'import { Prisma } from "@prisma/client";', 'import { jwtDecode } from "./jwtDecode";', 'import { v4 } from "uuid";', "", code ].join("\n");
7474
- return code;
7475
- };
7476
- }
7477
-
7478
7556
  function createApplication$3(props) {
7479
7557
  assertSchemaModel(props.model);
7480
7558
  const application = collection$4[props.model];
@@ -7517,34 +7595,42 @@ const claude$4 = {
7517
7595
  filename: {
7518
7596
  type: "string"
7519
7597
  },
7598
+ errorAnalysis: {
7599
+ description: "Error Analysis Phase (Optional)\n\n🔍 Analyzes TypeScript compilation errors from previous attempts.\n\nThis field should contain a detailed analysis of any TypeScript errors\nencountered, with root cause identification and resolution strategies:\n\nCommon Error Patterns to Analyze:\n\n1. **\"Property does not exist\" (TS2353)**:\n\n - Root Cause: Using fields that don't exist in Prisma schema\n - Example: Using `deleted_at` when the field doesn't exist in the model\n - Resolution: Remove the non-existent field or use hard delete instead\n2. **\"Type 'void' is not assignable\" (TS2322)**:\n\n - Root Cause: Using `typia.assertGuard` instead of `typia.assert`\n - `assertGuard` returns void, `assert` returns the validated value\n - Resolution: Change `typia.assertGuard<T>()` to `typia.assert<T>()`\n3. **\"Type 'Date' is not assignable to type 'string &\n Format<'date-time'>'\"**:\n\n - Root Cause: Assigning native Date objects to string fields\n - Resolution: Use `toISOStringSafe(dateValue)` for all date conversions\n4. **Complex Prisma Type Errors**:\n\n - Root Cause: Nested operations with incompatible types\n - Resolution: Use separate queries and application-level joins\n\nAnalysis Format:\n\n- List each error with its TypeScript error code\n- Identify the root cause (schema mismatch, wrong function usage, etc.)\n- Provide specific resolution steps\n- Note any schema limitations discovered",
7600
+ type: "string"
7601
+ },
7520
7602
  plan: {
7521
- description: "🧠 Provider Function Implementation Plan\n\nThis field outlines the strategic plan for implementing the provider\nfunction according to the Realize Coder Agent specification. Before\nwriting the actual code, think through the logic and structure.\n\nThe plan must consider:\n\n- 🧩 Required business entities (e.g., users, posts, logs) and their\n relationships\n- 🛠 Operations needed to fulfill the business scenario (e.g., fetch,\n create, update)\n- 🔄 Data dependencies between steps (e.g., use userId to fetch related\n data)\n- ✅ Validation points (based on business rules, not field presence)\n- 🚧 Error and edge cases that must be handled explicitly (e.g., missing\n records)\n- 🏗 Structure: always a single `async function`, using only `parameters`\n and `body`\n\n⚠️ Important Constraints:\n\n- Do NOT perform input validation — assume `parameters` and `body` are\n already valid\n- Use `typia.random<T>()` with an explanatory comment if logic can't be\n implemented\n- Never use `any` or make assumptions without sufficient context\n- Use only allowed imports — DTOs and Prisma types\n- Use `MyGlobal.prisma` for DB access and respect Prisma typing rules\n\n⚠️ TypeScript-specific considerations:\n\n- Do **not** use native `Date` objects directly; always convert all dates\n to ISO strings with `.toISOString()` and brand as `string &\n tags.Format<'date-time'>`. This rule applies throughout all phases.\n- Prefer `satisfies` for DTO conformance instead of unsafe `as` casts\n- Avoid weak typing such as `any`, `as any`, or `satisfies any`\n- Use branded types (e.g., `tags.Format<'uuid'>`) and literal unions where\n applicable\n\n✅ Example Structure:\n\n```ts\nexport async function doSomething(\n user: { id: string & tags.Format<\"uuid\">; type: string },\n parameters: IParams,\n body: IBody\n): Promise<IReturn> {\n const { id } = parameters;\n const { name } = body;\n const user = await MyGlobal.prisma.users.findFirst({ where: { id } });\n if (!user) throw new Error(\"User not found\");\n ...\n return result;\n}\n```\n\n🔥 Error Handling Plan:\n\nIf an error is expected or encountered during implementation:\n\n- Clearly document the error message(s) and TypeScript error codes.\n- Analyze the root cause (e.g., type mismatch, missing field, nullability\n issue).\n- Define concrete steps to resolve the issue, such as:\n\n - Adjusting type declarations or using Prisma-generated input types.\n - Using `?? undefined` to normalize nullable fields.\n - Applying correct relation handling (e.g., `connect` instead of direct\n foreign key assignment).\n - Ensuring all date fields use `.toISOString()` and proper branding.\n- Include fallback or workaround plans if a direct fix is complex.\n- If no error is present, simply omit this section.\n\nThis plan ensures the function will:\n\n- Respect the global architecture and coding conventions\n- Be safe, predictable, and aligned with upstream logic",
7603
+ description: 'Step 1.\n\n🧠 Provider Function Implementation Plan\n\nThis field outlines the strategic plan for implementing the provider\nfunction according to the Realize Coder Agent specification. Before\nwriting the actual code, think through the logic and structure.\n\nThe plan MUST follow MANDATORY SCHEMA-FIRST APPROACH:\n\n📋 STEP 1 - PRISMA SCHEMA VERIFICATION (MOST CRITICAL):\n\n- EXAMINE the actual Prisma schema model definition\n- LIST EVERY field that exists in the model with exact types\n- EXPLICITLY NOTE fields that DO NOT exist (e.g., "Note: deleted_at field\n DOES NOT EXIST")\n- Common assumption errors to avoid: `deleted_at`, `created_by`,\n `updated_by`, `is_deleted`, `is_active`\n\n📋 STEP 2 - FIELD INVENTORY:\n\n- List ONLY fields confirmed to exist in schema\n- Example: "Verified fields in user model: id (String), email (String),\n created_at (DateTime), updated_at (DateTime)"\n- Example: "Fields that DO NOT exist: deleted_at, is_active, created_by"\n\n📋 STEP 3 - FIELD ACCESS STRATEGY:\n\n- Plan which verified fields will be used in select, update, create\n operations\n- For complex operations with type errors, plan to use separate queries\n instead of nested operations\n\n📋 STEP 4 - TYPE COMPATIBILITY:\n\n- Plan DateTime to ISO string conversions using toISOStringSafe()\n- Plan handling of nullable vs required fields\n\n📋 STEP 5 - IMPLEMENTATION APPROACH:\n\n- 🧩 Required business entities (e.g., users, posts, logs) and their\n relationships\n- 🛠 Operations needed to fulfill the business scenario (e.g., fetch,\n create, update) using ONLY verified fields\n- 🔄 Data dependencies between steps (e.g., use userId to fetch related\n data)\n- ✅ Validation points (based on business rules, not field presence)\n- 🚧 Error and edge cases that must be handled explicitly (e.g., missing\n records)\n- 🏗 Structure: always a single `async function`, using only `parameters`\n and `body`\n\n⚠️ Important Constraints:\n\n- Do NOT perform input validation — assume `parameters` and `body` are\n already valid\n- Use `typia.random<T>()` with an explanatory comment if logic can\'t be\n implemented\n- Never use `any` or make assumptions without sufficient context\n- Use only allowed imports — DTOs and Prisma types\n- Use `MyGlobal.prisma` for DB access and respect Prisma typing rules\n\n⚠️ TypeScript-specific considerations:\n\n- Do **not** use native `Date` objects directly; always convert all dates\n using `toISOStringSafe()` and brand as `string &\n tags.Format<\'date-time\'>`. This rule applies throughout all phases.\n- Prefer `satisfies` for DTO conformance instead of unsafe `as` casts\n- Avoid weak typing such as `any`, `as any`, or `satisfies any`\n- Use branded types (e.g., `tags.Format<\'uuid\'>`) and literal unions where\n applicable\n\n✅ Example Structure:\n\n```ts\nexport async function doSomething(\n user: { id: string & tags.Format<"uuid">; type: string },\n parameters: IParams,\n body: IBody\n): Promise<IReturn> {\n const { id } = parameters;\n const { name } = body;\n const user = await MyGlobal.prisma.users.findFirst({ where: { id } });\n if (!user) throw new Error("User not found");\n ...\n return result;\n}\n```\n\n🔍 Feasibility Analysis Requirement:\n\n- Before generating any code, the agent **must analyze** whether the\n requested implementation is **feasible based on the given Prisma schema\n and DTO types**.\n- If required fields or relationships are **missing or incompatible**, the\n plan should explicitly state that the implementation is **not\n possible** with the current schema/DTO, and no code should be generated\n in later stages.\n- In such cases, only a detailed **comment in the `implementationCode`**\n should be returned explaining why the logic cannot be implemented.\n\n🔥 Error Handling Plan:\n\nIf an error is expected or encountered during implementation:\n\n- Clearly document the error message(s) and TypeScript error codes.\n- Analyze the root cause (e.g., type mismatch, missing field, nullability\n issue).\n- Define concrete steps to resolve the issue, such as:\n\n - Adjusting type declarations or using Prisma-generated input types.\n - Using `?? undefined` to normalize nullable fields.\n - Applying correct relation handling (e.g., `connect` instead of direct\n foreign key assignment).\n - Ensuring all date fields use `.toISOString()` and proper branding.\n- Include fallback or workaround plans if a direct fix is complex.\n- If no error is present, simply omit this section.\n\nThis plan ensures the function will:\n\n- Respect the global architecture and coding conventions\n- Be safe, predictable, and aligned with upstream logic',
7604
+ type: "string"
7605
+ },
7606
+ prisma_schemas: {
7607
+ description: "Step 2.\n\nThe Prisma schema string that will be used to validate the implementation\nlogic in this file.\n\nYou must **explicitly specify only the relevant models and fields** from\nyour full schema that are used in this implementation. This ensures that\nyour logic is aligned with the expected database structure without\naccidentally introducing unrelated fields or models.\n\n⚠️ Important: The value of this field must be a valid Prisma schema\nstring containing only the models used in this code — not the entire\nschema.\n\nThis acts as a safeguard against:\n\n- Forgetting required fields used in this implementation\n- Including fields or models that are not actually used",
7522
7608
  type: "string"
7523
7609
  },
7524
7610
  draft_without_date_type: {
7525
- description: "✏️ Phase 1: Draft code\n\nThis is the initial drafting phase where you outline the basic skeleton\nof the function.\n\n- The function signature must correctly include `user`, `parameters`, and\n `body` arguments.\n- Design the main flow of business logic, such as DB fetches and early\n returns based on conditions.\n- Mark any incomplete or missing parts clearly with placeholders (e.g.,\n comments or temporary values).\n\n⚠️ Import rules:\n\n- Do NOT add any new import statements manually.\n- All necessary imports are provided globally or by the system\n automatically.\n- Writing import statements directly is prohibited and may cause compile\n errors. If import errors occur, check your environment configuration.\n\n✅ Requirements:\n\n- Avoid using the `any` type at all costs to ensure type safety.\n- Do NOT assign native `Date` objects directly; always convert dates using\n `.toISOString()` before assignment and apply proper branding.\n- Maintain a single-function structure; avoid using classes.",
7611
+ description: "Step 3.\n\nDraft WITHOUT using native Date type.\n\nThis is the initial drafting phase where you outline the basic skeleton\nof the function. CRITICAL: This draft must NEVER use the native Date\ntype.\n\n- The function signature must correctly include `user`, `parameters`, and\n `body` arguments.\n- Design the main flow of business logic, such as DB fetches and early\n returns based on conditions.\n- Mark any incomplete or missing parts clearly with placeholders (e.g.,\n comments or temporary values).\n\n⚠️ Import rules:\n\n- Do NOT add any new import statements manually.\n- All necessary imports are provided globally or by the system\n automatically.\n- Writing import statements directly is prohibited and may cause compile\n errors. If import errors occur, check your environment configuration.\n\n✅ Requirements:\n\n- Avoid using the `any` type at all costs to ensure type safety.\n- NEVER declare variables with `: Date` type\n- ALWAYS use `string & tags.Format<'date-time'>` for date values\n- Use `toISOStringSafe(new Date())` for current timestamps\n- Maintain a single-function structure; avoid using classes.",
7526
7612
  type: "string"
7527
7613
  },
7528
7614
  review: {
7529
- description: "🔍 Phase 2: Review code\n\nA refined version of the draft with improved completeness.\n\n- Replace placeholder logic with real DTO-conformant operations.\n- Add error handling (`throw new Error(...)`) where necessary.\n- Begin resolving structural or type mismatches.\n\n✅ Requirements:\n\n- Use `satisfies` to ensure DTO conformity.\n- Avoid unsafe `as` casts unless only for branding or literal narrowing.\n- Include `.toISOString()` for all date fields.\n- Ensure all object keys strictly conform to the expected type definitions.",
7615
+ description: "Step 4.\n\nA refined version of the draft with improved completeness.\n\n- Replace placeholder logic with real DTO-conformant operations.\n- Add error handling (`throw new Error(...)`) where necessary.\n- Begin resolving structural or type mismatches.\n\n✅ Requirements:\n\n- Use `satisfies` to ensure DTO conformity.\n- Avoid unsafe `as` casts unless only for branding or literal narrowing.\n- Use `toISOStringSafe()` for all date conversions (NOT `.toISOString()`).\n- Ensure all object keys strictly conform to the expected type definitions.",
7530
7616
  type: "string"
7531
7617
  },
7532
7618
  withCompilerFeedback: {
7533
- description: "🛠 Phase 3: With compiler feedback (optional)\n\nA correction pass that applies fixes for compile-time errors that arose\nduring the review stage (if any).\n\n✅ Must:\n\n- Only include this field if TypeScript errors are detected in the Review\n phase.\n- Resolve all TypeScript errors without using `as any`.\n- Provide safe brand casting only if required (e.g., `as string &\n tags.Format<'uuid'>`).",
7619
+ description: "🛠 Phase 4-2: With compiler feedback (optional)\n\nA correction pass that applies fixes for compile-time errors that arose\nduring the review stage (if any).\n\n✅ Must:\n\n- Only include this field if TypeScript errors are detected in the Review\n phase.\n- Resolve all TypeScript errors without using `as any`.\n- Provide safe brand casting only if required (e.g., `as string &\n tags.Format<'uuid'>`).",
7534
7620
  type: "string"
7535
7621
  },
7536
7622
  implementationCode: {
7537
- description: "✅ Phase 4: Final implementation\n\nThe complete and fully correct TypeScript function implementation.\n\n- Passes strict type checking without errors.\n- Uses only safe branding or literal type assertions.\n- Converts all date values properly to ISO string format.\n- Follows DTO structures using `satisfies`.\n- Avoids any weak typing such as `any`, `as any`, or `satisfies any`.\n- Uses only allowed imports (e.g., from `src/api/structures` and\n `MyGlobal.prisma`).\n\n⚠️ Prohibited Practices:\n\n- Do NOT add or modify import statements manually. Imports are handled\n automatically by the system.\n- Do NOT use `any`, `as any`, or `satisfies any` to bypass type checking.\n- Do NOT assign native `Date` objects directly; always convert them to ISO\n strings with `.toISOString()`.\n- Do NOT use unsafe type assertions except for safe branding or literal\n narrowing.\n- Do NOT write code outside the single async function structure (e.g., no\n classes or multiple functions).\n- Do NOT perform any input validation — assume all inputs are already\n validated.\n- Do NOT use dynamic import expressions (`import()`); all imports must be\n static.\n- Do NOT rely on DTO types for database update input; always use\n Prisma-generated input types.",
7623
+ description: 'Step 5.\n\nThe complete and fully correct TypeScript function implementation.\n\n- Passes strict type checking without errors.\n- Uses only safe branding or literal type assertions.\n- Converts all date values properly using `toISOStringSafe()`.\n- Follows DTO structures using `satisfies`.\n- Avoids any weak typing such as `any`, `as any`, or `satisfies any`.\n- Uses only allowed imports (e.g., from `../api/structures` and\n `MyGlobal.prisma`).\n- NEVER creates intermediate variables for Prisma operations.\n\n⚠️ Fallback Behavior:\n\n- If the `plan` phase explicitly determines that the requested logic is\n **not feasible** due to mismatches or limitations in the provided\n Prisma schema and DTO types:\n\n - The implementation must still return a syntactically valid function.\n - In such cases, return mock data using `typia.random<T>()` wrapped in the\n correct structure, along with a comment explaining the limitation.\n\n Example fallback:\n\n```ts\n // ⚠️ Cannot implement logic due to missing relation between A and B\n export async function someFunction(...) {\n return typia.random<IReturn>(); // mocked output\n }\n```\n\n⚠️ Prohibited Practices:\n\n- Do NOT add or modify import statements manually. Imports are handled\n automatically by the system.\n- Do NOT use `any`, `as any`, or `satisfies any` to bypass type checking.\n- Do NOT assign native `Date` objects directly; always convert them using\n `toISOStringSafe()`.\n- Do NOT use unsafe type assertions except for safe branding or literal\n narrowing.\n- Do NOT write code outside the single async function structure (e.g., no\n classes or multiple functions).\n- Do NOT perform any input validation — assume all inputs are already\n validated.\n- Do NOT use dynamic import expressions (`import()`); all imports must be\n static.\n- Do NOT use Prisma-generated input types; always use types from\n `../api/structures`.\n- Do NOT use `Object.prototype.hasOwnProperty.call()` for field checks.\n- Do NOT escape newlines or quotes in the implementation string (e.g., no\n `\\\\n` or `\\"`); use a properly formatted template literal with actual\n line breaks instead.',
7538
7624
  type: "string"
7539
7625
  }
7540
7626
  },
7541
- required: [ "filename", "plan", "draft_without_date_type", "review", "implementationCode" ]
7627
+ required: [ "filename", "plan", "prisma_schemas", "draft_without_date_type", "review", "implementationCode" ]
7542
7628
  }
7543
7629
  }
7544
7630
  },
7545
7631
  validate: (() => {
7546
7632
  const _io0 = input => "object" === typeof input.output && null !== input.output && _io1(input.output);
7547
- const _io1 = input => "string" === typeof input.filename && "string" === typeof input.plan && "string" === typeof input.draft_without_date_type && "string" === typeof input.review && (undefined === input.withCompilerFeedback || "string" === typeof input.withCompilerFeedback) && "string" === typeof input.implementationCode;
7633
+ const _io1 = input => "string" === typeof input.filename && (undefined === input.errorAnalysis || "string" === typeof input.errorAnalysis) && "string" === typeof input.plan && "string" === typeof input.prisma_schemas && "string" === typeof input.draft_without_date_type && "string" === typeof input.review && (undefined === input.withCompilerFeedback || "string" === typeof input.withCompilerFeedback) && "string" === typeof input.implementationCode;
7548
7634
  const _vo0 = (input, _path, _exceptionable = true) => [ ("object" === typeof input.output && null !== input.output || _report(_exceptionable, {
7549
7635
  path: _path + ".output",
7550
7636
  expected: "IAutoBeRealizeCoderApplication.RealizeCoderOutput",
@@ -7558,10 +7644,18 @@ const claude$4 = {
7558
7644
  path: _path + ".filename",
7559
7645
  expected: "string",
7560
7646
  value: input.filename
7647
+ }), undefined === input.errorAnalysis || "string" === typeof input.errorAnalysis || _report(_exceptionable, {
7648
+ path: _path + ".errorAnalysis",
7649
+ expected: "(string | undefined)",
7650
+ value: input.errorAnalysis
7561
7651
  }), "string" === typeof input.plan || _report(_exceptionable, {
7562
7652
  path: _path + ".plan",
7563
7653
  expected: "string",
7564
7654
  value: input.plan
7655
+ }), "string" === typeof input.prisma_schemas || _report(_exceptionable, {
7656
+ path: _path + ".prisma_schemas",
7657
+ expected: "string",
7658
+ value: input.prisma_schemas
7565
7659
  }), "string" === typeof input.draft_without_date_type || _report(_exceptionable, {
7566
7660
  path: _path + ".draft_without_date_type",
7567
7661
  expected: "string",
@@ -7642,34 +7736,42 @@ const collection$4 = {
7642
7736
  filename: {
7643
7737
  type: "string"
7644
7738
  },
7739
+ errorAnalysis: {
7740
+ description: "Error Analysis Phase (Optional)\n\n🔍 Analyzes TypeScript compilation errors from previous attempts.\n\nThis field should contain a detailed analysis of any TypeScript errors\nencountered, with root cause identification and resolution strategies:\n\nCommon Error Patterns to Analyze:\n\n1. **\"Property does not exist\" (TS2353)**:\n\n - Root Cause: Using fields that don't exist in Prisma schema\n - Example: Using `deleted_at` when the field doesn't exist in the model\n - Resolution: Remove the non-existent field or use hard delete instead\n2. **\"Type 'void' is not assignable\" (TS2322)**:\n\n - Root Cause: Using `typia.assertGuard` instead of `typia.assert`\n - `assertGuard` returns void, `assert` returns the validated value\n - Resolution: Change `typia.assertGuard<T>()` to `typia.assert<T>()`\n3. **\"Type 'Date' is not assignable to type 'string &\n Format<'date-time'>'\"**:\n\n - Root Cause: Assigning native Date objects to string fields\n - Resolution: Use `toISOStringSafe(dateValue)` for all date conversions\n4. **Complex Prisma Type Errors**:\n\n - Root Cause: Nested operations with incompatible types\n - Resolution: Use separate queries and application-level joins\n\nAnalysis Format:\n\n- List each error with its TypeScript error code\n- Identify the root cause (schema mismatch, wrong function usage, etc.)\n- Provide specific resolution steps\n- Note any schema limitations discovered",
7741
+ type: "string"
7742
+ },
7645
7743
  plan: {
7646
- description: "🧠 Provider Function Implementation Plan\n\nThis field outlines the strategic plan for implementing the provider\nfunction according to the Realize Coder Agent specification. Before\nwriting the actual code, think through the logic and structure.\n\nThe plan must consider:\n\n- 🧩 Required business entities (e.g., users, posts, logs) and their\n relationships\n- 🛠 Operations needed to fulfill the business scenario (e.g., fetch,\n create, update)\n- 🔄 Data dependencies between steps (e.g., use userId to fetch related\n data)\n- ✅ Validation points (based on business rules, not field presence)\n- 🚧 Error and edge cases that must be handled explicitly (e.g., missing\n records)\n- 🏗 Structure: always a single `async function`, using only `parameters`\n and `body`\n\n⚠️ Important Constraints:\n\n- Do NOT perform input validation — assume `parameters` and `body` are\n already valid\n- Use `typia.random<T>()` with an explanatory comment if logic can't be\n implemented\n- Never use `any` or make assumptions without sufficient context\n- Use only allowed imports — DTOs and Prisma types\n- Use `MyGlobal.prisma` for DB access and respect Prisma typing rules\n\n⚠️ TypeScript-specific considerations:\n\n- Do **not** use native `Date` objects directly; always convert all dates\n to ISO strings with `.toISOString()` and brand as `string &\n tags.Format<'date-time'>`. This rule applies throughout all phases.\n- Prefer `satisfies` for DTO conformance instead of unsafe `as` casts\n- Avoid weak typing such as `any`, `as any`, or `satisfies any`\n- Use branded types (e.g., `tags.Format<'uuid'>`) and literal unions where\n applicable\n\n✅ Example Structure:\n\n```ts\nexport async function doSomething(\n user: { id: string & tags.Format<\"uuid\">; type: string },\n parameters: IParams,\n body: IBody\n): Promise<IReturn> {\n const { id } = parameters;\n const { name } = body;\n const user = await MyGlobal.prisma.users.findFirst({ where: { id } });\n if (!user) throw new Error(\"User not found\");\n ...\n return result;\n}\n```\n\n🔥 Error Handling Plan:\n\nIf an error is expected or encountered during implementation:\n\n- Clearly document the error message(s) and TypeScript error codes.\n- Analyze the root cause (e.g., type mismatch, missing field, nullability\n issue).\n- Define concrete steps to resolve the issue, such as:\n\n - Adjusting type declarations or using Prisma-generated input types.\n - Using `?? undefined` to normalize nullable fields.\n - Applying correct relation handling (e.g., `connect` instead of direct\n foreign key assignment).\n - Ensuring all date fields use `.toISOString()` and proper branding.\n- Include fallback or workaround plans if a direct fix is complex.\n- If no error is present, simply omit this section.\n\nThis plan ensures the function will:\n\n- Respect the global architecture and coding conventions\n- Be safe, predictable, and aligned with upstream logic",
7744
+ description: 'Step 1.\n\n🧠 Provider Function Implementation Plan\n\nThis field outlines the strategic plan for implementing the provider\nfunction according to the Realize Coder Agent specification. Before\nwriting the actual code, think through the logic and structure.\n\nThe plan MUST follow MANDATORY SCHEMA-FIRST APPROACH:\n\n📋 STEP 1 - PRISMA SCHEMA VERIFICATION (MOST CRITICAL):\n\n- EXAMINE the actual Prisma schema model definition\n- LIST EVERY field that exists in the model with exact types\n- EXPLICITLY NOTE fields that DO NOT exist (e.g., "Note: deleted_at field\n DOES NOT EXIST")\n- Common assumption errors to avoid: `deleted_at`, `created_by`,\n `updated_by`, `is_deleted`, `is_active`\n\n📋 STEP 2 - FIELD INVENTORY:\n\n- List ONLY fields confirmed to exist in schema\n- Example: "Verified fields in user model: id (String), email (String),\n created_at (DateTime), updated_at (DateTime)"\n- Example: "Fields that DO NOT exist: deleted_at, is_active, created_by"\n\n📋 STEP 3 - FIELD ACCESS STRATEGY:\n\n- Plan which verified fields will be used in select, update, create\n operations\n- For complex operations with type errors, plan to use separate queries\n instead of nested operations\n\n📋 STEP 4 - TYPE COMPATIBILITY:\n\n- Plan DateTime to ISO string conversions using toISOStringSafe()\n- Plan handling of nullable vs required fields\n\n📋 STEP 5 - IMPLEMENTATION APPROACH:\n\n- 🧩 Required business entities (e.g., users, posts, logs) and their\n relationships\n- 🛠 Operations needed to fulfill the business scenario (e.g., fetch,\n create, update) using ONLY verified fields\n- 🔄 Data dependencies between steps (e.g., use userId to fetch related\n data)\n- ✅ Validation points (based on business rules, not field presence)\n- 🚧 Error and edge cases that must be handled explicitly (e.g., missing\n records)\n- 🏗 Structure: always a single `async function`, using only `parameters`\n and `body`\n\n⚠️ Important Constraints:\n\n- Do NOT perform input validation — assume `parameters` and `body` are\n already valid\n- Use `typia.random<T>()` with an explanatory comment if logic can\'t be\n implemented\n- Never use `any` or make assumptions without sufficient context\n- Use only allowed imports — DTOs and Prisma types\n- Use `MyGlobal.prisma` for DB access and respect Prisma typing rules\n\n⚠️ TypeScript-specific considerations:\n\n- Do **not** use native `Date` objects directly; always convert all dates\n using `toISOStringSafe()` and brand as `string &\n tags.Format<\'date-time\'>`. This rule applies throughout all phases.\n- Prefer `satisfies` for DTO conformance instead of unsafe `as` casts\n- Avoid weak typing such as `any`, `as any`, or `satisfies any`\n- Use branded types (e.g., `tags.Format<\'uuid\'>`) and literal unions where\n applicable\n\n✅ Example Structure:\n\n```ts\nexport async function doSomething(\n user: { id: string & tags.Format<"uuid">; type: string },\n parameters: IParams,\n body: IBody\n): Promise<IReturn> {\n const { id } = parameters;\n const { name } = body;\n const user = await MyGlobal.prisma.users.findFirst({ where: { id } });\n if (!user) throw new Error("User not found");\n ...\n return result;\n}\n```\n\n🔍 Feasibility Analysis Requirement:\n\n- Before generating any code, the agent **must analyze** whether the\n requested implementation is **feasible based on the given Prisma schema\n and DTO types**.\n- If required fields or relationships are **missing or incompatible**, the\n plan should explicitly state that the implementation is **not\n possible** with the current schema/DTO, and no code should be generated\n in later stages.\n- In such cases, only a detailed **comment in the `implementationCode`**\n should be returned explaining why the logic cannot be implemented.\n\n🔥 Error Handling Plan:\n\nIf an error is expected or encountered during implementation:\n\n- Clearly document the error message(s) and TypeScript error codes.\n- Analyze the root cause (e.g., type mismatch, missing field, nullability\n issue).\n- Define concrete steps to resolve the issue, such as:\n\n - Adjusting type declarations or using Prisma-generated input types.\n - Using `?? undefined` to normalize nullable fields.\n - Applying correct relation handling (e.g., `connect` instead of direct\n foreign key assignment).\n - Ensuring all date fields use `.toISOString()` and proper branding.\n- Include fallback or workaround plans if a direct fix is complex.\n- If no error is present, simply omit this section.\n\nThis plan ensures the function will:\n\n- Respect the global architecture and coding conventions\n- Be safe, predictable, and aligned with upstream logic',
7745
+ type: "string"
7746
+ },
7747
+ prisma_schemas: {
7748
+ description: "Step 2.\n\nThe Prisma schema string that will be used to validate the implementation\nlogic in this file.\n\nYou must **explicitly specify only the relevant models and fields** from\nyour full schema that are used in this implementation. This ensures that\nyour logic is aligned with the expected database structure without\naccidentally introducing unrelated fields or models.\n\n⚠️ Important: The value of this field must be a valid Prisma schema\nstring containing only the models used in this code — not the entire\nschema.\n\nThis acts as a safeguard against:\n\n- Forgetting required fields used in this implementation\n- Including fields or models that are not actually used",
7647
7749
  type: "string"
7648
7750
  },
7649
7751
  draft_without_date_type: {
7650
- description: "✏️ Phase 1: Draft code\n\nThis is the initial drafting phase where you outline the basic skeleton\nof the function.\n\n- The function signature must correctly include `user`, `parameters`, and\n `body` arguments.\n- Design the main flow of business logic, such as DB fetches and early\n returns based on conditions.\n- Mark any incomplete or missing parts clearly with placeholders (e.g.,\n comments or temporary values).\n\n⚠️ Import rules:\n\n- Do NOT add any new import statements manually.\n- All necessary imports are provided globally or by the system\n automatically.\n- Writing import statements directly is prohibited and may cause compile\n errors. If import errors occur, check your environment configuration.\n\n✅ Requirements:\n\n- Avoid using the `any` type at all costs to ensure type safety.\n- Do NOT assign native `Date` objects directly; always convert dates using\n `.toISOString()` before assignment and apply proper branding.\n- Maintain a single-function structure; avoid using classes.",
7752
+ description: "Step 3.\n\nDraft WITHOUT using native Date type.\n\nThis is the initial drafting phase where you outline the basic skeleton\nof the function. CRITICAL: This draft must NEVER use the native Date\ntype.\n\n- The function signature must correctly include `user`, `parameters`, and\n `body` arguments.\n- Design the main flow of business logic, such as DB fetches and early\n returns based on conditions.\n- Mark any incomplete or missing parts clearly with placeholders (e.g.,\n comments or temporary values).\n\n⚠️ Import rules:\n\n- Do NOT add any new import statements manually.\n- All necessary imports are provided globally or by the system\n automatically.\n- Writing import statements directly is prohibited and may cause compile\n errors. If import errors occur, check your environment configuration.\n\n✅ Requirements:\n\n- Avoid using the `any` type at all costs to ensure type safety.\n- NEVER declare variables with `: Date` type\n- ALWAYS use `string & tags.Format<'date-time'>` for date values\n- Use `toISOStringSafe(new Date())` for current timestamps\n- Maintain a single-function structure; avoid using classes.",
7651
7753
  type: "string"
7652
7754
  },
7653
7755
  review: {
7654
- description: "🔍 Phase 2: Review code\n\nA refined version of the draft with improved completeness.\n\n- Replace placeholder logic with real DTO-conformant operations.\n- Add error handling (`throw new Error(...)`) where necessary.\n- Begin resolving structural or type mismatches.\n\n✅ Requirements:\n\n- Use `satisfies` to ensure DTO conformity.\n- Avoid unsafe `as` casts unless only for branding or literal narrowing.\n- Include `.toISOString()` for all date fields.\n- Ensure all object keys strictly conform to the expected type definitions.",
7756
+ description: "Step 4.\n\nA refined version of the draft with improved completeness.\n\n- Replace placeholder logic with real DTO-conformant operations.\n- Add error handling (`throw new Error(...)`) where necessary.\n- Begin resolving structural or type mismatches.\n\n✅ Requirements:\n\n- Use `satisfies` to ensure DTO conformity.\n- Avoid unsafe `as` casts unless only for branding or literal narrowing.\n- Use `toISOStringSafe()` for all date conversions (NOT `.toISOString()`).\n- Ensure all object keys strictly conform to the expected type definitions.",
7655
7757
  type: "string"
7656
7758
  },
7657
7759
  withCompilerFeedback: {
7658
- description: "🛠 Phase 3: With compiler feedback (optional)\n\nA correction pass that applies fixes for compile-time errors that arose\nduring the review stage (if any).\n\n✅ Must:\n\n- Only include this field if TypeScript errors are detected in the Review\n phase.\n- Resolve all TypeScript errors without using `as any`.\n- Provide safe brand casting only if required (e.g., `as string &\n tags.Format<'uuid'>`).",
7760
+ description: "🛠 Phase 4-2: With compiler feedback (optional)\n\nA correction pass that applies fixes for compile-time errors that arose\nduring the review stage (if any).\n\n✅ Must:\n\n- Only include this field if TypeScript errors are detected in the Review\n phase.\n- Resolve all TypeScript errors without using `as any`.\n- Provide safe brand casting only if required (e.g., `as string &\n tags.Format<'uuid'>`).",
7659
7761
  type: "string"
7660
7762
  },
7661
7763
  implementationCode: {
7662
- description: "✅ Phase 4: Final implementation\n\nThe complete and fully correct TypeScript function implementation.\n\n- Passes strict type checking without errors.\n- Uses only safe branding or literal type assertions.\n- Converts all date values properly to ISO string format.\n- Follows DTO structures using `satisfies`.\n- Avoids any weak typing such as `any`, `as any`, or `satisfies any`.\n- Uses only allowed imports (e.g., from `src/api/structures` and\n `MyGlobal.prisma`).\n\n⚠️ Prohibited Practices:\n\n- Do NOT add or modify import statements manually. Imports are handled\n automatically by the system.\n- Do NOT use `any`, `as any`, or `satisfies any` to bypass type checking.\n- Do NOT assign native `Date` objects directly; always convert them to ISO\n strings with `.toISOString()`.\n- Do NOT use unsafe type assertions except for safe branding or literal\n narrowing.\n- Do NOT write code outside the single async function structure (e.g., no\n classes or multiple functions).\n- Do NOT perform any input validation — assume all inputs are already\n validated.\n- Do NOT use dynamic import expressions (`import()`); all imports must be\n static.\n- Do NOT rely on DTO types for database update input; always use\n Prisma-generated input types.",
7764
+ description: 'Step 5.\n\nThe complete and fully correct TypeScript function implementation.\n\n- Passes strict type checking without errors.\n- Uses only safe branding or literal type assertions.\n- Converts all date values properly using `toISOStringSafe()`.\n- Follows DTO structures using `satisfies`.\n- Avoids any weak typing such as `any`, `as any`, or `satisfies any`.\n- Uses only allowed imports (e.g., from `../api/structures` and\n `MyGlobal.prisma`).\n- NEVER creates intermediate variables for Prisma operations.\n\n⚠️ Fallback Behavior:\n\n- If the `plan` phase explicitly determines that the requested logic is\n **not feasible** due to mismatches or limitations in the provided\n Prisma schema and DTO types:\n\n - The implementation must still return a syntactically valid function.\n - In such cases, return mock data using `typia.random<T>()` wrapped in the\n correct structure, along with a comment explaining the limitation.\n\n Example fallback:\n\n```ts\n // ⚠️ Cannot implement logic due to missing relation between A and B\n export async function someFunction(...) {\n return typia.random<IReturn>(); // mocked output\n }\n```\n\n⚠️ Prohibited Practices:\n\n- Do NOT add or modify import statements manually. Imports are handled\n automatically by the system.\n- Do NOT use `any`, `as any`, or `satisfies any` to bypass type checking.\n- Do NOT assign native `Date` objects directly; always convert them using\n `toISOStringSafe()`.\n- Do NOT use unsafe type assertions except for safe branding or literal\n narrowing.\n- Do NOT write code outside the single async function structure (e.g., no\n classes or multiple functions).\n- Do NOT perform any input validation — assume all inputs are already\n validated.\n- Do NOT use dynamic import expressions (`import()`); all imports must be\n static.\n- Do NOT use Prisma-generated input types; always use types from\n `../api/structures`.\n- Do NOT use `Object.prototype.hasOwnProperty.call()` for field checks.\n- Do NOT escape newlines or quotes in the implementation string (e.g., no\n `\\\\n` or `\\"`); use a properly formatted template literal with actual\n line breaks instead.',
7663
7765
  type: "string"
7664
7766
  }
7665
7767
  },
7666
- required: [ "filename", "plan", "draft_without_date_type", "review", "implementationCode" ]
7768
+ required: [ "filename", "plan", "prisma_schemas", "draft_without_date_type", "review", "implementationCode" ]
7667
7769
  }
7668
7770
  }
7669
7771
  },
7670
7772
  validate: (() => {
7671
7773
  const _io0 = input => "object" === typeof input.output && null !== input.output && _io1(input.output);
7672
- const _io1 = input => "string" === typeof input.filename && "string" === typeof input.plan && "string" === typeof input.draft_without_date_type && "string" === typeof input.review && (undefined === input.withCompilerFeedback || "string" === typeof input.withCompilerFeedback) && "string" === typeof input.implementationCode;
7774
+ const _io1 = input => "string" === typeof input.filename && (undefined === input.errorAnalysis || "string" === typeof input.errorAnalysis) && "string" === typeof input.plan && "string" === typeof input.prisma_schemas && "string" === typeof input.draft_without_date_type && "string" === typeof input.review && (undefined === input.withCompilerFeedback || "string" === typeof input.withCompilerFeedback) && "string" === typeof input.implementationCode;
7673
7775
  const _vo0 = (input, _path, _exceptionable = true) => [ ("object" === typeof input.output && null !== input.output || _report(_exceptionable, {
7674
7776
  path: _path + ".output",
7675
7777
  expected: "IAutoBeRealizeCoderApplication.RealizeCoderOutput",
@@ -7683,10 +7785,18 @@ const collection$4 = {
7683
7785
  path: _path + ".filename",
7684
7786
  expected: "string",
7685
7787
  value: input.filename
7788
+ }), undefined === input.errorAnalysis || "string" === typeof input.errorAnalysis || _report(_exceptionable, {
7789
+ path: _path + ".errorAnalysis",
7790
+ expected: "(string | undefined)",
7791
+ value: input.errorAnalysis
7686
7792
  }), "string" === typeof input.plan || _report(_exceptionable, {
7687
7793
  path: _path + ".plan",
7688
7794
  expected: "string",
7689
7795
  value: input.plan
7796
+ }), "string" === typeof input.prisma_schemas || _report(_exceptionable, {
7797
+ path: _path + ".prisma_schemas",
7798
+ expected: "string",
7799
+ value: input.prisma_schemas
7690
7800
  }), "string" === typeof input.draft_without_date_type || _report(_exceptionable, {
7691
7801
  path: _path + ".draft_without_date_type",
7692
7802
  expected: "string",
@@ -7744,7 +7854,7 @@ const collection$4 = {
7744
7854
  3.1: claude$4
7745
7855
  };
7746
7856
 
7747
- const orchestrateRealizePlanner = async (ctx, operation) => {
7857
+ const orchestrateRealizePlanner = async (ctx, operation, authorization) => {
7748
7858
  const testScenarios = ctx.state().test?.files.filter((el => el.scenario.endpoint.method === operation.method && el.scenario.endpoint.path === operation.path)) ?? [];
7749
7859
  return {
7750
7860
  description: operation.description,
@@ -7753,17 +7863,21 @@ const orchestrateRealizePlanner = async (ctx, operation) => {
7753
7863
  outputSchema: operation.responseBody,
7754
7864
  operationType: operation.method,
7755
7865
  testScenarios: testScenarios.map((el => el.scenario.draft)),
7756
- functionName: `${operation.method}_${operation.path.replaceAll("/", "_").replaceAll("-", "_").replaceAll("{", "$").replaceAll("}", "")}`
7866
+ functionName: `${operation.method}_${operation.path.replaceAll("/", "_").replaceAll("-", "_").replaceAll("{", "$").replaceAll("}", "")}`,
7867
+ decoratorEvent: authorization
7757
7868
  };
7758
7869
  };
7759
7870
 
7760
- async function writeCodeUntilCompilePassed(ctx, ops, retry = 3) {
7871
+ async function writeCodeUntilCompilePassed(ctx, ops, authorizations, retry) {
7872
+ const payloads = authorizations.map((el => ({
7873
+ [el.payload.location]: el.payload.content
7874
+ }))).reduce(((acc, cur) => Object.assign(acc, cur)), {});
7761
7875
  const files = Object.entries(await ctx.files({
7762
7876
  dbms: "postgres"
7763
7877
  })).filter((([key]) => key.startsWith("src"))).reduce(((acc, [filename, content]) => Object.assign(acc, {
7764
7878
  [filename]: content
7765
7879
  })), {});
7766
- const templateFiles = [ "src/providers/jwtDecode.ts", "src/MyGlobal.ts" ];
7880
+ const templateFiles = [ "src/MyGlobal.ts", "src/util/toISOStringSafe.ts" ];
7767
7881
  const entireCodes = {
7768
7882
  ...await loadTemplateFiles(templateFiles)
7769
7883
  };
@@ -7771,19 +7885,28 @@ async function writeCodeUntilCompilePassed(ctx, ops, retry = 3) {
7771
7885
  current: [],
7772
7886
  total: []
7773
7887
  };
7774
- ops = ops.filter(((_el, i) => i < 10));
7775
7888
  for (let i = 0; i < retry; i++) {
7776
7889
  const targets = ops.filter((op => shouldProcessOperation(op, diagnostics.current)));
7777
7890
  const metadata = {
7778
7891
  total: targets.length,
7779
7892
  count: 0
7780
7893
  };
7781
- const generatedCodes = await Promise.all(targets.map((op => process$1(ctx, metadata, op, diagnostics, entireCodes))));
7894
+ const generatedCodes = await Promise.all(targets.map((op => {
7895
+ const role = op.authorizationRole;
7896
+ const decorator = authorizations.find((el => el.role === role));
7897
+ return process$1(ctx, metadata, op, diagnostics, entireCodes, decorator);
7898
+ })));
7782
7899
  for (const c of generatedCodes) {
7783
7900
  if (c.type === "success") {
7784
7901
  entireCodes[c.result.filename] = {
7785
7902
  content: c.result.implementationCode,
7786
- result: "success"
7903
+ result: "success",
7904
+ endpoint: {
7905
+ method: c.op.method,
7906
+ path: c.op.path
7907
+ },
7908
+ location: c.result.filename,
7909
+ name: c.result.name
7787
7910
  };
7788
7911
  }
7789
7912
  }
@@ -7792,6 +7915,7 @@ async function writeCodeUntilCompilePassed(ctx, ops, retry = 3) {
7792
7915
  const compiler = await ctx.compiler();
7793
7916
  const compiled = await compiler.typescript.compile({
7794
7917
  files: {
7918
+ ...payloads,
7795
7919
  ...files,
7796
7920
  ...nodeModules,
7797
7921
  ...Object.entries(entireCodes).map((([filename, {content}]) => ({
@@ -7804,12 +7928,16 @@ async function writeCodeUntilCompilePassed(ctx, ops, retry = 3) {
7804
7928
  } else if (compiled.type === "failure") {
7805
7929
  diagnostics.current = compiled.diagnostics;
7806
7930
  diagnostics.total = [ ...diagnostics.total, ...compiled.diagnostics ];
7807
- console.log(JSON.stringify(diagnostics.current, null, 2), `현재 에러의 수: ${diagnostics.current.length}\n`, `현재 시도 수: ${i}`);
7931
+ console.log(JSON.stringify(diagnostics.current, null, 2), `현재 에러의 수: ${diagnostics.current.length}\n`, `현재 시도 수: ${i + 1}`);
7808
7932
  }
7809
7933
  }
7810
- return Object.entries(entireCodes).map((([filename, {content}]) => ({
7934
+ return Object.entries(entireCodes).filter((([filename]) => filename.startsWith("src/providers"))).map((([filename, value]) => ({
7811
7935
  filename,
7812
- implementationCode: content
7936
+ content: value.content,
7937
+ endpoint: value.endpoint,
7938
+ location: value.location,
7939
+ name: value.name,
7940
+ role: value.role
7813
7941
  })));
7814
7942
  }
7815
7943
 
@@ -7821,31 +7949,37 @@ async function loadTemplateFiles(templateFiles) {
7821
7949
  content: await readFile(path.join(templateBasePath, filePath), {
7822
7950
  encoding: "utf-8"
7823
7951
  }),
7824
- result: "success"
7952
+ result: "success",
7953
+ location: filePath,
7954
+ role: null
7825
7955
  };
7826
7956
  }
7827
7957
  return result;
7828
7958
  }
7829
7959
 
7830
- async function process$1(ctx, metadata, op, diagnostics, entireCodes) {
7831
- const result = await pipe(op, (op => orchestrateRealizePlanner(ctx, op)), (async p => {
7960
+ async function process$1(ctx, metadata, op, diagnostics, entireCodes, decorator) {
7961
+ const result = await pipe(op, (op => orchestrateRealizePlanner(ctx, op, decorator)), (async p => {
7832
7962
  const filename = `src/providers/${p.functionName}.ts`;
7833
7963
  const t = diagnostics.total.filter((el => el.file === filename));
7834
7964
  const d = diagnostics.current.filter((el => el.file === filename));
7835
7965
  const c = entireCodes[filename]?.content ?? null;
7836
7966
  return orchestrateRealizeCoder(ctx, op, p, c, t, d).then((res => {
7837
- if (res === FAILED) ; else {
7838
- ctx.dispatch({
7839
- type: "realizeProgress",
7840
- filename: res.filename,
7841
- content: res.implementationCode,
7842
- completed: ++metadata.count,
7843
- created_at: (new Date).toISOString(),
7844
- step: ctx.state().analyze?.step ?? 0,
7845
- total: metadata.total
7846
- });
7967
+ ctx.dispatch({
7968
+ type: "realizeProgress",
7969
+ filename,
7970
+ content: res === FAILED ? "FAILED" : res.implementationCode,
7971
+ completed: ++metadata.count,
7972
+ created_at: (new Date).toISOString(),
7973
+ step: ctx.state().analyze?.step ?? 0,
7974
+ total: metadata.total
7975
+ });
7976
+ if (res === FAILED) {
7977
+ return res;
7847
7978
  }
7848
- return res;
7979
+ return {
7980
+ ...res,
7981
+ name: p.functionName
7982
+ };
7849
7983
  }));
7850
7984
  }));
7851
7985
  if (result === FAILED) {
@@ -7885,9 +8019,28 @@ const orchestrateRealize = ctx => async props => {
7885
8019
  reason: props.reason,
7886
8020
  step: ctx.state().test?.step ?? 0
7887
8021
  });
7888
- await orchestrateRealizeDecorator(ctx);
7889
- await writeCodeUntilCompilePassed(ctx, ops, 3);
8022
+ const decorators = await orchestrateRealizeAuthorization(ctx);
8023
+ const files = await writeCodeUntilCompilePassed(ctx, ops, decorators, 2);
7890
8024
  const now = (new Date).toISOString();
8025
+ const realize = ctx.state().realize;
8026
+ if (realize !== null) {
8027
+ realize.functions = files;
8028
+ } else {
8029
+ const history = ctx.state().realize = {
8030
+ type: "realize",
8031
+ compiled: {
8032
+ type: "success"
8033
+ },
8034
+ functions: files,
8035
+ completed_at: now,
8036
+ created_at: now,
8037
+ id: v4(),
8038
+ reason: props.reason,
8039
+ step: ctx.state().analyze?.step ?? 0,
8040
+ authorizations: ctx.state().realize?.authorizations ?? []
8041
+ };
8042
+ ctx.histories().push(history);
8043
+ }
7891
8044
  ctx.dispatch({
7892
8045
  type: "assistantMessage",
7893
8046
  text: "Any codes can not be generated.",
@@ -7895,13 +8048,16 @@ const orchestrateRealize = ctx => async props => {
7895
8048
  });
7896
8049
  return {
7897
8050
  type: "realize",
7898
- compiled: 1,
7899
- files: {},
8051
+ compiled: {
8052
+ type: "success"
8053
+ },
8054
+ functions: files,
7900
8055
  completed_at: now,
7901
8056
  created_at: now,
7902
8057
  id: v4(),
7903
8058
  reason: props.reason,
7904
- step: ctx.state().test?.step ?? 0
8059
+ step: ctx.state().analyze?.step ?? 0,
8060
+ authorizations: ctx.state().realize?.authorizations ?? []
7905
8061
  };
7906
8062
  };
7907
8063
 
@@ -10629,7 +10785,8 @@ class AutoBeMockAgent extends AutoBeAgentBase {
10629
10785
  }
10630
10786
  const take = async type => {
10631
10787
  for (const s of this.getEventSnapshots(type)) {
10632
- await sleep_for(sleepMap[s.event.type] ?? 500);
10788
+ const time = sleepMap[s.event.type] ?? 500;
10789
+ await sleep_for(randint(time * .2, time * 1.8));
10633
10790
  void this.dispatch(s.event).catch((() => {}));
10634
10791
  this.token_usage_ = new AutoBeTokenUsage(s.tokenUsage);
10635
10792
  }