@inkeep/agents-cli 0.59.2 → 0.59.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agents-cli/package.js +1 -1
- package/dist/commands/pull-v4/collector-common.js +128 -0
- package/dist/commands/pull-v4/collector-common.js.map +1 -0
- package/dist/commands/pull-v4/collector-reference-helpers.js +323 -0
- package/dist/commands/pull-v4/collector-reference-helpers.js.map +1 -0
- package/dist/commands/pull-v4/component-parser.js +2 -1
- package/dist/commands/pull-v4/component-parser.js.map +1 -1
- package/dist/commands/pull-v4/file-scope.js +43 -0
- package/dist/commands/pull-v4/file-scope.js.map +1 -0
- package/dist/commands/pull-v4/generation-resolver.js +305 -0
- package/dist/commands/pull-v4/generation-resolver.js.map +1 -0
- package/dist/commands/pull-v4/generation-types.js +56 -0
- package/dist/commands/pull-v4/generation-types.js.map +1 -0
- package/dist/commands/pull-v4/generators/agent-generator.helpers.js +4 -10
- package/dist/commands/pull-v4/generators/agent-generator.helpers.js.map +1 -1
- package/dist/commands/pull-v4/generators/agent-generator.js +154 -81
- package/dist/commands/pull-v4/generators/agent-generator.js.map +1 -1
- package/dist/commands/pull-v4/generators/artifact-component-generator.js +48 -27
- package/dist/commands/pull-v4/generators/artifact-component-generator.js.map +1 -1
- package/dist/commands/pull-v4/generators/context-config-generator.js +147 -129
- package/dist/commands/pull-v4/generators/context-config-generator.js.map +1 -1
- package/dist/commands/pull-v4/generators/credential-generator.js +36 -14
- package/dist/commands/pull-v4/generators/credential-generator.js.map +1 -1
- package/dist/commands/pull-v4/generators/data-component-generator.js +55 -19
- package/dist/commands/pull-v4/generators/data-component-generator.js.map +1 -1
- package/dist/commands/pull-v4/generators/environment-generator.js +29 -33
- package/dist/commands/pull-v4/generators/environment-generator.js.map +1 -1
- package/dist/commands/pull-v4/generators/environment-settings-generator.js +57 -0
- package/dist/commands/pull-v4/generators/environment-settings-generator.js.map +1 -0
- package/dist/commands/pull-v4/generators/external-agent-generator.js +51 -23
- package/dist/commands/pull-v4/generators/external-agent-generator.js.map +1 -1
- package/dist/commands/pull-v4/generators/function-tool-generator.js +50 -14
- package/dist/commands/pull-v4/generators/function-tool-generator.js.map +1 -1
- package/dist/commands/pull-v4/generators/helpers/agent.js +129 -0
- package/dist/commands/pull-v4/generators/helpers/agent.js.map +1 -0
- package/dist/commands/pull-v4/generators/helpers/sub-agent.js +65 -0
- package/dist/commands/pull-v4/generators/helpers/sub-agent.js.map +1 -0
- package/dist/commands/pull-v4/generators/index.js +38 -0
- package/dist/commands/pull-v4/generators/index.js.map +1 -0
- package/dist/commands/pull-v4/generators/mcp-tool-generator.js +48 -27
- package/dist/commands/pull-v4/generators/mcp-tool-generator.js.map +1 -1
- package/dist/commands/pull-v4/generators/project-generator.js +144 -110
- package/dist/commands/pull-v4/generators/project-generator.js.map +1 -1
- package/dist/commands/pull-v4/generators/scheduled-trigger-generator.js +66 -0
- package/dist/commands/pull-v4/generators/scheduled-trigger-generator.js.map +1 -0
- package/dist/commands/pull-v4/generators/status-component-generator.js +55 -20
- package/dist/commands/pull-v4/generators/status-component-generator.js.map +1 -1
- package/dist/commands/pull-v4/generators/sub-agent-generator.helpers.js +4 -1
- package/dist/commands/pull-v4/generators/sub-agent-generator.helpers.js.map +1 -1
- package/dist/commands/pull-v4/generators/sub-agent-generator.js +282 -166
- package/dist/commands/pull-v4/generators/sub-agent-generator.js.map +1 -1
- package/dist/commands/pull-v4/generators/trigger-generator.js +62 -27
- package/dist/commands/pull-v4/generators/trigger-generator.js.map +1 -1
- package/dist/commands/pull-v4/import-plan.js +40 -0
- package/dist/commands/pull-v4/import-plan.js.map +1 -0
- package/dist/commands/pull-v4/introspect/index.js +11 -7
- package/dist/commands/pull-v4/introspect/index.js.map +1 -1
- package/dist/commands/pull-v4/introspect-generator.js +15 -1218
- package/dist/commands/pull-v4/introspect-generator.js.map +1 -1
- package/dist/commands/pull-v4/module-merge.js +14 -5
- package/dist/commands/pull-v4/module-merge.js.map +1 -1
- package/dist/commands/pull-v4/reference-resolution.js +111 -0
- package/dist/commands/pull-v4/reference-resolution.js.map +1 -0
- package/dist/commands/pull-v4/simple-factory-generator.js +54 -0
- package/dist/commands/pull-v4/simple-factory-generator.js.map +1 -0
- package/dist/commands/pull-v4/{generators/skill-generator.js → skill.js} +18 -6
- package/dist/commands/pull-v4/skill.js.map +1 -0
- package/dist/commands/pull-v4/typescript-file-writer.js +78 -0
- package/dist/commands/pull-v4/typescript-file-writer.js.map +1 -0
- package/dist/commands/pull-v4/utils/code-values.js +64 -0
- package/dist/commands/pull-v4/utils/code-values.js.map +1 -0
- package/dist/commands/pull-v4/utils/factory-writer.js +128 -0
- package/dist/commands/pull-v4/utils/factory-writer.js.map +1 -0
- package/dist/commands/pull-v4/utils/index.js +8 -0
- package/dist/commands/pull-v4/utils/naming.js +74 -0
- package/dist/commands/pull-v4/utils/naming.js.map +1 -0
- package/dist/commands/pull-v4/utils/schema-rendering.js +20 -0
- package/dist/commands/pull-v4/utils/schema-rendering.js.map +1 -0
- package/dist/commands/pull-v4/utils/shared.js +18 -0
- package/dist/commands/pull-v4/utils/shared.js.map +1 -0
- package/dist/commands/pull-v4/utils/templates.js +58 -0
- package/dist/commands/pull-v4/utils/templates.js.map +1 -0
- package/package.json +4 -4
- package/dist/commands/pull-v4/generators/skill-generator.js.map +0 -1
- package/dist/commands/pull-v4/scheduled-trigger-generator.js +0 -38
- package/dist/commands/pull-v4/scheduled-trigger-generator.js.map +0 -1
- package/dist/commands/pull-v4/utils.js +0 -320
- package/dist/commands/pull-v4/utils.js.map +0 -1
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { buildComponentFileName, createUniqueReferenceName, resolveNonCollidingName, toCamelCase } from "./utils/naming.js";
|
|
2
|
+
import "./utils/index.js";
|
|
3
|
+
|
|
4
|
+
//#region src/commands/pull-v4/reference-resolution.ts
|
|
5
|
+
function resolveReferenceBinding(input, options) {
|
|
6
|
+
const [binding] = resolveReferenceBindings([input], options);
|
|
7
|
+
if (!binding) throw new Error(`Failed to resolve reference binding for ${input.id}`);
|
|
8
|
+
return binding;
|
|
9
|
+
}
|
|
10
|
+
function resolveReferenceBindings(inputs, options) {
|
|
11
|
+
const dedupedInputs = dedupeReferenceInputs(inputs);
|
|
12
|
+
const importNameCounts = /* @__PURE__ */ new Map();
|
|
13
|
+
for (const input of dedupedInputs) importNameCounts.set(input.importName, (importNameCounts.get(input.importName) ?? 0) + 1);
|
|
14
|
+
return dedupedInputs.map((input) => {
|
|
15
|
+
if (input.local) {
|
|
16
|
+
options.reservedNames.add(input.importName);
|
|
17
|
+
return {
|
|
18
|
+
id: input.id,
|
|
19
|
+
importName: input.importName,
|
|
20
|
+
localName: input.importName,
|
|
21
|
+
modulePath: normalizeModulePath(input.modulePath),
|
|
22
|
+
isLocal: true
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
const collisionStrategy = input.collisionStrategy ?? options.collisionStrategy ?? "descriptive";
|
|
26
|
+
const shouldUseNumeric = collisionStrategy === "numeric" || collisionStrategy === "numeric-for-duplicates" && (importNameCounts.get(input.importName) ?? 0) > 1;
|
|
27
|
+
const conflictSuffix = input.conflictSuffix ?? options.conflictSuffix ?? "Reference";
|
|
28
|
+
const localName = shouldUseNumeric ? resolveNonCollidingName(input.importName, options.reservedNames) : createUniqueReferenceName(input.importName, options.reservedNames, conflictSuffix);
|
|
29
|
+
return {
|
|
30
|
+
id: input.id,
|
|
31
|
+
importName: input.importName,
|
|
32
|
+
localName,
|
|
33
|
+
modulePath: normalizeModulePath(input.modulePath),
|
|
34
|
+
isLocal: false,
|
|
35
|
+
namedImport: input.importName === localName ? input.importName : {
|
|
36
|
+
name: input.importName,
|
|
37
|
+
alias: localName
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
function resolveReferenceBindingsFromIds(options) {
|
|
43
|
+
const defaultImportName = options.defaultImportName ?? toCamelCase;
|
|
44
|
+
const defaultModulePath = options.defaultModulePath ?? ((id) => buildComponentFileName(id));
|
|
45
|
+
const inputs = [];
|
|
46
|
+
const seenIds = /* @__PURE__ */ new Set();
|
|
47
|
+
for (const id of options.ids) {
|
|
48
|
+
if (!id || seenIds.has(id)) continue;
|
|
49
|
+
seenIds.add(id);
|
|
50
|
+
const referenceOverride = options.referenceOverrides?.[id];
|
|
51
|
+
const importName = typeof referenceOverride === "string" ? referenceOverride : referenceOverride?.name ?? defaultImportName(id);
|
|
52
|
+
const modulePath = options.referencePathOverrides?.[id] ?? defaultModulePath(id);
|
|
53
|
+
inputs.push({
|
|
54
|
+
id,
|
|
55
|
+
importName,
|
|
56
|
+
modulePath,
|
|
57
|
+
local: typeof referenceOverride === "object" && referenceOverride?.local === true,
|
|
58
|
+
conflictSuffix: options.conflictSuffix,
|
|
59
|
+
collisionStrategy: options.collisionStrategy
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
return resolveReferenceBindings(inputs, {
|
|
63
|
+
reservedNames: options.reservedNames,
|
|
64
|
+
conflictSuffix: options.conflictSuffix,
|
|
65
|
+
collisionStrategy: options.collisionStrategy
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
function addResolvedReferenceImports(sourceFile, references, resolveModuleSpecifier) {
|
|
69
|
+
const namedImportsByModuleSpecifier = /* @__PURE__ */ new Map();
|
|
70
|
+
for (const reference of references) {
|
|
71
|
+
if (!reference.namedImport) continue;
|
|
72
|
+
const moduleSpecifier = resolveModuleSpecifier(reference);
|
|
73
|
+
const namedImports = namedImportsByModuleSpecifier.get(moduleSpecifier) ?? [];
|
|
74
|
+
namedImports.push(reference.namedImport);
|
|
75
|
+
namedImportsByModuleSpecifier.set(moduleSpecifier, namedImports);
|
|
76
|
+
}
|
|
77
|
+
for (const [moduleSpecifier, namedImports] of namedImportsByModuleSpecifier) sourceFile.addImportDeclaration({
|
|
78
|
+
namedImports,
|
|
79
|
+
moduleSpecifier
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
function toReferenceNameMap(references) {
|
|
83
|
+
return new Map([...references].map((reference) => {
|
|
84
|
+
return [reference.id, reference.localName];
|
|
85
|
+
}));
|
|
86
|
+
}
|
|
87
|
+
function toReferenceNameRecord(references) {
|
|
88
|
+
return Object.fromEntries([...references].map((reference) => {
|
|
89
|
+
return [reference.id, reference.localName];
|
|
90
|
+
}));
|
|
91
|
+
}
|
|
92
|
+
function toReferenceNames(references) {
|
|
93
|
+
return [...references].map((reference) => reference.localName);
|
|
94
|
+
}
|
|
95
|
+
function dedupeReferenceInputs(inputs) {
|
|
96
|
+
const dedupedInputs = [];
|
|
97
|
+
const seenIds = /* @__PURE__ */ new Set();
|
|
98
|
+
for (const input of inputs) {
|
|
99
|
+
if (seenIds.has(input.id)) continue;
|
|
100
|
+
seenIds.add(input.id);
|
|
101
|
+
dedupedInputs.push(input);
|
|
102
|
+
}
|
|
103
|
+
return dedupedInputs;
|
|
104
|
+
}
|
|
105
|
+
function normalizeModulePath(modulePath) {
|
|
106
|
+
return modulePath.replace(/\.[^.]+$/, "");
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
//#endregion
|
|
110
|
+
export { addResolvedReferenceImports, resolveReferenceBinding, resolveReferenceBindings, resolveReferenceBindingsFromIds, toReferenceNameMap, toReferenceNameRecord, toReferenceNames };
|
|
111
|
+
//# sourceMappingURL=reference-resolution.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reference-resolution.js","names":[],"sources":["../../../src/commands/pull-v4/reference-resolution.ts"],"sourcesContent":["import type { SourceFile } from 'ts-morph';\nimport {\n buildComponentFileName,\n createUniqueReferenceName,\n resolveNonCollidingName,\n toCamelCase,\n} from './utils';\n\nexport type CollisionStrategy = 'descriptive' | 'numeric' | 'numeric-for-duplicates';\n\nexport interface NamedReferenceOverride {\n name: string;\n local?: boolean;\n}\n\nexport type ReferenceOverride = string | NamedReferenceOverride;\n\nexport interface ReferenceResolutionInput {\n id: string;\n importName: string;\n modulePath: string;\n local?: boolean;\n conflictSuffix?: string;\n collisionStrategy?: CollisionStrategy;\n}\n\nexport interface ResolvedReferenceBinding {\n id: string;\n importName: string;\n localName: string;\n modulePath: string;\n isLocal: boolean;\n namedImport?: string | { name: string; alias: string };\n}\n\nexport function resolveReferenceBinding(\n input: ReferenceResolutionInput,\n options: {\n reservedNames: Set<string>;\n conflictSuffix?: string;\n collisionStrategy?: CollisionStrategy;\n }\n): ResolvedReferenceBinding {\n const [binding] = resolveReferenceBindings([input], options);\n if (!binding) {\n throw new Error(`Failed to resolve reference binding for ${input.id}`);\n }\n return binding;\n}\n\nexport function resolveReferenceBindings(\n inputs: Iterable<ReferenceResolutionInput>,\n options: {\n reservedNames: Set<string>;\n conflictSuffix?: string;\n collisionStrategy?: CollisionStrategy;\n }\n): ResolvedReferenceBinding[] {\n const dedupedInputs = dedupeReferenceInputs(inputs);\n const importNameCounts = new Map<string, number>();\n\n for (const input of dedupedInputs) {\n importNameCounts.set(input.importName, (importNameCounts.get(input.importName) ?? 0) + 1);\n }\n\n return dedupedInputs.map((input) => {\n if (input.local) {\n options.reservedNames.add(input.importName);\n return {\n id: input.id,\n importName: input.importName,\n localName: input.importName,\n modulePath: normalizeModulePath(input.modulePath),\n isLocal: true,\n };\n }\n\n const collisionStrategy = input.collisionStrategy ?? options.collisionStrategy ?? 'descriptive';\n const shouldUseNumeric =\n collisionStrategy === 'numeric' ||\n (collisionStrategy === 'numeric-for-duplicates' &&\n (importNameCounts.get(input.importName) ?? 0) > 1);\n const conflictSuffix = input.conflictSuffix ?? options.conflictSuffix ?? 'Reference';\n const localName = shouldUseNumeric\n ? resolveNonCollidingName(input.importName, options.reservedNames)\n : createUniqueReferenceName(input.importName, options.reservedNames, conflictSuffix);\n\n return {\n id: input.id,\n importName: input.importName,\n localName,\n modulePath: normalizeModulePath(input.modulePath),\n isLocal: false,\n namedImport:\n input.importName === localName\n ? input.importName\n : { name: input.importName, alias: localName },\n };\n });\n}\n\nexport function resolveReferenceBindingsFromIds(options: {\n ids: Iterable<string>;\n reservedNames: Set<string>;\n conflictSuffix: string;\n collisionStrategy?: CollisionStrategy;\n referenceOverrides?: Record<string, ReferenceOverride>;\n referencePathOverrides?: Record<string, string>;\n defaultImportName?: (id: string) => string;\n defaultModulePath?: (id: string) => string;\n}): ResolvedReferenceBinding[] {\n const defaultImportName = options.defaultImportName ?? toCamelCase;\n const defaultModulePath =\n options.defaultModulePath ?? ((id: string) => buildComponentFileName(id));\n\n const inputs: ReferenceResolutionInput[] = [];\n const seenIds = new Set<string>();\n for (const id of options.ids) {\n if (!id || seenIds.has(id)) {\n continue;\n }\n seenIds.add(id);\n\n const referenceOverride = options.referenceOverrides?.[id];\n const importName =\n typeof referenceOverride === 'string'\n ? referenceOverride\n : (referenceOverride?.name ?? defaultImportName(id));\n const modulePath = options.referencePathOverrides?.[id] ?? defaultModulePath(id);\n\n inputs.push({\n id,\n importName,\n modulePath,\n local: typeof referenceOverride === 'object' && referenceOverride?.local === true,\n conflictSuffix: options.conflictSuffix,\n collisionStrategy: options.collisionStrategy,\n });\n }\n\n return resolveReferenceBindings(inputs, {\n reservedNames: options.reservedNames,\n conflictSuffix: options.conflictSuffix,\n collisionStrategy: options.collisionStrategy,\n });\n}\n\nexport function addResolvedReferenceImports(\n sourceFile: SourceFile,\n references: Iterable<ResolvedReferenceBinding>,\n resolveModuleSpecifier: (reference: ResolvedReferenceBinding) => string\n): void {\n const namedImportsByModuleSpecifier = new Map<\n string,\n Array<string | { name: string; alias: string }>\n >();\n\n for (const reference of references) {\n if (!reference.namedImport) {\n continue;\n }\n\n const moduleSpecifier = resolveModuleSpecifier(reference);\n const namedImports = namedImportsByModuleSpecifier.get(moduleSpecifier) ?? [];\n namedImports.push(reference.namedImport);\n namedImportsByModuleSpecifier.set(moduleSpecifier, namedImports);\n }\n\n for (const [moduleSpecifier, namedImports] of namedImportsByModuleSpecifier) {\n sourceFile.addImportDeclaration({\n namedImports,\n moduleSpecifier,\n });\n }\n}\n\nexport function toReferenceNameMap(\n references: Iterable<ResolvedReferenceBinding>\n): Map<string, string> {\n return new Map(\n [...references].map((reference) => {\n return [reference.id, reference.localName];\n })\n );\n}\n\nexport function toReferenceNameRecord(\n references: Iterable<ResolvedReferenceBinding>\n): Record<string, string> {\n return Object.fromEntries(\n [...references].map((reference) => {\n return [reference.id, reference.localName];\n })\n );\n}\n\nexport function toReferenceNames(references: Iterable<ResolvedReferenceBinding>): string[] {\n return [...references].map((reference) => reference.localName);\n}\n\nfunction dedupeReferenceInputs(\n inputs: Iterable<ReferenceResolutionInput>\n): ReferenceResolutionInput[] {\n const dedupedInputs: ReferenceResolutionInput[] = [];\n const seenIds = new Set<string>();\n\n for (const input of inputs) {\n if (seenIds.has(input.id)) {\n continue;\n }\n seenIds.add(input.id);\n dedupedInputs.push(input);\n }\n\n return dedupedInputs;\n}\n\nfunction normalizeModulePath(modulePath: string): string {\n return modulePath.replace(/\\.[^.]+$/, '');\n}\n"],"mappings":";;;;AAmCA,SAAgB,wBACd,OACA,SAK0B;CAC1B,MAAM,CAAC,WAAW,yBAAyB,CAAC,MAAM,EAAE,QAAQ;AAC5D,KAAI,CAAC,QACH,OAAM,IAAI,MAAM,2CAA2C,MAAM,KAAK;AAExE,QAAO;;AAGT,SAAgB,yBACd,QACA,SAK4B;CAC5B,MAAM,gBAAgB,sBAAsB,OAAO;CACnD,MAAM,mCAAmB,IAAI,KAAqB;AAElD,MAAK,MAAM,SAAS,cAClB,kBAAiB,IAAI,MAAM,aAAa,iBAAiB,IAAI,MAAM,WAAW,IAAI,KAAK,EAAE;AAG3F,QAAO,cAAc,KAAK,UAAU;AAClC,MAAI,MAAM,OAAO;AACf,WAAQ,cAAc,IAAI,MAAM,WAAW;AAC3C,UAAO;IACL,IAAI,MAAM;IACV,YAAY,MAAM;IAClB,WAAW,MAAM;IACjB,YAAY,oBAAoB,MAAM,WAAW;IACjD,SAAS;IACV;;EAGH,MAAM,oBAAoB,MAAM,qBAAqB,QAAQ,qBAAqB;EAClF,MAAM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,UAAU,YACb;EAGF,MAAM,kBAAkB,uBAAuB,UAAU;EACzD,MAAM,eAAe,8BAA8B,IAAI,gBAAgB,IAAI,EAAE;AAC7E,eAAa,KAAK,UAAU,YAAY;AACxC,gCAA8B,IAAI,iBAAiB,aAAa;;AAGlE,MAAK,MAAM,CAAC,iBAAiB,iBAAiB,8BAC5C,YAAW,qBAAqB;EAC9B;EACA;EACD,CAAC;;AAIN,SAAgB,mBACd,YACqB;AACrB,QAAO,IAAI,IACT,CAAC,GAAG,WAAW,CAAC,KAAK,cAAc;AACjC,SAAO,CAAC,UAAU,IAAI,UAAU,UAAU;GAC1C,CACH;;AAGH,SAAgB,sBACd,YACwB;AACxB,QAAO,OAAO,YACZ,CAAC,GAAG,WAAW,CAAC,KAAK,cAAc;AACjC,SAAO,CAAC,UAAU,IAAI,UAAU,UAAU;GAC1C,CACH;;AAGH,SAAgB,iBAAiB,YAA0D;AACzF,QAAO,CAAC,GAAG,WAAW,CAAC,KAAK,cAAc,UAAU,UAAU;;AAGhE,SAAS,sBACP,QAC4B;CAC5B,MAAM,gBAA4C,EAAE;CACpD,MAAM,0BAAU,IAAI,KAAa;AAEjC,MAAK,MAAM,SAAS,QAAQ;AAC1B,MAAI,QAAQ,IAAI,MAAM,GAAG,CACvB;AAEF,UAAQ,IAAI,MAAM,GAAG;AACrB,gBAAc,KAAK,MAAM;;AAG3B,QAAO;;AAGT,SAAS,oBAAoB,YAA4B;AACvD,QAAO,WAAW,QAAQ,YAAY,GAAG"}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { addValueToObject, createFactoryDefinition } from "./utils/factory-writer.js";
|
|
2
|
+
import "./utils/index.js";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
|
|
5
|
+
//#region src/commands/pull-v4/simple-factory-generator.ts
|
|
6
|
+
function validateGeneratorInput(data, options) {
|
|
7
|
+
const result = options.schema.safeParse(data);
|
|
8
|
+
if (!result.success) throw new Error(`Validation failed for ${options.errorLabel ?? options.importName}:\n${z.prettifyError(result.error)}`);
|
|
9
|
+
return result.data;
|
|
10
|
+
}
|
|
11
|
+
function generateValidatedSourceFile(data, options) {
|
|
12
|
+
return options.render(validateGeneratorInput(data, options));
|
|
13
|
+
}
|
|
14
|
+
function generateFactorySourceFile(data, options) {
|
|
15
|
+
const { importName, fileName, moduleSpecifier, syntaxKind } = options.factory;
|
|
16
|
+
return generateValidatedSourceFile(data, {
|
|
17
|
+
schema: options.schema,
|
|
18
|
+
importName,
|
|
19
|
+
render(parsed) {
|
|
20
|
+
const { sourceFile, configObject } = createFactoryDefinition({
|
|
21
|
+
importName,
|
|
22
|
+
variableName: options.factory.variableName(parsed),
|
|
23
|
+
...fileName && { fileName },
|
|
24
|
+
...moduleSpecifier && { moduleSpecifier },
|
|
25
|
+
...syntaxKind && { syntaxKind }
|
|
26
|
+
});
|
|
27
|
+
options.render({
|
|
28
|
+
parsed,
|
|
29
|
+
sourceFile,
|
|
30
|
+
configObject
|
|
31
|
+
});
|
|
32
|
+
return sourceFile;
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
function generateSimpleFactoryDefinition(data, options) {
|
|
37
|
+
return generateFactorySourceFile(data, {
|
|
38
|
+
schema: options.schema,
|
|
39
|
+
factory: options.factory,
|
|
40
|
+
render({ parsed, sourceFile, configObject }) {
|
|
41
|
+
const config = options.buildConfig ? options.buildConfig(parsed) : parsed;
|
|
42
|
+
for (const [key, value] of Object.entries(config)) addValueToObject(configObject, key, value);
|
|
43
|
+
options.finalize?.({
|
|
44
|
+
parsed,
|
|
45
|
+
sourceFile,
|
|
46
|
+
configObject
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
//#endregion
|
|
53
|
+
export { generateFactorySourceFile, generateSimpleFactoryDefinition, generateValidatedSourceFile, validateGeneratorInput };
|
|
54
|
+
//# sourceMappingURL=simple-factory-generator.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"simple-factory-generator.js","names":[],"sources":["../../../src/commands/pull-v4/simple-factory-generator.ts"],"sourcesContent":["import type { ObjectLiteralExpression, SourceFile, SyntaxKind } from 'ts-morph';\nimport { type input, type output, type ZodType, z } from 'zod';\nimport { addValueToObject, createFactoryDefinition } from './utils';\n\ninterface GeneratorValidationOptions<TSchema extends ZodType> {\n schema: TSchema;\n errorLabel?: string;\n importName?: string;\n}\n\ninterface FactorySourceFileOptions<TSchema extends ZodType>\n extends Omit<GeneratorValidationOptions<TSchema>, 'errorLabel' | 'importName'> {\n factory: {\n importName: string;\n variableName: (parsed: output<TSchema>) => string;\n fileName?: string;\n moduleSpecifier?: string;\n syntaxKind?: SyntaxKind.CallExpression | SyntaxKind.NewExpression;\n };\n render: (options: {\n parsed: output<TSchema>;\n sourceFile: SourceFile;\n configObject: ObjectLiteralExpression;\n }) => void;\n}\n\ninterface SimpleFactoryDefinitionOptions<TSchema extends ZodType<Record<string, unknown>>>\n extends Omit<GeneratorValidationOptions<TSchema>, 'errorLabel' | 'importName'> {\n factory: FactorySourceFileOptions<TSchema>['factory'];\n buildConfig?: (parsed: output<TSchema>) => Record<string, unknown>;\n finalize?: (options: {\n parsed: output<TSchema>;\n sourceFile: SourceFile;\n configObject: ObjectLiteralExpression;\n }) => void;\n}\n\nexport function validateGeneratorInput<TSchema extends ZodType>(\n data: input<TSchema>,\n options: GeneratorValidationOptions<TSchema>\n): output<TSchema> {\n const result = options.schema.safeParse(data);\n if (!result.success) {\n throw new Error(\n `Validation failed for ${options.errorLabel ?? options.importName}:\\n${z.prettifyError(result.error)}`\n );\n }\n\n return result.data;\n}\n\nexport function generateValidatedSourceFile<TSchema extends ZodType>(\n data: input<TSchema>,\n options: GeneratorValidationOptions<TSchema> & {\n render: (parsed: output<TSchema>) => SourceFile;\n }\n): SourceFile {\n return options.render(validateGeneratorInput(data, options));\n}\n\nexport function generateFactorySourceFile<TSchema extends ZodType>(\n data: input<TSchema>,\n options: FactorySourceFileOptions<TSchema>\n): SourceFile {\n const { importName, fileName, moduleSpecifier, syntaxKind } = options.factory;\n\n return generateValidatedSourceFile(data, {\n schema: options.schema,\n importName,\n render(parsed) {\n const { sourceFile, configObject } = createFactoryDefinition({\n importName,\n variableName: options.factory.variableName(parsed),\n ...(fileName && { fileName }),\n ...(moduleSpecifier && { moduleSpecifier }),\n ...(syntaxKind && { syntaxKind }),\n });\n\n options.render({ parsed, sourceFile, configObject });\n\n return sourceFile;\n },\n });\n}\n\nexport function generateSimpleFactoryDefinition<TSchema extends ZodType<Record<string, unknown>>>(\n data: input<TSchema>,\n options: SimpleFactoryDefinitionOptions<TSchema>\n): SourceFile {\n return generateFactorySourceFile(data, {\n schema: options.schema,\n factory: options.factory,\n render({ parsed, sourceFile, configObject }) {\n const config = options.buildConfig ? options.buildConfig(parsed) : parsed;\n for (const [key, value] of Object.entries(config)) {\n addValueToObject(configObject, key, value);\n }\n\n options.finalize?.({ parsed, sourceFile, configObject });\n },\n });\n}\n"],"mappings":";;;;;AAqCA,SAAgB,uBACd,MACA,SACiB;CACjB,MAAM,SAAS,QAAQ,OAAO,UAAU,KAAK;AAC7C,KAAI,CAAC,OAAO,QACV,OAAM,IAAI,MACR,yBAAyB,QAAQ,cAAc,QAAQ,WAAW,KAAK,EAAE,cAAc,OAAO,MAAM,GACrG;AAGH,QAAO,OAAO;;AAGhB,SAAgB,4BACd,MACA,SAGY;AACZ,QAAO,QAAQ,OAAO,uBAAuB,MAAM,QAAQ,CAAC;;AAG9D,SAAgB,0BACd,MACA,SACY;CACZ,MAAM,EAAE,YAAY,UAAU,iBAAiB,eAAe,QAAQ;AAEtE,QAAO,4BAA4B,MAAM;EACvC,QAAQ,QAAQ;EAChB;EACA,OAAO,QAAQ;GACb,MAAM,EAAE,YAAY,iBAAiB,wBAAwB;IAC3D;IACA,cAAc,QAAQ,QAAQ,aAAa,OAAO;IAClD,GAAI,YAAY,EAAE,UAAU;IAC5B,GAAI,mBAAmB,EAAE,iBAAiB;IAC1C,GAAI,cAAc,EAAE,YAAY;IACjC,CAAC;AAEF,WAAQ,OAAO;IAAE;IAAQ;IAAY;IAAc,CAAC;AAEpD,UAAO;;EAEV,CAAC;;AAGJ,SAAgB,gCACd,MACA,SACY;AACZ,QAAO,0BAA0B,MAAM;EACrC,QAAQ,QAAQ;EAChB,SAAS,QAAQ;EACjB,OAAO,EAAE,QAAQ,YAAY,gBAAgB;GAC3C,MAAM,SAAS,QAAQ,cAAc,QAAQ,YAAY,OAAO,GAAG;AACnE,QAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,CAC/C,kBAAiB,cAAc,KAAK,MAAM;AAG5C,WAAQ,WAAW;IAAE;IAAQ;IAAY;IAAc,CAAC;;EAE3D,CAAC"}
|
|
@@ -1,21 +1,33 @@
|
|
|
1
|
+
import { validateGeneratorInput } from "./simple-factory-generator.js";
|
|
1
2
|
import { FullProjectDefinitionSchema } from "@inkeep/agents-core";
|
|
3
|
+
import { z } from "zod";
|
|
2
4
|
import { join } from "node:path";
|
|
3
5
|
import { stringify } from "yaml";
|
|
4
6
|
import { mkdir, writeFile } from "node:fs/promises";
|
|
5
7
|
|
|
6
|
-
//#region src/commands/pull-v4/
|
|
7
|
-
FullProjectDefinitionSchema.shape.skills.unwrap().valueType;
|
|
8
|
+
//#region src/commands/pull-v4/skill.ts
|
|
9
|
+
const MySchema = FullProjectDefinitionSchema.shape.skills.unwrap().valueType;
|
|
10
|
+
const SkillsSchema = z.record(z.string(), MySchema);
|
|
11
|
+
const SkillsDirSchema = z.string().nonempty();
|
|
8
12
|
function formatMetadata(metadata) {
|
|
9
13
|
return `metadata:\n${stringify(metadata).split("\n").filter((line) => line.trim() !== "").map((line) => ` ${line}`).join("\n")}`;
|
|
10
14
|
}
|
|
11
15
|
async function generateSkills(skills, skillsDir) {
|
|
12
|
-
|
|
13
|
-
|
|
16
|
+
const validatedSkills = validateGeneratorInput(skills, {
|
|
17
|
+
schema: SkillsSchema,
|
|
18
|
+
errorLabel: "skills"
|
|
19
|
+
});
|
|
20
|
+
const validatedSkillsDir = validateGeneratorInput(skillsDir, {
|
|
21
|
+
schema: SkillsDirSchema,
|
|
22
|
+
errorLabel: "skills directory"
|
|
23
|
+
});
|
|
24
|
+
await mkdir(validatedSkillsDir, { recursive: true });
|
|
25
|
+
for (const [skillId, skill] of Object.entries(validatedSkills)) {
|
|
14
26
|
const parts = ["---", `name: ${JSON.stringify(skill.name)}`];
|
|
15
27
|
parts.push(`description: ${JSON.stringify(skill.description ?? "")}`);
|
|
16
28
|
if (skill.metadata && Object.keys(skill.metadata).length > 0) parts.push(formatMetadata(skill.metadata));
|
|
17
29
|
parts.push("---", "", skill.content || "");
|
|
18
|
-
const skillDir = join(
|
|
30
|
+
const skillDir = join(validatedSkillsDir, skillId);
|
|
19
31
|
await mkdir(skillDir, { recursive: true });
|
|
20
32
|
await writeFile(join(skillDir, "SKILL.md"), parts.join("\n"), "utf8");
|
|
21
33
|
}
|
|
@@ -23,4 +35,4 @@ async function generateSkills(skills, skillsDir) {
|
|
|
23
35
|
|
|
24
36
|
//#endregion
|
|
25
37
|
export { generateSkills };
|
|
26
|
-
//# sourceMappingURL=skill
|
|
38
|
+
//# sourceMappingURL=skill.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"skill.js","names":[],"sources":["../../../src/commands/pull-v4/skill.ts"],"sourcesContent":["import { mkdir, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { FullProjectDefinitionSchema } from '@inkeep/agents-core';\nimport { stringify } from 'yaml';\nimport { z } from 'zod';\nimport { validateGeneratorInput } from './simple-factory-generator';\n\nconst MySchema = FullProjectDefinitionSchema.shape.skills.unwrap().valueType;\nconst SkillsSchema = z.record(z.string(), MySchema);\nconst SkillsDirSchema = z.string().nonempty();\n\ntype SkillInput = z.input<typeof MySchema>;\n\ntype SkillMap = Record<string, SkillInput>;\n\nfunction formatMetadata(metadata: NonNullable<SkillInput['metadata']>): string {\n const yaml = stringify(metadata);\n const indented = yaml\n .split('\\n')\n .filter((line) => line.trim() !== '')\n .map((line) => ` ${line}`)\n .join('\\n');\n return `metadata:\\n${indented}`;\n}\n\nexport async function generateSkills(skills: SkillMap, skillsDir: string): Promise<void> {\n const validatedSkills = validateGeneratorInput(skills, {\n schema: SkillsSchema,\n errorLabel: 'skills',\n });\n const validatedSkillsDir = validateGeneratorInput(skillsDir, {\n schema: SkillsDirSchema,\n errorLabel: 'skills directory',\n });\n\n await mkdir(validatedSkillsDir, { recursive: true });\n\n for (const [skillId, skill] of Object.entries(validatedSkills)) {\n const parts: string[] = ['---', `name: ${JSON.stringify(skill.name)}`];\n parts.push(`description: ${JSON.stringify(skill.description ?? '')}`);\n\n if (skill.metadata && Object.keys(skill.metadata).length > 0) {\n parts.push(formatMetadata(skill.metadata));\n }\n\n parts.push('---', '', skill.content || '');\n\n const skillDir = join(validatedSkillsDir, skillId);\n await mkdir(skillDir, { recursive: true });\n\n const filePath = join(skillDir, 'SKILL.md');\n await writeFile(filePath, parts.join('\\n'), 'utf8');\n }\n}\n"],"mappings":";;;;;;;;AAOA,MAAM,WAAW,4BAA4B,MAAM,OAAO,QAAQ,CAAC;AACnE,MAAM,eAAe,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAS;AACnD,MAAM,kBAAkB,EAAE,QAAQ,CAAC,UAAU;AAM7C,SAAS,eAAe,UAAuD;AAO7E,QAAO,cANM,UAAU,SAAS,CAE7B,MAAM,KAAK,CACX,QAAQ,SAAS,KAAK,MAAM,KAAK,GAAG,CACpC,KAAK,SAAS,KAAK,OAAO,CAC1B,KAAK,KAAK;;AAIf,eAAsB,eAAe,QAAkB,WAAkC;CACvF,MAAM,kBAAkB,uBAAuB,QAAQ;EACrD,QAAQ;EACR,YAAY;EACb,CAAC;CACF,MAAM,qBAAqB,uBAAuB,WAAW;EAC3D,QAAQ;EACR,YAAY;EACb,CAAC;AAEF,OAAM,MAAM,oBAAoB,EAAE,WAAW,MAAM,CAAC;AAEpD,MAAK,MAAM,CAAC,SAAS,UAAU,OAAO,QAAQ,gBAAgB,EAAE;EAC9D,MAAM,QAAkB,CAAC,OAAO,SAAS,KAAK,UAAU,MAAM,KAAK,GAAG;AACtE,QAAM,KAAK,gBAAgB,KAAK,UAAU,MAAM,eAAe,GAAG,GAAG;AAErE,MAAI,MAAM,YAAY,OAAO,KAAK,MAAM,SAAS,CAAC,SAAS,EACzD,OAAM,KAAK,eAAe,MAAM,SAAS,CAAC;AAG5C,QAAM,KAAK,OAAO,IAAI,MAAM,WAAW,GAAG;EAE1C,MAAM,WAAW,KAAK,oBAAoB,QAAQ;AAClD,QAAM,MAAM,UAAU,EAAE,WAAW,MAAM,CAAC;AAG1C,QAAM,UADW,KAAK,UAAU,WAAW,EACjB,MAAM,KAAK,KAAK,EAAE,OAAO"}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { createInMemoryProject } from "./utils/factory-writer.js";
|
|
2
|
+
import "./utils/index.js";
|
|
3
|
+
import { mergeGeneratedModule } from "./module-merge.js";
|
|
4
|
+
import { dirname } from "node:path";
|
|
5
|
+
import { Node, SyntaxKind } from "ts-morph";
|
|
6
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
7
|
+
|
|
8
|
+
//#region src/commands/pull-v4/typescript-file-writer.ts
|
|
9
|
+
function writeTypeScriptFile(filePath, content, writeMode) {
|
|
10
|
+
mkdirSync(dirname(filePath), { recursive: true });
|
|
11
|
+
const processedContent = writeMode === "merge" && existsSync(filePath) ? mergeSafely(readFileSync(filePath, "utf8"), content) : content;
|
|
12
|
+
const sourceFile = createInMemoryProject().createSourceFile("generated.ts", processedContent, { overwrite: true });
|
|
13
|
+
const normalizedSourceFile = moveVariableDeclarationsBeforeUsage(applyObjectShorthand(sourceFile));
|
|
14
|
+
sourceFile.formatText();
|
|
15
|
+
writeFileSync(filePath, `${normalizedSourceFile.getFullText().trimEnd()}\n`);
|
|
16
|
+
}
|
|
17
|
+
function mergeSafely(existingContent, generatedContent) {
|
|
18
|
+
try {
|
|
19
|
+
return mergeGeneratedModule(existingContent, generatedContent);
|
|
20
|
+
} catch (error) {
|
|
21
|
+
console.warn(`Warning: Failed to merge file, using generated content. Manual changes may be lost. Reason: ${error instanceof Error ? error.message : String(error)}`);
|
|
22
|
+
return generatedContent;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function applyObjectShorthand(sourceFile) {
|
|
26
|
+
for (const objectLiteral of sourceFile.getDescendantsOfKind(SyntaxKind.ObjectLiteralExpression)) for (const property of objectLiteral.getProperties()) {
|
|
27
|
+
if (!Node.isPropertyAssignment(property)) continue;
|
|
28
|
+
const nameNode = property.getNameNode();
|
|
29
|
+
const initializer = property.getInitializer();
|
|
30
|
+
if (!Node.isIdentifier(nameNode) || !initializer || !Node.isIdentifier(initializer)) continue;
|
|
31
|
+
if (nameNode.getText() !== initializer.getText()) continue;
|
|
32
|
+
property.replaceWithText(nameNode.getText());
|
|
33
|
+
}
|
|
34
|
+
return sourceFile;
|
|
35
|
+
}
|
|
36
|
+
function moveVariableDeclarationsBeforeUsage(sourceFile) {
|
|
37
|
+
let moved = true;
|
|
38
|
+
while (moved) {
|
|
39
|
+
moved = false;
|
|
40
|
+
const variableStatements = sourceFile.getVariableStatements();
|
|
41
|
+
for (const variableStatement of variableStatements) {
|
|
42
|
+
const statementStart = variableStatement.getStart();
|
|
43
|
+
const sourceStatements = sourceFile.getStatements();
|
|
44
|
+
const statementIndex = sourceStatements.indexOf(variableStatement);
|
|
45
|
+
if (statementIndex <= 0) continue;
|
|
46
|
+
let targetIndex;
|
|
47
|
+
for (const declaration of variableStatement.getDeclarations()) for (const referenceNode of declaration.findReferencesAsNodes()) {
|
|
48
|
+
if (referenceNode.getSourceFile() !== sourceFile) continue;
|
|
49
|
+
if (referenceNode.getParent() === declaration) continue;
|
|
50
|
+
if (referenceNode.getStart() >= statementStart) continue;
|
|
51
|
+
if (isReferenceInsideFunctionLike(referenceNode)) continue;
|
|
52
|
+
const topLevelStatement = referenceNode.getFirstAncestor((ancestor) => {
|
|
53
|
+
return Node.isStatement(ancestor) && ancestor.getParentIfKind(SyntaxKind.SourceFile);
|
|
54
|
+
});
|
|
55
|
+
if (!topLevelStatement) continue;
|
|
56
|
+
const topLevelStatementIndex = sourceStatements.indexOf(topLevelStatement);
|
|
57
|
+
if (topLevelStatementIndex === -1 || topLevelStatementIndex >= statementIndex) continue;
|
|
58
|
+
targetIndex = targetIndex === void 0 ? topLevelStatementIndex : Math.min(targetIndex, topLevelStatementIndex);
|
|
59
|
+
}
|
|
60
|
+
if (targetIndex === void 0) continue;
|
|
61
|
+
const statementText = variableStatement.getText();
|
|
62
|
+
variableStatement.remove();
|
|
63
|
+
sourceFile.insertStatements(targetIndex, [statementText]);
|
|
64
|
+
moved = true;
|
|
65
|
+
break;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return sourceFile;
|
|
69
|
+
}
|
|
70
|
+
function isReferenceInsideFunctionLike(referenceNode) {
|
|
71
|
+
return Boolean(referenceNode.getFirstAncestor((ancestor) => {
|
|
72
|
+
return Node.isArrowFunction(ancestor) || Node.isFunctionDeclaration(ancestor) || Node.isFunctionExpression(ancestor) || Node.isMethodDeclaration(ancestor) || Node.isGetAccessorDeclaration(ancestor) || Node.isSetAccessorDeclaration(ancestor);
|
|
73
|
+
}));
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
//#endregion
|
|
77
|
+
export { writeTypeScriptFile };
|
|
78
|
+
//# sourceMappingURL=typescript-file-writer.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"typescript-file-writer.js","names":[],"sources":["../../../src/commands/pull-v4/typescript-file-writer.ts"],"sourcesContent":["import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport { Node, type SourceFile, SyntaxKind } from 'ts-morph';\nimport { mergeGeneratedModule } from './module-merge';\nimport { createInMemoryProject } from './utils';\n\nexport function writeTypeScriptFile(\n filePath: string,\n content: string,\n writeMode: 'merge' | 'overwrite'\n): void {\n mkdirSync(dirname(filePath), { recursive: true });\n\n const processedContent =\n writeMode === 'merge' && existsSync(filePath)\n ? mergeSafely(readFileSync(filePath, 'utf8'), content)\n : content;\n\n const sourceFile = createInMemoryProject().createSourceFile('generated.ts', processedContent, {\n overwrite: true,\n });\n\n const normalizedSourceFile = moveVariableDeclarationsBeforeUsage(\n applyObjectShorthand(sourceFile)\n );\n sourceFile.formatText();\n writeFileSync(filePath, `${normalizedSourceFile.getFullText().trimEnd()}\\n`);\n}\n\nfunction mergeSafely(existingContent: string, generatedContent: string): string {\n try {\n return mergeGeneratedModule(existingContent, generatedContent);\n } catch (error) {\n console.warn(\n `Warning: Failed to merge file, using generated content. Manual changes may be lost. Reason: ${error instanceof Error ? error.message : String(error)}`\n );\n return generatedContent;\n }\n}\n\nfunction applyObjectShorthand(sourceFile: SourceFile): SourceFile {\n for (const objectLiteral of sourceFile.getDescendantsOfKind(SyntaxKind.ObjectLiteralExpression)) {\n for (const property of objectLiteral.getProperties()) {\n if (!Node.isPropertyAssignment(property)) {\n continue;\n }\n const nameNode = property.getNameNode();\n const initializer = property.getInitializer();\n if (!Node.isIdentifier(nameNode) || !initializer || !Node.isIdentifier(initializer)) {\n continue;\n }\n if (nameNode.getText() !== initializer.getText()) {\n continue;\n }\n property.replaceWithText(nameNode.getText());\n }\n }\n return sourceFile;\n}\n\nfunction moveVariableDeclarationsBeforeUsage(sourceFile: SourceFile): SourceFile {\n let moved = true;\n while (moved) {\n moved = false;\n const variableStatements = sourceFile.getVariableStatements();\n for (const variableStatement of variableStatements) {\n const statementStart = variableStatement.getStart();\n const sourceStatements = sourceFile.getStatements();\n const statementIndex = sourceStatements.indexOf(variableStatement);\n if (statementIndex <= 0) {\n continue;\n }\n\n let targetIndex: number | undefined;\n for (const declaration of variableStatement.getDeclarations()) {\n for (const referenceNode of declaration.findReferencesAsNodes()) {\n if (referenceNode.getSourceFile() !== sourceFile) {\n continue;\n }\n\n const parentNode = referenceNode.getParent();\n if (parentNode === declaration) {\n continue;\n }\n\n if (referenceNode.getStart() >= statementStart) {\n continue;\n }\n\n if (isReferenceInsideFunctionLike(referenceNode)) {\n continue;\n }\n // @ts-expect-error\n const topLevelStatement = referenceNode.getFirstAncestor((ancestor) => {\n return Node.isStatement(ancestor) && ancestor.getParentIfKind(SyntaxKind.SourceFile);\n });\n if (!topLevelStatement) {\n continue;\n }\n // @ts-expect-error\n const topLevelStatementIndex = sourceStatements.indexOf(topLevelStatement);\n if (topLevelStatementIndex === -1 || topLevelStatementIndex >= statementIndex) {\n continue;\n }\n\n targetIndex =\n targetIndex === undefined\n ? topLevelStatementIndex\n : Math.min(targetIndex, topLevelStatementIndex);\n }\n }\n\n if (targetIndex === undefined) {\n continue;\n }\n\n const statementText = variableStatement.getText();\n variableStatement.remove();\n sourceFile.insertStatements(targetIndex, [statementText]);\n moved = true;\n break;\n }\n }\n return sourceFile;\n}\n\nfunction isReferenceInsideFunctionLike(referenceNode: Node): boolean {\n return Boolean(\n referenceNode.getFirstAncestor((ancestor) => {\n return (\n Node.isArrowFunction(ancestor) ||\n Node.isFunctionDeclaration(ancestor) ||\n Node.isFunctionExpression(ancestor) ||\n Node.isMethodDeclaration(ancestor) ||\n Node.isGetAccessorDeclaration(ancestor) ||\n Node.isSetAccessorDeclaration(ancestor)\n );\n })\n );\n}\n"],"mappings":";;;;;;;;AAMA,SAAgB,oBACd,UACA,SACA,WACM;AACN,WAAU,QAAQ,SAAS,EAAE,EAAE,WAAW,MAAM,CAAC;CAEjD,MAAM,mBACJ,cAAc,WAAW,WAAW,SAAS,GACzC,YAAY,aAAa,UAAU,OAAO,EAAE,QAAQ,GACpD;CAEN,MAAM,aAAa,uBAAuB,CAAC,iBAAiB,gBAAgB,kBAAkB,EAC5F,WAAW,MACZ,CAAC;CAEF,MAAM,uBAAuB,oCAC3B,qBAAqB,WAAW,CACjC;AACD,YAAW,YAAY;AAC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B,aAAa;AACrE,YAAO,KAAK,YAAY,SAAS,IAAI,SAAS,gBAAgB,WAAW,WAAW;MACpF;AACF,QAAI,CAAC,kBACH;IAGF,MAAM,yBAAyB,iBAAiB,QAAQ,kBAAkB;AAC1E,QAAI,2BAA2B,MAAM,0BAA0B,eAC7D;AAGF,kBACE,gBAAgB,SACZ,yBACA,KAAK,IAAI,aAAa,uBAAuB;;AAIvD,OAAI,gBAAgB,OAClB;GAGF,MAAM,gBAAgB,kBAAkB,SAAS;AACjD,qBAAkB,QAAQ;AAC1B,cAAW,iBAAiB,aAAa,CAAC,cAAc,CAAC;AACzD,WAAQ;AACR;;;AAGJ,QAAO;;AAGT,SAAS,8BAA8B,eAA8B;AACnE,QAAO,QACL,cAAc,kBAAkB,aAAa;AAC3C,SACE,KAAK,gBAAgB,SAAS,IAC9B,KAAK,sBAAsB,SAAS,IACpC,KAAK,qBAAqB,SAAS,IACnC,KAAK,oBAAoB,SAAS,IAClC,KAAK,yBAAyB,SAAS,IACvC,KAAK,yBAAyB,SAAS;GAEzC,CACH"}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { isPlainObject } from "./shared.js";
|
|
2
|
+
import { formatPropertyName, formatStringLiteral } from "./templates.js";
|
|
3
|
+
|
|
4
|
+
//#region src/commands/pull-v4/utils/code-values.ts
|
|
5
|
+
function codeReference(name) {
|
|
6
|
+
return {
|
|
7
|
+
kind: "reference",
|
|
8
|
+
name
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
function codeExpression(code) {
|
|
12
|
+
return {
|
|
13
|
+
kind: "expression",
|
|
14
|
+
code
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
function isCodeValue(value) {
|
|
18
|
+
return isCodeReferenceValue(value) || isCodeExpressionValue(value);
|
|
19
|
+
}
|
|
20
|
+
function codePropertyAccess(target, property) {
|
|
21
|
+
return codeExpression(`${toCodeSource(target)}.${property}`);
|
|
22
|
+
}
|
|
23
|
+
function codeCall(callee, ...args) {
|
|
24
|
+
return codeExpression(`${toCodeSource(callee)}(${args.map((arg) => formatInlineLiteral(arg)).join(", ")})`);
|
|
25
|
+
}
|
|
26
|
+
function codeMethodCall(target, method, ...args) {
|
|
27
|
+
return codeExpression(`${toCodeSource(target)}.${method}(${args.map((arg) => formatInlineLiteral(arg)).join(", ")})`);
|
|
28
|
+
}
|
|
29
|
+
function createArrayGetterValue(values) {
|
|
30
|
+
return codeExpression(`() => [${values.map((value) => formatInlineLiteral(value)).join(", ")}]`);
|
|
31
|
+
}
|
|
32
|
+
function createReferenceGetterValue(references) {
|
|
33
|
+
return createArrayGetterValue(references.map((reference) => typeof reference === "string" ? codeReference(reference) : reference));
|
|
34
|
+
}
|
|
35
|
+
function formatInlineLiteral(value) {
|
|
36
|
+
if (isCodeReferenceValue(value)) return value.name;
|
|
37
|
+
if (isCodeExpressionValue(value)) return value.code;
|
|
38
|
+
if (typeof value === "string") return formatStringLiteral(value);
|
|
39
|
+
if (typeof value === "number" || typeof value === "bigint") return String(value);
|
|
40
|
+
if (typeof value === "boolean") return value ? "true" : "false";
|
|
41
|
+
if (value === null) return "null";
|
|
42
|
+
if (Array.isArray(value)) return `[${value.map((item) => formatInlineLiteral(item)).join(", ")}]`;
|
|
43
|
+
if (isPlainObject(value)) {
|
|
44
|
+
const entries = Object.entries(value).filter(([, entryValue]) => entryValue !== void 0);
|
|
45
|
+
if (!entries.length) return "{}";
|
|
46
|
+
return `{ ${entries.map(([key, entryValue]) => `${formatPropertyName(key)}: ${formatInlineLiteral(entryValue)}`).join(", ")} }`;
|
|
47
|
+
}
|
|
48
|
+
return "undefined";
|
|
49
|
+
}
|
|
50
|
+
function isCodeReferenceValue(value) {
|
|
51
|
+
return isPlainObject(value) && value.kind === "reference" && typeof value.name === "string";
|
|
52
|
+
}
|
|
53
|
+
function isCodeExpressionValue(value) {
|
|
54
|
+
return isPlainObject(value) && value.kind === "expression" && typeof value.code === "string";
|
|
55
|
+
}
|
|
56
|
+
function toCodeSource(value) {
|
|
57
|
+
if (typeof value === "string") return value;
|
|
58
|
+
if (isCodeReferenceValue(value)) return value.name;
|
|
59
|
+
return value.code;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
//#endregion
|
|
63
|
+
export { codeCall, codeExpression, codeMethodCall, codePropertyAccess, codeReference, createArrayGetterValue, createReferenceGetterValue, formatInlineLiteral, isCodeValue };
|
|
64
|
+
//# sourceMappingURL=code-values.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"code-values.js","names":[],"sources":["../../../../src/commands/pull-v4/utils/code-values.ts"],"sourcesContent":["import { isPlainObject } from './shared';\nimport { formatPropertyName, formatStringLiteral } from './templates';\n\ninterface CodeReferenceValue {\n kind: 'reference';\n name: string;\n}\n\ninterface CodeExpressionValue {\n kind: 'expression';\n code: string;\n}\n\nexport type CodeValue = CodeReferenceValue | CodeExpressionValue;\n\nexport function codeReference(name: string): CodeReferenceValue {\n return {\n kind: 'reference',\n name,\n };\n}\n\nexport function codeExpression(code: string): CodeExpressionValue {\n return {\n kind: 'expression',\n code,\n };\n}\n\nexport function isCodeValue(value: unknown): value is CodeValue {\n return isCodeReferenceValue(value) || isCodeExpressionValue(value);\n}\n\nexport function codePropertyAccess(\n target: string | CodeValue,\n property: string\n): CodeExpressionValue {\n return codeExpression(`${toCodeSource(target)}.${property}`);\n}\n\nexport function codeCall(callee: string | CodeValue, ...args: unknown[]): CodeExpressionValue {\n return codeExpression(\n `${toCodeSource(callee)}(${args.map((arg) => formatInlineLiteral(arg)).join(', ')})`\n );\n}\n\nexport function codeMethodCall(\n target: string | CodeValue,\n method: string,\n ...args: unknown[]\n): CodeExpressionValue {\n return codeExpression(\n `${toCodeSource(target)}.${method}(${args.map((arg) => formatInlineLiteral(arg)).join(', ')})`\n );\n}\n\nexport function createArrayGetterValue(values: unknown[]): CodeExpressionValue {\n return codeExpression(`() => [${values.map((value) => formatInlineLiteral(value)).join(', ')}]`);\n}\n\nexport function createReferenceGetterValue(\n references: Array<string | CodeValue>\n): CodeExpressionValue {\n return createArrayGetterValue(\n references.map((reference) =>\n typeof reference === 'string' ? codeReference(reference) : reference\n )\n );\n}\n\nexport function formatInlineLiteral(value: unknown): string {\n if (isCodeReferenceValue(value)) {\n return value.name;\n }\n if (isCodeExpressionValue(value)) {\n return value.code;\n }\n if (typeof value === 'string') {\n return formatStringLiteral(value);\n }\n if (typeof value === 'number' || typeof value === 'bigint') {\n return String(value);\n }\n if (typeof value === 'boolean') {\n return value ? 'true' : 'false';\n }\n if (value === null) {\n return 'null';\n }\n if (Array.isArray(value)) {\n return `[${value.map((item) => formatInlineLiteral(item)).join(', ')}]`;\n }\n if (isPlainObject(value)) {\n const entries = Object.entries(value).filter(([, entryValue]) => entryValue !== undefined);\n if (!entries.length) {\n return '{}';\n }\n return `{ ${entries\n .map(([key, entryValue]) => `${formatPropertyName(key)}: ${formatInlineLiteral(entryValue)}`)\n .join(', ')} }`;\n }\n return 'undefined';\n}\n\nfunction isCodeReferenceValue(value: unknown): value is CodeReferenceValue {\n return isPlainObject(value) && value.kind === 'reference' && typeof value.name === 'string';\n}\n\nfunction isCodeExpressionValue(value: unknown): value is CodeExpressionValue {\n return isPlainObject(value) && value.kind === 'expression' && typeof value.code === 'string';\n}\n\nfunction toCodeSource(value: string | CodeValue): string {\n if (typeof value === 'string') {\n return value;\n }\n\n if (isCodeReferenceValue(value)) {\n return value.name;\n }\n\n return value.code;\n}\n"],"mappings":";;;;AAeA,SAAgB,cAAc,MAAkC;AAC9D,QAAO;EACL,MAAM;EACN;EACD;;AAGH,SAAgB,eAAe,MAAmC;AAChE,QAAO;EACL,MAAM;EACN;EACD;;AAGH,SAAgB,YAAY,OAAoC;AAC9D,QAAO,qBAAqB,MAAM,IAAI,sBAAsB,MAAM;;AAGpE,SAAgB,mBACd,QACA,UACqB;AACrB,QAAO,eAAe,GAAG,aAAa,OAAO,CAAC,GAAG,WAAW;;AAG9D,SAAgB,SAAS,QAA4B,GAAG,MAAsC;AAC5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QAAO;;AAGT,SAAS,qBAAqB,OAA6C;AACzE,QAAO,cAAc,MAAM,IAAI,MAAM,SAAS,eAAe,OAAO,MAAM,SAAS;;AAGrF,SAAS,sBAAsB,OAA8C;AAC3E,QAAO,cAAc,MAAM,IAAI,MAAM,SAAS,gBAAgB,OAAO,MAAM,SAAS;;AAGtF,SAAS,aAAa,OAAmC;AACvD,KAAI,OAAO,UAAU,SACnB,QAAO;AAGT,KAAI,qBAAqB,MAAM,CAC7B,QAAO,MAAM;AAGf,QAAO,MAAM"}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { isPlainObject } from "./shared.js";
|
|
2
|
+
import { formatPropertyName, formatStringLiteral } from "./templates.js";
|
|
3
|
+
import { formatInlineLiteral, isCodeValue } from "./code-values.js";
|
|
4
|
+
import { resolveNonCollidingName } from "./naming.js";
|
|
5
|
+
import { IndentationText, NewLineKind, Project, QuoteKind, SyntaxKind, VariableDeclarationKind } from "ts-morph";
|
|
6
|
+
|
|
7
|
+
//#region src/commands/pull-v4/utils/factory-writer.ts
|
|
8
|
+
function createInMemoryProject() {
|
|
9
|
+
return new Project({
|
|
10
|
+
useInMemoryFileSystem: true,
|
|
11
|
+
skipLoadingLibFiles: true,
|
|
12
|
+
manipulationSettings: {
|
|
13
|
+
indentationText: IndentationText.TwoSpaces,
|
|
14
|
+
quoteKind: QuoteKind.Single,
|
|
15
|
+
newLineKind: NewLineKind.LineFeed,
|
|
16
|
+
useTrailingCommas: true
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
function addFactoryConfigVariable({ sourceFile, importName, variableName, isExported, syntaxKind = SyntaxKind.CallExpression }) {
|
|
21
|
+
const initializer = `${syntaxKind === SyntaxKind.NewExpression ? "new " : ""}${importName}({})`;
|
|
22
|
+
const [declaration] = sourceFile.addVariableStatement({
|
|
23
|
+
declarationKind: VariableDeclarationKind.Const,
|
|
24
|
+
isExported,
|
|
25
|
+
declarations: [{
|
|
26
|
+
name: variableName,
|
|
27
|
+
initializer
|
|
28
|
+
}]
|
|
29
|
+
}).getDeclarations();
|
|
30
|
+
const [configArg] = declaration.getInitializerIfKindOrThrow(syntaxKind).getArguments();
|
|
31
|
+
return { configObject: configArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression) };
|
|
32
|
+
}
|
|
33
|
+
function createFactoryDefinition({ importName, variableName: name, fileName = "definition.ts", moduleSpecifier = "@inkeep/agents-sdk", syntaxKind }) {
|
|
34
|
+
const sourceFile = createInMemoryProject().createSourceFile(fileName, "", { overwrite: true });
|
|
35
|
+
sourceFile.addImportDeclaration({
|
|
36
|
+
namedImports: [importName],
|
|
37
|
+
moduleSpecifier
|
|
38
|
+
});
|
|
39
|
+
const localVariableName = resolveNonCollidingName(name, collectTakenNames(sourceFile));
|
|
40
|
+
const shouldAliasExport = localVariableName !== name;
|
|
41
|
+
const { configObject } = addFactoryConfigVariable({
|
|
42
|
+
sourceFile,
|
|
43
|
+
importName,
|
|
44
|
+
variableName: localVariableName,
|
|
45
|
+
isExported: !shouldAliasExport,
|
|
46
|
+
syntaxKind
|
|
47
|
+
});
|
|
48
|
+
if (shouldAliasExport) sourceFile.addExportDeclaration({ namedExports: [{
|
|
49
|
+
name: localVariableName,
|
|
50
|
+
alias: name
|
|
51
|
+
}] });
|
|
52
|
+
return {
|
|
53
|
+
sourceFile,
|
|
54
|
+
configObject
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
function addStringProperty(configObject, key, value) {
|
|
58
|
+
configObject.addPropertyAssignment({
|
|
59
|
+
name: key,
|
|
60
|
+
initializer: formatStringLiteral(value)
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
function addValueToObject(obj, key, value) {
|
|
64
|
+
if (value === void 0) return;
|
|
65
|
+
if (isCodeValue(value)) {
|
|
66
|
+
obj.addPropertyAssignment({
|
|
67
|
+
name: formatPropertyName(key),
|
|
68
|
+
initializer: formatInlineLiteral(value)
|
|
69
|
+
});
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
if (isPlainObject(value)) {
|
|
73
|
+
const child = obj.addPropertyAssignment({
|
|
74
|
+
name: formatPropertyName(key),
|
|
75
|
+
initializer: "{}"
|
|
76
|
+
}).getInitializerIfKindOrThrow(SyntaxKind.ObjectLiteralExpression);
|
|
77
|
+
for (const [childKey, childValue] of Object.entries(value)) addValueToObject(child, childKey, childValue);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
if (Array.isArray(value)) {
|
|
81
|
+
const arrayLiteral = obj.addPropertyAssignment({
|
|
82
|
+
name: formatPropertyName(key),
|
|
83
|
+
initializer: "[]"
|
|
84
|
+
}).getInitializerIfKindOrThrow(SyntaxKind.ArrayLiteralExpression);
|
|
85
|
+
for (const item of value) addValueToArray(arrayLiteral, item);
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
obj.addPropertyAssignment({
|
|
89
|
+
name: formatPropertyName(key),
|
|
90
|
+
initializer: formatInlineLiteral(value)
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
function collectTakenNames(sourceFile) {
|
|
94
|
+
const takenNames = /* @__PURE__ */ new Set();
|
|
95
|
+
for (const importDeclaration of sourceFile.getImportDeclarations()) {
|
|
96
|
+
const defaultImport = importDeclaration.getDefaultImport()?.getText();
|
|
97
|
+
if (defaultImport) takenNames.add(defaultImport);
|
|
98
|
+
const namespaceImport = importDeclaration.getNamespaceImport()?.getText();
|
|
99
|
+
if (namespaceImport) takenNames.add(namespaceImport);
|
|
100
|
+
for (const namedImport of importDeclaration.getNamedImports()) {
|
|
101
|
+
const localName = namedImport.getAliasNode()?.getText() ?? namedImport.getName();
|
|
102
|
+
takenNames.add(localName);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
for (const variableDeclaration of sourceFile.getVariableDeclarations()) takenNames.add(variableDeclaration.getName());
|
|
106
|
+
return takenNames;
|
|
107
|
+
}
|
|
108
|
+
function addValueToArray(arr, value) {
|
|
109
|
+
if (isCodeValue(value)) {
|
|
110
|
+
arr.addElement(formatInlineLiteral(value));
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
if (isPlainObject(value)) {
|
|
114
|
+
const child = arr.addElement("{}").asKindOrThrow(SyntaxKind.ObjectLiteralExpression);
|
|
115
|
+
for (const [key, childValue] of Object.entries(value)) addValueToObject(child, key, childValue);
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
if (Array.isArray(value)) {
|
|
119
|
+
const child = arr.addElement("[]").asKindOrThrow(SyntaxKind.ArrayLiteralExpression);
|
|
120
|
+
for (const item of value) addValueToArray(child, item);
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
arr.addElement(formatInlineLiteral(value));
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
//#endregion
|
|
127
|
+
export { addFactoryConfigVariable, addStringProperty, addValueToObject, createFactoryDefinition, createInMemoryProject };
|
|
128
|
+
//# sourceMappingURL=factory-writer.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"factory-writer.js","names":[],"sources":["../../../../src/commands/pull-v4/utils/factory-writer.ts"],"sourcesContent":["import {\n type ArrayLiteralExpression,\n IndentationText,\n NewLineKind,\n type ObjectLiteralExpression,\n Project,\n QuoteKind,\n type SourceFile,\n SyntaxKind,\n VariableDeclarationKind,\n} from 'ts-morph';\nimport { formatInlineLiteral, isCodeValue } from './code-values';\nimport { resolveNonCollidingName } from './naming';\nimport { isPlainObject } from './shared';\nimport { formatPropertyName, formatStringLiteral } from './templates';\n\ninterface CreateFactoryDefinitionOptions\n extends Pick<AddFactoryConfigVariableOptions, 'syntaxKind' | 'importName' | 'variableName'> {\n fileName?: string;\n moduleSpecifier?: string;\n}\n\ninterface AddFactoryConfigVariableOptions {\n sourceFile: SourceFile;\n importName: string;\n variableName: string;\n isExported?: boolean;\n syntaxKind?: SyntaxKind.CallExpression | SyntaxKind.NewExpression;\n}\n\nexport function createInMemoryProject(): Project {\n return new Project({\n useInMemoryFileSystem: true,\n skipLoadingLibFiles: true,\n manipulationSettings: {\n indentationText: IndentationText.TwoSpaces,\n quoteKind: QuoteKind.Single,\n newLineKind: NewLineKind.LineFeed,\n useTrailingCommas: true,\n },\n });\n}\n\nexport function addFactoryConfigVariable({\n sourceFile,\n importName,\n variableName,\n isExported,\n syntaxKind = SyntaxKind.CallExpression,\n}: AddFactoryConfigVariableOptions): {\n configObject: ObjectLiteralExpression;\n} {\n const initializer = `${syntaxKind === SyntaxKind.NewExpression ? 'new ' : ''}${importName}({})`;\n const variableStatement = sourceFile.addVariableStatement({\n declarationKind: VariableDeclarationKind.Const,\n isExported,\n declarations: [{ name: variableName, initializer }],\n });\n const [declaration] = variableStatement.getDeclarations();\n const invocation = declaration.getInitializerIfKindOrThrow(syntaxKind);\n const [configArg] = invocation.getArguments();\n\n return {\n configObject: configArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression),\n };\n}\n\nexport function createFactoryDefinition({\n importName,\n variableName: name,\n fileName = 'definition.ts',\n moduleSpecifier = '@inkeep/agents-sdk',\n syntaxKind,\n}: CreateFactoryDefinitionOptions): {\n sourceFile: SourceFile;\n configObject: ObjectLiteralExpression;\n} {\n const sourceFile = createInMemoryProject().createSourceFile(fileName, '', {\n overwrite: true,\n });\n sourceFile.addImportDeclaration({ namedImports: [importName], moduleSpecifier });\n const localVariableName = resolveNonCollidingName(name, collectTakenNames(sourceFile));\n const shouldAliasExport = localVariableName !== name;\n const { configObject } = addFactoryConfigVariable({\n sourceFile,\n importName,\n variableName: localVariableName,\n isExported: !shouldAliasExport,\n syntaxKind,\n });\n if (shouldAliasExport) {\n sourceFile.addExportDeclaration({\n namedExports: [{ name: localVariableName, alias: name }],\n });\n }\n\n return {\n sourceFile,\n configObject,\n };\n}\n\nexport function addStringProperty(\n configObject: ObjectLiteralExpression,\n key: string,\n value: string\n): void {\n configObject.addPropertyAssignment({\n name: key,\n initializer: formatStringLiteral(value),\n });\n}\n\nexport function addValueToObject(obj: ObjectLiteralExpression, key: string, value: unknown): void {\n if (value === undefined) {\n return;\n }\n\n if (isCodeValue(value)) {\n obj.addPropertyAssignment({\n name: formatPropertyName(key),\n initializer: formatInlineLiteral(value),\n });\n return;\n }\n\n if (isPlainObject(value)) {\n const property = obj.addPropertyAssignment({\n name: formatPropertyName(key),\n initializer: '{}',\n });\n const child = property.getInitializerIfKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n for (const [childKey, childValue] of Object.entries(value)) {\n addValueToObject(child, childKey, childValue);\n }\n return;\n }\n\n if (Array.isArray(value)) {\n const property = obj.addPropertyAssignment({\n name: formatPropertyName(key),\n initializer: '[]',\n });\n const arrayLiteral = property.getInitializerIfKindOrThrow(SyntaxKind.ArrayLiteralExpression);\n for (const item of value) {\n addValueToArray(arrayLiteral, item);\n }\n return;\n }\n\n obj.addPropertyAssignment({\n name: formatPropertyName(key),\n initializer: formatInlineLiteral(value),\n });\n}\n\nfunction collectTakenNames(sourceFile: SourceFile): Set<string> {\n const takenNames = new Set<string>();\n\n for (const importDeclaration of sourceFile.getImportDeclarations()) {\n const defaultImport = importDeclaration.getDefaultImport()?.getText();\n if (defaultImport) {\n takenNames.add(defaultImport);\n }\n\n const namespaceImport = importDeclaration.getNamespaceImport()?.getText();\n if (namespaceImport) {\n takenNames.add(namespaceImport);\n }\n\n for (const namedImport of importDeclaration.getNamedImports()) {\n const localName = namedImport.getAliasNode()?.getText() ?? namedImport.getName();\n takenNames.add(localName);\n }\n }\n\n for (const variableDeclaration of sourceFile.getVariableDeclarations()) {\n takenNames.add(variableDeclaration.getName());\n }\n\n return takenNames;\n}\n\nfunction addValueToArray(arr: ArrayLiteralExpression, value: unknown): void {\n if (isCodeValue(value)) {\n arr.addElement(formatInlineLiteral(value));\n return;\n }\n\n if (isPlainObject(value)) {\n const expression = arr.addElement('{}');\n const child = expression.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n for (const [key, childValue] of Object.entries(value)) {\n addValueToObject(child, key, childValue);\n }\n return;\n }\n\n if (Array.isArray(value)) {\n const expression = arr.addElement('[]');\n const child = expression.asKindOrThrow(SyntaxKind.ArrayLiteralExpression);\n for (const item of value) {\n addValueToArray(child, item);\n }\n return;\n }\n\n arr.addElement(formatInlineLiteral(value));\n}\n"],"mappings":";;;;;;;AA8BA,SAAgB,wBAAiC;AAC/C,QAAO,IAAI,QAAQ;EACjB,uBAAuB;EACvB,qBAAqB;EACrB,sBAAsB;GACpB,iBAAiB,gBAAgB;GACjC,WAAW,UAAU;GACrB,aAAa,YAAY;GACzB,mBAAmB;GACpB;EACF,CAAC;;AAGJ,SAAgB,yBAAyB,EACvC,YACA,YACA,cACA,YACA,aAAa,WAAW,kBAGxB;CACA,MAAM,cAAc,GAAG,eAAe,WAAW,gBAAgB,SAAS,KAAK,WAAW;CAM1F,MAAM,CAAC,eALmB,WAAW,qBAAqB;EACxD,iBAAiB,wBAAwB;EACzC;EACA,cAAc,CAAC;GAAE,MAAM;GAAc;GAAa,CAAC;EACpD,CAAC,CACsC,iBAAiB;CAEzD,MAAM,CAAC,aADY,YAAY,4BAA4B,WAAW,CACvC,cAAc;AAE7C,QAAO,EACL,cAAc,UAAU,cAAc,WAAW,wBAAwB,EAC1E;;AAGH,SAAgB,wBAAwB,EACtC,YACA,cAAc,MACd,WAAW,iBACX,kBAAkB,sBAClB,cAIA;CACA,MAAM,aAAa,uBAAuB,CAAC,iBAAiB,UAAU,IAAI,EACxE,WAAW,MACZ,CAAC;AACF,YAAW,qBAAqB;EAAE,cAAc,CAAC,WAAW;EAAE;EAAiB,CAAC;CAChF,MAAM,oBAAoB,wBAAwB,MAAM,kBAAkB,WAAW,CAAC;CACtF,MAAM,oBAAoB,sBAAsB;CAChD,MAAM,EAAE,iBAAiB,yBAAyB;EAChD;EACA;EACA,cAAc;EACd,YAAY,CAAC;EACb;EACD,CAAC;AACF,KAAI,kBACF,YAAW,qBAAqB,EAC9B,cAAc,CAAC;EAAE,MAAM;EAAmB,OAAO;EAAM,CAAC,EACzD,CAAC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AAS,IAAI,YAAY,SAAS;AAChF,cAAW,IAAI,UAAU;;;AAI7B,MAAK,MAAM,uBAAuB,WAAW,yBAAyB,CACpE,YAAW,IAAI,oBAAoB,SAAS,CAAC;AAG/C,QAAO;;AAGT,SAAS,gBAAgB,KAA6B,OAAsB;AAC1E,KAAI,YAAY,MAAM,EAAE;AACtB,MAAI,WAAW,oBAAoB,MAAM,CAAC;AAC1C;;AAGF,KAAI,cAAc,MAAM,EAAE;EAExB,MAAM,QADa,IAAI,WAAW,KAAK,CACd,cAAc,WAAW,wBAAwB;AAC1E,OAAK,MAAM,CAAC,KAAK,eAAe,OAAO,QAAQ,MAAM,CACnD,kBAAiB,OAAO,KAAK,WAAW;AAE1C;;AAGF,KAAI,MAAM,QAAQ,MAAM,EAAE;EAExB,MAAM,QADa,IAAI,WAAW,KAAK,CACd,cAAc,WAAW,uBAAuB;AACzE,OAAK,MAAM,QAAQ,MACjB,iBAAgB,OAAO,KAAK;AAE9B;;AAGF,KAAI,WAAW,oBAAoB,MAAM,CAAC"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { expectSnapshots, hasReferences, isPlainObject } from "./shared.js";
|
|
2
|
+
import { TEMPLATE_VARIABLE_REGEX, collectTemplateVariableNames, formatPropertyName, formatStringLiteral, formatTemplate } from "./templates.js";
|
|
3
|
+
import { codeCall, codeExpression, codeMethodCall, codePropertyAccess, codeReference, createArrayGetterValue, createReferenceGetterValue, formatInlineLiteral, isCodeValue } from "./code-values.js";
|
|
4
|
+
import { buildComponentFileName, createUniqueReferenceName, isHumanReadableId, resolveNonCollidingName, resolveReferenceName, toCamelCase, toCredentialReferenceName, toKebabCase, toToolReferenceName, toTriggerReferenceName } from "./naming.js";
|
|
5
|
+
import { addFactoryConfigVariable, addStringProperty, addValueToObject, createFactoryDefinition, createInMemoryProject } from "./factory-writer.js";
|
|
6
|
+
import { convertJsonSchemaToZodSafe } from "./schema-rendering.js";
|
|
7
|
+
|
|
8
|
+
export { TEMPLATE_VARIABLE_REGEX, addFactoryConfigVariable, addStringProperty, addValueToObject, buildComponentFileName, codeCall, codeExpression, codeMethodCall, codePropertyAccess, codeReference, collectTemplateVariableNames, convertJsonSchemaToZodSafe, createArrayGetterValue, createFactoryDefinition, createInMemoryProject, createReferenceGetterValue, createUniqueReferenceName, expectSnapshots, formatInlineLiteral, formatPropertyName, formatStringLiteral, formatTemplate, hasReferences, isCodeValue, isHumanReadableId, isPlainObject, resolveNonCollidingName, resolveReferenceName, toCamelCase, toCredentialReferenceName, toKebabCase, toToolReferenceName, toTriggerReferenceName };
|