@kapeta/local-cluster-service 0.47.0 → 0.47.2

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.
@@ -3,17 +3,32 @@
3
3
  * Copyright 2023 Kapeta Inc.
4
4
  * SPDX-License-Identifier: BUSL-1.1
5
5
  */
6
- var __importDefault = (this && this.__importDefault) || function (mod) {
7
- return (mod && mod.__esModule) ? mod : { "default": mod };
8
- };
9
6
  Object.defineProperty(exports, "__esModule", { value: true });
10
7
  exports.StormEventParser = exports.resolveOptions = void 0;
11
8
  const nodejs_utils_1 = require("@kapeta/nodejs-utils");
12
9
  const kaplang_core_1 = require("@kapeta/kaplang-core");
13
- const node_uuid_1 = __importDefault(require("node-uuid"));
10
+ const uuid_1 = require("uuid");
14
11
  const definitionsManager_1 = require("../definitionsManager");
15
- const ngraph_graph_1 = __importDefault(require("ngraph.graph"));
16
- const ngraph_forcelayout_1 = __importDefault(require("ngraph.forcelayout"));
12
+ function prettifyKaplang(source) {
13
+ if (!source || !source.trim()) {
14
+ return '';
15
+ }
16
+ try {
17
+ const ast = kaplang_core_1.DSLParser.parse(source, {
18
+ ignoreSemantics: true,
19
+ types: true,
20
+ methods: true,
21
+ rest: true,
22
+ extends: true,
23
+ generics: true,
24
+ });
25
+ return kaplang_core_1.KaplangWriter.write(ast.entities ?? []);
26
+ }
27
+ catch (e) {
28
+ console.warn('Failed to prettify source:\n%s', source);
29
+ return source;
30
+ }
31
+ }
17
32
  async function resolveOptions() {
18
33
  // Predefined types for now - TODO: Allow user to select / change
19
34
  const blockTypeService = await definitionsManager_1.definitionsManager.getLatestDefinition('kapeta/block-type-service');
@@ -89,7 +104,6 @@ async function resolveOptions() {
89
104
  };
90
105
  }
91
106
  exports.resolveOptions = resolveOptions;
92
- const LAYOUT_MARGIN = 50;
93
107
  class StormEventParser {
94
108
  events = [];
95
109
  planName = '';
@@ -110,6 +124,7 @@ class StormEventParser {
110
124
  }
111
125
  addEvent(handle, evt) {
112
126
  this.events.push(evt);
127
+ console.log('evt', evt);
113
128
  switch (evt.type) {
114
129
  case 'CREATE_PLAN_PROPERTIES':
115
130
  this.planName = evt.payload.name;
@@ -131,13 +146,13 @@ class StormEventParser {
131
146
  this.error = evt.payload.error;
132
147
  break;
133
148
  case 'CREATE_API':
134
- this.blocks[evt.payload.blockName].apis.push(evt.payload.content);
149
+ this.blocks[evt.payload.blockName].apis.push(prettifyKaplang(evt.payload.content));
135
150
  break;
136
151
  case 'CREATE_TYPE':
137
- this.blocks[evt.payload.blockName].types.push(evt.payload.content);
152
+ this.blocks[evt.payload.blockName].types.push(prettifyKaplang(evt.payload.content));
138
153
  break;
139
154
  case 'CREATE_MODEL':
140
- this.blocks[evt.payload.blockName].models.push(evt.payload.content);
155
+ this.blocks[evt.payload.blockName].models.push(prettifyKaplang(evt.payload.content));
141
156
  break;
142
157
  case 'CREATE_CONNECTION':
143
158
  this.connections.push(evt.payload);
@@ -153,55 +168,21 @@ class StormEventParser {
153
168
  return this.events;
154
169
  }
155
170
  isValid() {
171
+ if (!this.planName) {
172
+ return false;
173
+ }
156
174
  return !this.failed;
157
175
  }
158
176
  getError() {
159
177
  return this.error;
160
178
  }
161
- applyLayoutToBlocks(result) {
162
- const graph = (0, ngraph_graph_1.default)();
163
- const blockInstances = {};
164
- result.plan.spec.blocks.forEach((block, index) => {
165
- graph.addNode(block.id, block);
166
- blockInstances[block.id] = block;
167
- });
168
- result.plan.spec.connections.forEach((connection) => {
169
- graph.addLink(connection.provider.blockId, connection.consumer.blockId);
170
- });
171
- const layout = (0, ngraph_forcelayout_1.default)(graph, {
172
- springLength: 150,
173
- debug: true,
174
- dimensions: 2,
175
- gravity: 2,
176
- springCoefficient: 0.0008,
177
- });
178
- for (let i = 0; i < 100; ++i) {
179
- layout.step();
180
- }
181
- // Layout might place things in negative space. We move everything to positive space
182
- const graphBox = layout.getGraphRect();
183
- let yAdjust = 0;
184
- let xAdjust = 0;
185
- if (graphBox.y1 < 0) {
186
- yAdjust = -graphBox.y1;
187
- }
188
- if (graphBox.x1 < 0) {
189
- xAdjust = -graphBox.x1;
190
- }
191
- graph.forEachNode((node) => {
192
- const position = layout.getNodePosition(node.id);
193
- blockInstances[node.id].dimensions.left = LAYOUT_MARGIN + Math.round(position.x + xAdjust);
194
- blockInstances[node.id].dimensions.top = LAYOUT_MARGIN + Math.round(position.y + yAdjust);
195
- });
196
- layout.dispose();
197
- return result;
198
- }
199
179
  toResult(handle) {
200
- const planRef = this.toRef(handle, this.planName);
180
+ const planRef = this.toRef(handle, this.planName ?? 'undefined');
201
181
  const blockDefinitions = this.toBlockDefinitions(handle);
202
182
  const refIdMap = {};
203
183
  const blocks = Object.entries(blockDefinitions).map(([ref, block]) => {
204
- const id = node_uuid_1.default.v4();
184
+ // Create a deterministic uuid
185
+ const id = (0, uuid_1.v5)(ref, uuid_1.v5.URL);
205
186
  refIdMap[ref] = id;
206
187
  return {
207
188
  id,
@@ -249,6 +230,28 @@ class StormEventParser {
249
230
  console.warn('Client resource not found: %s on %s', apiConnection.toResource, clientConsumerRef.toNormalizedString(), apiConnection);
250
231
  return;
251
232
  }
233
+ if (apiProviderBlock.content.spec.entities?.source?.value) {
234
+ if (!clientConsumerBlock.content.spec.entities) {
235
+ clientConsumerBlock.content.spec.entities = {
236
+ types: [],
237
+ source: {
238
+ type: kaplang_core_1.KAPLANG_ID,
239
+ version: kaplang_core_1.KAPLANG_VERSION,
240
+ value: '',
241
+ },
242
+ };
243
+ }
244
+ const clientTypes = kaplang_core_1.DSLDataTypeParser.parse(clientConsumerBlock.content.spec.entities.source.value);
245
+ const apiTypes = kaplang_core_1.DSLDataTypeParser.parse(apiProviderBlock.content.spec.entities?.source?.value);
246
+ apiTypes.forEach((apiType) => {
247
+ if (clientTypes.some((clientType) => clientType.name === apiType.name)) {
248
+ // Already exists
249
+ return;
250
+ }
251
+ clientTypes.push(apiType);
252
+ });
253
+ clientConsumerBlock.content.spec.entities.source.value = kaplang_core_1.KaplangWriter.write(clientTypes);
254
+ }
252
255
  clientResource.spec.methods = apiResource.spec.methods;
253
256
  clientResource.spec.source = apiResource.spec.source;
254
257
  });
@@ -267,9 +270,7 @@ class StormEventParser {
267
270
  blockId: refIdMap[fromRef.toNormalizedString()],
268
271
  resourceName: connection.fromResource,
269
272
  },
270
- mapping: {
271
- //TODO: Add mapping
272
- },
273
+ mapping: this.toConnectionMapping(handle, connection, blockDefinitions),
273
274
  };
274
275
  });
275
276
  const plan = {
@@ -284,10 +285,10 @@ class StormEventParser {
284
285
  connections,
285
286
  },
286
287
  };
287
- return this.applyLayoutToBlocks({
288
+ return {
288
289
  plan,
289
290
  blocks: Object.values(blockDefinitions),
290
- });
291
+ };
291
292
  }
292
293
  toSafeName(name) {
293
294
  return name.toLowerCase().replace(/[^0-9a-z-]/gi, '');
@@ -498,6 +499,33 @@ class StormEventParser {
498
499
  }
499
500
  return '';
500
501
  }
502
+ toConnectionMapping(handle, connection, blockDefinitions) {
503
+ if (connection.fromResourceType !== 'API') {
504
+ return;
505
+ }
506
+ const fromRef = this.toRef(handle, connection.fromComponent);
507
+ const apiProviderBlock = blockDefinitions[fromRef.toNormalizedString()];
508
+ if (!apiProviderBlock) {
509
+ console.warn('Provider block not found: %s', connection.fromComponent, connection);
510
+ return;
511
+ }
512
+ const apiResource = apiProviderBlock.content.spec.providers?.find((p) => p.kind === this.options.apiKind && p.metadata.name === connection.fromResource);
513
+ if (!apiResource) {
514
+ console.warn('API resource not found: %s on %s', connection.fromResource, fromRef.toNormalizedString(), connection);
515
+ return;
516
+ }
517
+ const apiMethods = kaplang_core_1.DSLConverters.toSchemaMethods(kaplang_core_1.DSLAPIParser.parse(apiResource.spec?.source?.value ?? '', {
518
+ ignoreSemantics: true,
519
+ }));
520
+ const mapping = {};
521
+ Object.entries(apiMethods).forEach(([methodId, method]) => {
522
+ mapping[methodId] = {
523
+ targetId: methodId,
524
+ type: 'EXACT',
525
+ };
526
+ });
527
+ return mapping;
528
+ }
501
529
  toPortType(type) {
502
530
  switch (type) {
503
531
  case 'API':
@@ -2,7 +2,7 @@
2
2
  * Copyright 2023 Kapeta Inc.
3
3
  * SPDX-License-Identifier: BUSL-1.1
4
4
  */
5
- import { StormDefinitions } from "./event-parser";
5
+ import { StormDefinitions } from './event-parser';
6
6
  export type StormResourceType = 'API' | 'DATABASE' | 'CLIENT' | 'JWTPROVIDER' | 'JWTCONSUMER' | 'WEBFRAGMENT' | 'WEBPAGE' | 'SMTPCLIENT' | 'EXTERNAL_API' | 'SUBSCRIBER' | 'PUBLISHER' | 'QUEUE' | 'EXCHANGE';
7
7
  export type StormBlockType = 'BACKEND' | 'FRONTEND' | 'GATEWAY' | 'MQ' | 'CLI' | 'DESKTOP';
8
8
  export interface StormBlockInfo {
@@ -117,6 +117,7 @@ export interface StormEventFile {
117
117
  payload: {
118
118
  filename: string;
119
119
  content: string;
120
+ blockName: string;
120
121
  blockRef: string;
121
122
  };
122
123
  }
@@ -28,6 +28,9 @@ class StormClient {
28
28
  if (api.hasToken()) {
29
29
  //headers['Authorization'] = `Bearer ${api.getAccessToken()}`; //TODO: Enable authentication
30
30
  }
31
+ if (body.conversationId) {
32
+ headers['conversationId'] = body.conversationId;
33
+ }
31
34
  return {
32
35
  url,
33
36
  method: method,
@@ -26,6 +26,7 @@ export interface ConversationItem {
26
26
  }
27
27
  export interface StormContextRequest<T = string> {
28
28
  history?: ConversationItem[];
29
+ conversationId?: string;
29
30
  prompt: T;
30
31
  }
31
32
  export interface StormFileInfo extends GeneratedFile {
@@ -150,16 +150,8 @@ describe('event-parser', () => {
150
150
  expect(dbResource?.spec.source.value).toContain('type Entity');
151
151
  const serviceBlockInstance = result.plan.spec.blocks[0];
152
152
  expect(serviceBlockInstance.name).toBe('service');
153
- expect(serviceBlockInstance.dimensions.width).toBe(150);
154
- expect(serviceBlockInstance.dimensions.height).toBe(200);
155
- expect(serviceBlockInstance.dimensions.top).toBe(3);
156
- expect(serviceBlockInstance.dimensions.left).toBe(6);
157
153
  const uiBlockInstance = result.plan.spec.blocks[1];
158
154
  expect(uiBlockInstance.name).toBe('ui');
159
- expect(uiBlockInstance.dimensions.width).toBe(150);
160
- expect(uiBlockInstance.dimensions.height).toBe(200);
161
- expect(uiBlockInstance.dimensions.top).toBe(107);
162
- expect(uiBlockInstance.dimensions.left).toBe(112);
163
155
  expect(result.plan.spec.connections.length).toBe(1);
164
156
  expect(result.plan.spec.connections[0].consumer.blockId).toBe(uiBlockInstance.id);
165
157
  expect(result.plan.spec.connections[0].consumer.resourceName).toBe(clientResource?.metadata.name);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kapeta/local-cluster-service",
3
- "version": "0.47.0",
3
+ "version": "0.47.2",
4
4
  "description": "Manages configuration, ports and service discovery for locally running Kapeta systems",
5
5
  "type": "commonjs",
6
6
  "exports": {
@@ -52,7 +52,7 @@
52
52
  "dependencies": {
53
53
  "@kapeta/codegen": "^1.4.0",
54
54
  "@kapeta/config-mapper": "^1.2.1",
55
- "@kapeta/kaplang-core": "^1.16.0",
55
+ "@kapeta/kaplang-core": "^1.17.1",
56
56
  "@kapeta/local-cluster-config": "^0.4.2",
57
57
  "@kapeta/nodejs-api-client": ">=0.2.0 <2",
58
58
  "@kapeta/nodejs-process": "^1.2.0",
@@ -74,8 +74,6 @@
74
74
  "gunzip-maybe": "^1.4.2",
75
75
  "lodash": "^4.17.15",
76
76
  "md5": "2.2.1",
77
- "ngraph.forcelayout": "^3.3.1",
78
- "ngraph.graph": "^20.0.1",
79
77
  "node-cache": "^5.1.2",
80
78
  "node-uuid": "^1.4.8",
81
79
  "parse-data-uri": "^0.2.0",
@@ -85,6 +83,7 @@
85
83
  "stream-json": "^1.8.0",
86
84
  "tar-stream": "^3.1.6",
87
85
  "typescript": "^5.1.6",
86
+ "uuid": "^9.0.1",
88
87
  "yaml": "^1.6.0"
89
88
  },
90
89
  "devDependencies": {
@@ -103,6 +102,7 @@
103
102
  "@types/node-uuid": "^0.0.29",
104
103
  "@types/request": "^2.48.8",
105
104
  "@types/tar-stream": "^2.2.2",
105
+ "@types/uuid": "^9.0.8",
106
106
  "eslint": "^8.42.0",
107
107
  "eslint-config-prettier": "^8.8.0",
108
108
  "jest": "^29.6.4",
@@ -8,7 +8,7 @@ import { AIFileTypes, BlockCodeGenerator, GeneratedFile, GeneratedResult } from
8
8
  import { BlockDefinition } from '@kapeta/schemas';
9
9
  import { codeGeneratorManager } from '../codeGeneratorManager';
10
10
  import { STORM_ID, stormClient } from './stormClient';
11
- import { ScreenTemplate, StormEvent, StormEventFile, StormEventScreen } from './events';
11
+ import { StormEvent, StormEventFile } from './events';
12
12
  import { BlockDefinitionInfo } from './event-parser';
13
13
  import { ConversationItem, StormFileImplementationPrompt, StormFileInfo, StormStream } from './stream';
14
14
  import { KapetaURI } from '@kapeta/nodejs-utils';
@@ -42,16 +42,16 @@ export class StormCodegen {
42
42
  return this.out;
43
43
  }
44
44
 
45
- private handleTemplateFileOutput(blockUri: KapetaURI, template: StormFileInfo, data: StormEvent) {
45
+ private handleTemplateFileOutput(blockUri: KapetaURI, aiName: string, template: StormFileInfo, data: StormEvent) {
46
46
  switch (data.type) {
47
47
  case 'FILE':
48
48
  template.filename = data.payload.filename;
49
49
  template.content = data.payload.content;
50
- return this.handleFileOutput(blockUri, data);
50
+ return this.handleFileOutput(blockUri, aiName, data);
51
51
  }
52
52
  }
53
53
 
54
- private handleUiOutput(blockUri: KapetaURI, data: StormEvent) {
54
+ private handleUiOutput(blockUri: KapetaURI, aiName: string, data: StormEvent) {
55
55
  switch (data.type) {
56
56
  case 'SCREEN':
57
57
  this.out.emit('data', {
@@ -60,18 +60,18 @@ export class StormCodegen {
60
60
  created: Date.now(),
61
61
  payload: {
62
62
  ...data.payload,
63
- blockName: blockUri.toNormalizedString(),
63
+ blockName: aiName,
64
64
  },
65
65
  });
66
66
  case 'FILE':
67
- return this.handleFileOutput(blockUri, data);
67
+ return this.handleFileOutput(blockUri, aiName, data);
68
68
  }
69
69
  }
70
70
 
71
- private handleFileOutput(blockUri: KapetaURI, data: StormEvent) {
71
+ private handleFileOutput(blockUri: KapetaURI, aiName: string, data: StormEvent) {
72
72
  switch (data.type) {
73
73
  case 'FILE':
74
- this.emitFile(blockUri, data.payload.filename, data.payload.content, data.reason);
74
+ this.emitFile(blockUri, aiName, data.payload.filename, data.payload.content, data.reason);
75
75
  return {
76
76
  type: 'FILE',
77
77
  created: Date.now(),
@@ -96,7 +96,7 @@ export class StormCodegen {
96
96
  const allFiles = this.toStormFiles(generatedResult);
97
97
 
98
98
  // Send all the non-ai files to the stream
99
- this.emitFiles(block.uri, allFiles);
99
+ this.emitFiles(block.uri, block.aiName, allFiles);
100
100
 
101
101
  const relevantFiles: StormFileInfo[] = allFiles.filter(
102
102
  (file) => file.type !== AIFileTypes.IGNORE && file.type !== AIFileTypes.WEB_SCREEN
@@ -112,7 +112,7 @@ export class StormCodegen {
112
112
  });
113
113
 
114
114
  uiStream.on('data', (evt) => {
115
- this.handleUiOutput(block.uri, evt);
115
+ this.handleUiOutput(block.uri, block.aiName, evt);
116
116
  });
117
117
 
118
118
  await uiStream.waitForDone();
@@ -128,6 +128,7 @@ export class StormCodegen {
128
128
  if (serviceFiles.length > 0) {
129
129
  await this.processTemplates(
130
130
  block.uri,
131
+ block.aiName,
131
132
  stormClient.createServiceImplementation.bind(stormClient),
132
133
  serviceFiles,
133
134
  contextFiles
@@ -138,7 +139,7 @@ export class StormCodegen {
138
139
  /**
139
140
  * Emits the text-based files to the stream
140
141
  */
141
- private emitFiles(uri: KapetaURI, files: StormFileInfo[]) {
142
+ private emitFiles(uri: KapetaURI, aiName: string, files: StormFileInfo[]) {
142
143
  files.forEach((file) => {
143
144
  if (!file.content || typeof file.content !== 'string') {
144
145
  return;
@@ -156,11 +157,17 @@ export class StormCodegen {
156
157
  return;
157
158
  }
158
159
 
159
- this.emitFile(uri, file.filename, file.content);
160
+ this.emitFile(uri, aiName, file.filename, file.content);
160
161
  });
161
162
  }
162
163
 
163
- private emitFile(uri: KapetaURI, filename: string, content: string, reason: string = 'File generated') {
164
+ private emitFile(
165
+ uri: KapetaURI,
166
+ blockName: string,
167
+ filename: string,
168
+ content: string,
169
+ reason: string = 'File generated'
170
+ ) {
164
171
  this.out.emit('data', {
165
172
  type: 'FILE',
166
173
  reason,
@@ -168,6 +175,7 @@ export class StormCodegen {
168
175
  payload: {
169
176
  filename: filename,
170
177
  content: content,
178
+ blockName,
171
179
  blockRef: uri.toNormalizedString(),
172
180
  },
173
181
  } satisfies StormEventFile);
@@ -178,6 +186,7 @@ export class StormCodegen {
178
186
  */
179
187
  private async processTemplates(
180
188
  blockUri: KapetaURI,
189
+ aiName: string,
181
190
  generator: ImplementationGenerator,
182
191
  templates: StormFileInfo[],
183
192
  contextFiles: StormFileInfo[]
@@ -192,7 +201,7 @@ export class StormCodegen {
192
201
  const files: StormEventFile[] = [];
193
202
 
194
203
  stream.on('data', (evt) => {
195
- const file = this.handleTemplateFileOutput(blockUri, templateFile, evt);
204
+ const file = this.handleTemplateFileOutput(blockUri, aiName, templateFile, evt);
196
205
  if (file) {
197
206
  files.push(file);
198
207
  }