UNPKG

@autobe/agent

Version:

AI backend server code generator

341 lines 16.4 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.orchestrateInterfaceSchemaRename = orchestrateInterfaceSchemaRename; const __typia_transform__validateReport = __importStar(require("typia/lib/internal/_validateReport")); const __typia_transform__llmApplicationFinalize = __importStar(require("typia/lib/internal/_llmApplicationFinalize")); const utils_1 = require("@typia/utils"); const tstl_1 = require("tstl"); const typia_1 = __importDefault(require("typia")); const uuid_1 = require("uuid"); const divideArray_1 = require("../../utils/divideArray"); const executeCachedBatch_1 = require("../../utils/executeCachedBatch"); const transformInterfaceSchemaRenameHistory_1 = require("./histories/transformInterfaceSchemaRenameHistory"); const AutoBeJsonSchemaFactory_1 = require("./utils/AutoBeJsonSchemaFactory"); function orchestrateInterfaceSchemaRename(ctx_1, props_1) { return __awaiter(this, arguments, void 0, function* (ctx, props, capacity = 25) { const tableNames = ctx .state() .database.result.data.files.map((f) => f.models) .flat() .map((m) => m.name) .filter((m) => m.startsWith("mv_") === false); const entireTypeNames = new Set(); const insert = (key) => { if (key.startsWith("IPage")) key = key.replace("IPage", ""); key = key.split(".")[0]; entireTypeNames.add(key); }; for (const op of props.operations) { if (op.requestBody) insert(op.requestBody.typeName); if (op.responseBody) insert(op.responseBody.typeName); } for (const key of Object.keys(props.collection.schemas)) insert(key); const matrix = (0, divideArray_1.divideArray)({ array: Array.from(entireTypeNames), capacity, }); props.progress.total += matrix.length; const refactors = uniqueRefactors((yield (0, executeCachedBatch_1.executeCachedBatch)(ctx, matrix.map((typeNames) => (promptCacheKey) => divideAndConquer(ctx, { tableNames, typeNames, promptCacheKey, progress: props.progress, })))).flat()); orchestrateInterfaceSchemaRename.rename({ operations: props.operations, collection: props.collection, refactors, }); }); } (function (orchestrateInterfaceSchemaRename) { orchestrateInterfaceSchemaRename.rename = (props) => { var _a, _b; // REPLACE RULE const replace = (typeName) => { // exact match const exact = props.refactors.find((r) => r.from === typeName); if (exact !== undefined) return exact.to; // T.X match const prefix = props.refactors.find((r) => typeName.startsWith(`${r.from}.`)); if (prefix !== undefined) return typeName.replace(`${prefix.from}.`, `${prefix.to}.`); // IPageT exact match const pageExact = props.refactors.find((r) => typeName === `IPage${r.from}`); if (pageExact !== undefined) return `IPage${pageExact.to}`; // IPageT.X match const pagePrefix = props.refactors.find((r) => typeName.startsWith(`IPage${r.from}.`)); if (pagePrefix !== undefined) return typeName.replace(`IPage${pagePrefix.from}.`, `IPage${pagePrefix.to}.`); return null; }; // JSON SCHEMA REFERENCES const $refChangers = new Map(); for (const value of Object.values(props.collection.schemas)) utils_1.OpenApiTypeChecker.visit({ components: { schemas: props.collection.schemas }, schema: value, closure: (schema) => { if (utils_1.OpenApiTypeChecker.isReference(schema) === false) return; const x = schema.$ref.split("/").pop(); const y = replace(x); if (y !== null) $refChangers.set(schema, () => { schema.$ref = `#/components/schemas/${y}`; }); }, }); for (const fn of $refChangers.values()) fn(); // COMPONENT SCHEMAS for (const x of Object.keys(props.collection.schemas)) { const y = replace(x); if (y !== null && x !== y) { props.collection.set(y, props.collection.get(x)); props.collection.delete(x); } } // OPERATIONS for (const op of props.operations) { if (op.requestBody) op.requestBody.typeName = (_a = replace(op.requestBody.typeName)) !== null && _a !== void 0 ? _a : op.requestBody.typeName; if (op.responseBody) op.responseBody.typeName = (_b = replace(op.responseBody.typeName)) !== null && _b !== void 0 ? _b : op.responseBody.typeName; } }; })(orchestrateInterfaceSchemaRename || (exports.orchestrateInterfaceSchemaRename = orchestrateInterfaceSchemaRename = {})); const divideAndConquer = (ctx, props) => __awaiter(void 0, void 0, void 0, function* () { const counter = new tstl_1.Singleton(() => ++props.progress.completed); try { const pointer = { value: null, }; const { metric, tokenUsage } = yield ctx.conversate(Object.assign({ source: SOURCE, controller: createController((value) => (pointer.value = value)), enforceFunctionCall: true, promptCacheKey: props.promptCacheKey }, (0, transformInterfaceSchemaRenameHistory_1.transformInterfaceSchemaRenameHistory)(props))); if (pointer.value === null) { counter.get(); return []; } pointer.value.refactors = uniqueRefactors(pointer.value.refactors); ctx.dispatch({ type: SOURCE, id: (0, uuid_1.v7)(), refactors: pointer.value.refactors, total: props.progress.total, completed: counter.get(), metric, tokenUsage, created_at: new Date().toISOString(), }); return pointer.value.refactors; } catch (_a) { counter.get(); return []; } }); const uniqueRefactors = (refactors) => { // Remove self-references (A->A) refactors = refactors.filter((r) => r.from !== r.to); // Remove presets refactors = refactors.filter((r) => AutoBeJsonSchemaFactory_1.AutoBeJsonSchemaFactory.DEFAULT_SCHEMAS[r.from] === undefined); // Remove duplicates (keep the first occurrence) refactors = Array.from(new Map(refactors.map((r) => [r.from, r])).values()); // Build adjacency map: from -> to const renameMap = new Map(); for (const r of refactors) { renameMap.set(r.from, r.to); } // Resolve transitive chains: A->B, B->C becomes A->C const resolveChain = (from) => { const visited = new Set(); let current = from; while (renameMap.has(current)) { // Cycle detection: A->B, B->C, C->A if (visited.has(current)) { // Cycle detected, keep the last valid mapping before cycle return current; } visited.add(current); current = renameMap.get(current); } return current; }; // Build final refactor list with resolved chains const resolved = new Map(); for (const from of renameMap.keys()) { const finalTo = resolveChain(from); // Only include if actually changes if (from !== finalTo) { resolved.set(from, { from, to: finalTo, }); } } return Array.from(resolved.values()); }; const createController = (build) => { const application = __typia_transform__llmApplicationFinalize._llmApplicationFinalize({ functions: [ { name: "rename", parameters: { description: "Current Type: {@link IAutoBeInterfaceSchemaRenameApplication.IProps}", type: "object", properties: { refactors: { description: "Refactoring operations for incorrectly named DTO types. Only include\nviolations. Orchestrator auto-handles variants, page types, and $ref\nupdates.", type: "array", items: { $ref: "#/$defs/AutoBeInterfaceSchemaRefactor" } } }, required: [ "refactors" ], additionalProperties: false, $defs: { AutoBeInterfaceSchemaRefactor: { description: "DTO type name refactoring operation.\n\nFixes names violating the rule: ALL words from the Prisma table name MUST be\npreserved. The orchestrator automatically renames all variants (.ICreate,\n.IUpdate, .ISummary, IPage*).\n\nCommon violations: `ISale` \u2192 `IShoppingSale` (prefix omission), `IBbsComment`\n\u2192 `IBbsArticleComment` (intermediate word omission).", type: "object", properties: { from: { description: "Current INCORRECT base type name (e.g., \"ISale\" when table is\n\"shopping_sales\").", type: "string" }, to: { description: "CORRECT base type name preserving ALL table words as PascalCase with \"I\"\nprefix (e.g., \"IShoppingSale\").", type: "string" } }, required: [ "from", "to" ] } } }, description: "Identify DTO type names that violate the naming rule: ALL words from the\ndatabase table name MUST be preserved in the DTO type name.", validate: (() => { const _io0 = input => Array.isArray(input.refactors) && input.refactors.every(elem => "object" === typeof elem && null !== elem && _io1(elem)); const _io1 = input => "string" === typeof input.from && "string" === typeof input.to; const _vo0 = (input, _path, _exceptionable = true) => [(Array.isArray(input.refactors) || _report(_exceptionable, { path: _path + ".refactors", expected: "Array<AutoBeInterfaceSchemaRefactor>", value: input.refactors })) && input.refactors.map((elem, _index2) => ("object" === typeof elem && null !== elem || _report(_exceptionable, { path: _path + ".refactors[" + _index2 + "]", expected: "AutoBeInterfaceSchemaRefactor", value: elem })) && _vo1(elem, _path + ".refactors[" + _index2 + "]", true && _exceptionable) || _report(_exceptionable, { path: _path + ".refactors[" + _index2 + "]", expected: "AutoBeInterfaceSchemaRefactor", value: elem })).every(flag => flag) || _report(_exceptionable, { path: _path + ".refactors", expected: "Array<AutoBeInterfaceSchemaRefactor>", value: input.refactors })].every(flag => flag); const _vo1 = (input, _path, _exceptionable = true) => ["string" === typeof input.from || _report(_exceptionable, { path: _path + ".from", expected: "string", value: input.from }), "string" === typeof input.to || _report(_exceptionable, { path: _path + ".to", expected: "string", value: input.to })].every(flag => flag); const __is = input => "object" === typeof input && null !== input && _io0(input); let errors; let _report; return input => { if (false === __is(input)) { errors = []; _report = __typia_transform__validateReport._validateReport(errors); ((input, _path, _exceptionable = true) => ("object" === typeof input && null !== input || _report(true, { path: _path + "", expected: "IAutoBeInterfaceSchemaRenameApplication.IProps", value: input })) && _vo0(input, _path + "", true) || _report(true, { path: _path + "", expected: "IAutoBeInterfaceSchemaRenameApplication.IProps", value: input }))(input, "$input", true); const success = 0 === errors.length; return success ? { success, data: input } : { success, errors, data: input }; } return { success: true, data: input }; }; })() } ] }); return { protocol: "class", name: SOURCE, application, execute: { rename: (props) => { build(props); }, }, }; }; const SOURCE = "interfaceSchemaRename"; //# sourceMappingURL=orchestrateInterfaceSchemaRename.js.map