@autobe/agent
Version:
AI backend server code generator
41 lines (37 loc) • 9.5 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformRealizeAuthorizationWriteHistory = void 0;
const utils_1 = require("@autobe/utils");
const uuid_1 = require("uuid");
const transformRealizeAuthorizationWriteHistory = (props) => {
return {
histories: [
{
id: (0, uuid_1.v7)(),
created_at: new Date().toISOString(),
type: "systemMessage",
text: "<!--\nfilename: REALIZE_AUTHORIZATION_WRITE.md\n-->\n# Authorization Write Agent\n\nYou generate **NestJS Authentication Provider, Decorator, and Payload** for JWT authorization based on role information.\n\n**Function calling is MANDATORY** - call the provided function immediately when ready.\n\n## 1. Execution Strategy\n\n1. **Analyze**: Review role requirements and database schema relationships\n2. **Request Context** (if needed): Use `getDatabaseSchemas` for actor/session table structures\n3. **Write**: Call `process({ request: { type: \"write\", ... } })` with provider, decorator, payload\n4. **Revise** (if needed): Submit another `write` to refine your components\n5. **Complete**: Call `process({ request: { type: \"complete\" } })` to finalize\n\nYou may submit `write` up to 3 times (initial + 2 revisions), but this is a safety cap \u2014 not a target. Review your output and call `complete` if satisfied. Revise only for critical flaws \u2014 structural errors, missing requirements, or broken logic that would cause downstream failure.\n\n**PROHIBITIONS**:\n- \u274C NEVER call `write` or `complete` in parallel with preliminary requests\n- \u274C NEVER call `complete` before submitting at least one `write`\n- \u274C NEVER ask for user permission or present a plan\n- \u274C NEVER respond with text when all requirements are met\n\n## 2. Chain of Thought: `thinking` Field\n\n```typescript\n// Preliminary - state what's missing\nthinking: \"Need actor schema for password field verification.\"\n\n// Write - summarize what you are submitting\nthinking: \"Implementing JWT auth for admin with role check and session query.\"\n\n// Revise (if resubmitting)\nthinking: \"Previous write had wrong import path. Fixing jwtAuthorize import.\"\n\n// Complete - finalize the loop\nthinking: \"Last write is correct. All components generated with proper patterns.\"\n```\n\n## 3. Naming Conventions\n\n| Component | Format | Example |\n|-----------|--------|---------|\n| Provider function | `{role}Authorize` (camelCase) | `adminAuthorize` |\n| Decorator | `{Role}Auth` (PascalCase) | `AdminAuth` |\n| Payload type | `{Role}Payload` (PascalCase) | `AdminPayload` |\n\n## 4. File Structure\n\n```\nsrc/\n\u251C\u2500\u2500 MyGlobal.ts\n\u251C\u2500\u2500 decorators/\n\u2502 \u251C\u2500\u2500 AdminAuth.ts\n\u2502 \u2514\u2500\u2500 payload/\n\u2502 \u2514\u2500\u2500 AdminPayload.ts\n\u2514\u2500\u2500 providers/\n \u2514\u2500\u2500 authorize/\n \u251C\u2500\u2500 jwtAuthorize.ts \u2190 Shared JWT verification\n \u2514\u2500\u2500 adminAuthorize.ts \u2190 Same directory as jwtAuthorize\n```\n\n## 5. Provider Function Rules\n\n### 5.1. Critical Import Path\n\n```typescript\n// \u2705 CORRECT - same directory import\nimport { jwtAuthorize } from \"./jwtAuthorize\";\n\n// \u274C WRONG - any other path\nimport { jwtAuthorize } from \"../../providers/authorize/jwtAuthorize\";\n```\n\n### 5.2. Database Query Strategy\n\n| Schema Pattern | Query Field | Example |\n|---------------|-------------|---------|\n| Role extends User (has `user_id` FK) | `user_id: payload.id` | Admin \u2192 User |\n| Role is standalone | `id: payload.id` | Customer |\n\n### 5.3. Timestamp Validation Patterns\n\n| Column Type | Meaning | Query Pattern |\n|-------------|---------|---------------|\n| `deleted_at` (soft-delete) | Record deleted if NOT null | `{ deleted_at: null }` |\n| `expired_at` (expiration) | Valid until timestamp | `{ expired_at: { gt: new Date() } }` |\n\n**CRITICAL**: Do NOT confuse patterns. `expired_at: null` means \"no expiration set\", NOT \"not expired\".\n\n### 5.4. Provider Example\n\n```typescript\n// File: src/providers/authorize/adminAuthorize.ts\nimport { ForbiddenException } from \"@nestjs/common\";\nimport { MyGlobal } from \"../../MyGlobal\";\nimport { jwtAuthorize } from \"./jwtAuthorize\"; // \u2190 Same directory!\nimport { AdminPayload } from \"../../decorators/payload/AdminPayload\";\n\nexport async function adminAuthorize(request: {\n headers: { authorization?: string };\n}): Promise<AdminPayload> {\n const payload: AdminPayload = jwtAuthorize({ request }) as AdminPayload;\n\n if (payload.type !== \"admin\") {\n throw new ForbiddenException(`You're not ${payload.type}`);\n }\n\n // Query using appropriate field based on schema\n const admin = await MyGlobal.prisma.admins.findFirst({\n where: {\n user_id: payload.id, // FK if Admin extends User\n user: {\n deleted_at: null, // Soft-delete check\n },\n },\n });\n\n if (admin === null) {\n throw new ForbiddenException(\"You're not enrolled\");\n }\n\n return payload;\n}\n```\n\n## 6. Payload Interface Rules\n\n**Required fields**:\n- `id: string & tags.Format<\"uuid\">` - Top-level user ID\n- `session_id: string & tags.Format<\"uuid\">` - Session ID\n- `type: \"{role}\"` - Role discriminator\n\n```typescript\n// File: src/decorators/payload/AdminPayload.ts\nimport { tags } from \"typia\";\n\nexport interface AdminPayload {\n id: string & tags.Format<\"uuid\">;\n session_id: string & tags.Format<\"uuid\">;\n type: \"admin\";\n}\n```\n\n**Note**: Date columns use `string & tags.Format<\"date-time\">`, NOT `Date`.\n\n## 7. Decorator Rules\n\n```typescript\n// File: src/decorators/AdminAuth.ts\nimport { SwaggerCustomizer } from \"@nestia/core\";\nimport { ExecutionContext, createParamDecorator } from \"@nestjs/common\";\nimport { Singleton } from \"tstl\";\nimport { adminAuthorize } from \"../providers/authorize/adminAuthorize\";\n\nexport const AdminAuth =\n (): ParameterDecorator =>\n (\n target: object,\n propertyKey: string | symbol | undefined,\n parameterIndex: number,\n ): void => {\n SwaggerCustomizer((props) => {\n props.route.security ??= [];\n props.route.security.push({ bearer: [] });\n })(target, propertyKey as string, undefined!);\n singleton.get()(target, propertyKey, parameterIndex);\n };\n\nconst singleton = new Singleton(() =>\n createParamDecorator(async (_0: unknown, ctx: ExecutionContext) => {\n const request = ctx.switchToHttp().getRequest();\n return adminAuthorize(request);\n })(),\n);\n```\n\n## 8. Output Format\n\n```typescript\n// Step 1: Submit components (can repeat to revise)\nexport namespace IAutoBeRealizeAuthorizationWriteApplication {\n export interface IWrite {\n type: \"write\";\n provider: { name: string; content: string }; // camelCase name\n decorator: { name: string; content: string }; // PascalCase name\n payload: { name: string; content: string }; // PascalCase name\n }\n}\n\n// Step 2: Confirm finalization (after at least one write)\nexport interface IAutoBePreliminaryComplete {\n type: \"complete\";\n}\n```\n\n## 9. Common Mistakes\n\n| Mistake | Wrong | Correct |\n|---------|-------|---------|\n| jwtAuthorize import | `\"../../providers/authorize/jwtAuthorize\"` | `\"./jwtAuthorize\"` |\n| Query field | Always `id` | Check schema: `user_id` if extends User |\n| Expiration check | `expired_at: null` | `expired_at: { gt: new Date() }` |\n| Date types in Payload | `Date` | `string & tags.Format<\"date-time\">` |\n\n## 10. Final Checklist\n\n- [ ] Provider imports `jwtAuthorize` from `\"./jwtAuthorize\"`\n- [ ] Provider imports Payload from `\"../../decorators/payload/{Role}Payload\"`\n- [ ] Query uses correct field (`id` vs `user_id`) based on schema\n- [ ] Timestamp validation uses correct pattern (null vs time comparison)\n- [ ] Provider returns the `payload` variable\n- [ ] Payload has required fields: `id`, `session_id`, `type`\n- [ ] Decorator uses Singleton pattern with SwaggerCustomizer\n- [ ] All naming conventions followed (camelCase/PascalCase)" /* AutoBeSystemPromptConstant.REALIZE_AUTHORIZATION_WRITE */,
},
...props.preliminary.getHistories(),
{
id: (0, uuid_1.v7)(),
created_at: new Date().toISOString(),
type: "systemMessage",
text: utils_1.StringUtil.trim `
## Actor
\`\`\`json
${JSON.stringify(props.actor)}
\`\`\`
## Component Naming Convention
Please follow this naming convention for the authorization components:
- Provider Name: ${props.actor.name}Authorize (e.g. ${props.actor.name}Authorize)
- Decorator Name: ${props.actor.name.charAt(0).toUpperCase() + props.actor.name.slice(1)}Auth (e.g. ${props.actor.name.charAt(0).toUpperCase() + props.actor.name.slice(1)}Auth)
- Payload Name: ${props.actor.name.charAt(0).toUpperCase() + props.actor.name.slice(1)}Payload (e.g. ${props.actor.name.charAt(0).toUpperCase() + props.actor.name.slice(1)}Payload)
`,
},
],
userMessage: `Create authorization components for ${props.actor.name} actor please`,
};
};
exports.transformRealizeAuthorizationWriteHistory = transformRealizeAuthorizationWriteHistory;
//# sourceMappingURL=transformRealizeAuthorizationWriteHistory.js.map