@ptkl/toolkit 0.11.0 → 0.14.0
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/README.md +101 -0
- package/dist/bin/toolkit.js +0 -0
- package/dist/commands/forge.js +582 -28
- package/dist/commands/index.js +4 -0
- package/dist/commands/kortex.js +106 -0
- package/dist/commands/logs.js +109 -0
- package/dist/lib/kortex/bridge.js +113 -0
- package/dist/lib/kortex/config.js +21 -0
- package/dist/lib/kortex/conversations.js +84 -0
- package/dist/lib/kortex/mcp.js +193 -0
- package/dist/lib/kortex/session.js +759 -0
- package/dist/lib/kortex/tools.js +406 -0
- package/dist/lib/kortex/ui/App.js +455 -0
- package/dist/lib/kortex/ui/SelectAgent.js +23 -0
- package/package.json +11 -2
package/dist/commands/forge.js
CHANGED
|
@@ -2,10 +2,11 @@ import { Command } from "commander";
|
|
|
2
2
|
import { build, createServer } from 'vite';
|
|
3
3
|
import { c } from 'tar';
|
|
4
4
|
import { Writable } from "stream";
|
|
5
|
-
import { writeFileSync, readFileSync, rmSync, existsSync } from "fs";
|
|
5
|
+
import { writeFileSync, readFileSync, rmSync, existsSync, mkdirSync } from "fs";
|
|
6
|
+
import { execSync } from "child_process";
|
|
6
7
|
import axios from 'axios';
|
|
7
8
|
import Util from "../lib/util.js";
|
|
8
|
-
import { extname, isAbsolute, join } from 'path';
|
|
9
|
+
import { dirname, extname, isAbsolute, join } from 'path';
|
|
9
10
|
import { forgeDevKernelPlugin } from '../lib/forgeDevKernelPlugin.js';
|
|
10
11
|
function formatBuildError(reason) {
|
|
11
12
|
const lines = [];
|
|
@@ -81,7 +82,16 @@ class ForgeCommand {
|
|
|
81
82
|
.requiredOption("-p, --path <path>", "Path is directory where app is located.")
|
|
82
83
|
.option("--platform-url <url>", "Platform UI URL (e.g. http://localhost:8081) — required for window.requestForgePermissions in dev mode")
|
|
83
84
|
.option("-m, --mode <mode>", "Vite mode (controls which .env.[mode] files are loaded). Defaults to 'development'.")
|
|
85
|
+
.option("--env <env>", "Run for a specific env only (dev or live)")
|
|
86
|
+
.option("--view <view>", "Which view to serve (defaults to 'main')")
|
|
84
87
|
.action(this.runDev))
|
|
88
|
+
.addCommand(new Command("setup")
|
|
89
|
+
.description("Scaffold a new Forge app in a directory (ptkl.config.js, vite, index.html, entry, deps)")
|
|
90
|
+
.requiredOption("-p, --path <path>", "Directory to create the app in (created if missing).")
|
|
91
|
+
.option("-n, --name <name>", "App name (kebab-case). Defaults to the folder name.")
|
|
92
|
+
.option("-t, --type <type>", "App type: platform | public. Defaults to platform.")
|
|
93
|
+
.option("--no-install", "Skip running npm install after scaffolding.")
|
|
94
|
+
.action(this.setup))
|
|
85
95
|
.addCommand(new Command("list")
|
|
86
96
|
.description("List all available apps")
|
|
87
97
|
.action(this.listApps))
|
|
@@ -99,14 +109,15 @@ class ForgeCommand {
|
|
|
99
109
|
.action((options) => this.uninstall(options)));
|
|
100
110
|
}
|
|
101
111
|
async bundle(options) {
|
|
102
|
-
const { path, upload, mode } = options;
|
|
112
|
+
const { path: rawPath, upload, mode } = options;
|
|
113
|
+
const path = isAbsolute(rawPath) ? rawPath : join(process.cwd(), rawPath);
|
|
103
114
|
// Store original working directory
|
|
104
115
|
const originalCwd = process.cwd();
|
|
105
116
|
try {
|
|
106
117
|
// Change to the app directory
|
|
107
118
|
process.chdir(path);
|
|
108
119
|
const module = await import(`${path}/ptkl.config.js`);
|
|
109
|
-
const { views, name, version, distPath, icon, type, label, permissions, install_permissions, runtime_permissions, entitlements, requires, scripts, ssrRenderer, } = module.default ?? {};
|
|
120
|
+
const { views, name, version, distPath: distPath = join(path, 'dist'), icon, type, label, permissions, install_permissions, runtime_permissions, entitlements, requires, scripts, services, ssrRenderer, } = module.default ?? {};
|
|
110
121
|
const iconBase64 = encodeIcon(icon, path);
|
|
111
122
|
// Clean dist folder before building to remove stale files
|
|
112
123
|
if (existsSync(distPath)) {
|
|
@@ -118,11 +129,23 @@ class ForgeCommand {
|
|
|
118
129
|
if (rtPerms.length + ents.length > 100) {
|
|
119
130
|
throw new Error(`Combined runtime_permissions (${rtPerms.length}) and entitlements (${ents.length}) must not exceed 100 entries`);
|
|
120
131
|
}
|
|
132
|
+
// Normalize views: support both string entries and object entries with access/permissions
|
|
133
|
+
const normalizedViews = {};
|
|
134
|
+
if (views) {
|
|
135
|
+
for (const [viewName, viewDef] of Object.entries(views)) {
|
|
136
|
+
if (typeof viewDef === 'string') {
|
|
137
|
+
normalizedViews[viewName] = { entry: viewDef };
|
|
138
|
+
}
|
|
139
|
+
else {
|
|
140
|
+
normalizedViews[viewName] = viewDef;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
121
144
|
// build manifest file
|
|
122
145
|
const manifest = {
|
|
123
146
|
name,
|
|
124
147
|
version,
|
|
125
|
-
views: {},
|
|
148
|
+
...(type !== 'service' && { views: {} }),
|
|
126
149
|
label,
|
|
127
150
|
icon: iconBase64,
|
|
128
151
|
permissions,
|
|
@@ -131,9 +154,20 @@ class ForgeCommand {
|
|
|
131
154
|
entitlements: entitlements ?? [],
|
|
132
155
|
requires: requires ?? null,
|
|
133
156
|
scripts: {},
|
|
134
|
-
type: type || 'platform',
|
|
157
|
+
type: type || 'platform',
|
|
135
158
|
ssrRenderer,
|
|
136
159
|
};
|
|
160
|
+
// Add services to manifest if defined
|
|
161
|
+
if (services && services.length > 0) {
|
|
162
|
+
manifest.services = services.map((svc) => ({
|
|
163
|
+
name: svc.name,
|
|
164
|
+
script: `services/${svc.name}.js`,
|
|
165
|
+
access: svc.access || 'public',
|
|
166
|
+
...(svc.label && { label: svc.label }),
|
|
167
|
+
...(svc.description && { description: svc.description }),
|
|
168
|
+
...(svc.permissions && { permissions: svc.permissions }),
|
|
169
|
+
}));
|
|
170
|
+
}
|
|
137
171
|
// Different build approach for public vs platform apps
|
|
138
172
|
if (type === 'public') {
|
|
139
173
|
// Public apps: standard SPA build with index.html
|
|
@@ -194,10 +228,21 @@ class ForgeCommand {
|
|
|
194
228
|
console.log("✅ All builds completed successfully");
|
|
195
229
|
}
|
|
196
230
|
else {
|
|
197
|
-
// Platform apps: custom bundle format with views and
|
|
231
|
+
// Platform/service apps: custom bundle format with views, scripts, and services
|
|
198
232
|
const bundleBasePath = `/luma/appservice/v1/forge/static/bundle/${name}/${version}/`;
|
|
199
|
-
const buildViews = Object.keys(
|
|
200
|
-
|
|
233
|
+
const buildViews = Object.keys(normalizedViews).map(async (view) => {
|
|
234
|
+
const viewDef = normalizedViews[view];
|
|
235
|
+
// Store view with access info in manifest
|
|
236
|
+
if (viewDef.access || viewDef.permissions) {
|
|
237
|
+
manifest.views[view] = {
|
|
238
|
+
entry: `${view}.bundle.js`,
|
|
239
|
+
access: viewDef.access || (type === 'public' ? 'public' : 'platform'),
|
|
240
|
+
...(viewDef.permissions && { permissions: viewDef.permissions }),
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
else {
|
|
244
|
+
manifest.views[view] = `${view}.bundle.js`;
|
|
245
|
+
}
|
|
201
246
|
try {
|
|
202
247
|
const result = await build({
|
|
203
248
|
root: path,
|
|
@@ -207,10 +252,10 @@ class ForgeCommand {
|
|
|
207
252
|
outDir: distPath,
|
|
208
253
|
emptyOutDir: false,
|
|
209
254
|
rollupOptions: {
|
|
210
|
-
input:
|
|
255
|
+
input: viewDef.entry,
|
|
211
256
|
output: {
|
|
212
257
|
format: 'esm',
|
|
213
|
-
entryFileNames:
|
|
258
|
+
entryFileNames: `${view}.bundle.js`,
|
|
214
259
|
assetFileNames: (assetInfo) => {
|
|
215
260
|
return '[name].[ext]'; // Example: Customize the output file name format
|
|
216
261
|
},
|
|
@@ -306,12 +351,12 @@ class ForgeCommand {
|
|
|
306
351
|
if (failedViews.length > 0) {
|
|
307
352
|
console.error('\n❌ Failed to build views:');
|
|
308
353
|
failedViews.forEach((result, index) => {
|
|
309
|
-
const viewNames = Object.keys(
|
|
354
|
+
const viewNames = Object.keys(normalizedViews);
|
|
310
355
|
const failedIndices = viewResults.map((r, i) => r.status === 'rejected' ? i : -1).filter(i => i >= 0);
|
|
311
356
|
const viewName = viewNames[failedIndices[index]];
|
|
312
357
|
const reason = result.reason;
|
|
313
358
|
console.error(`\n View: ${viewName}`);
|
|
314
|
-
console.error(` Input: ${
|
|
359
|
+
console.error(` Input: ${normalizedViews[viewName].entry}`);
|
|
315
360
|
console.error(formatBuildError(reason));
|
|
316
361
|
});
|
|
317
362
|
throw new Error('View build failed. See errors above.');
|
|
@@ -333,6 +378,75 @@ class ForgeCommand {
|
|
|
333
378
|
throw new Error('Script build failed. See errors above.');
|
|
334
379
|
}
|
|
335
380
|
}
|
|
381
|
+
// Build service scripts
|
|
382
|
+
if (services && services.length > 0) {
|
|
383
|
+
const servicesDir = join(distPath, 'services');
|
|
384
|
+
if (!existsSync(servicesDir)) {
|
|
385
|
+
mkdirSync(servicesDir, { recursive: true });
|
|
386
|
+
}
|
|
387
|
+
const buildServices = services.map(async (svc) => {
|
|
388
|
+
try {
|
|
389
|
+
const result = await build({
|
|
390
|
+
root: path,
|
|
391
|
+
mode: mode ?? 'production',
|
|
392
|
+
base: bundleBasePath,
|
|
393
|
+
build: {
|
|
394
|
+
outDir: servicesDir,
|
|
395
|
+
emptyOutDir: false,
|
|
396
|
+
target: 'esnext',
|
|
397
|
+
rollupOptions: {
|
|
398
|
+
input: svc.script,
|
|
399
|
+
external: ['axios'],
|
|
400
|
+
output: {
|
|
401
|
+
format: 'esm',
|
|
402
|
+
entryFileNames: `${svc.name}.js`,
|
|
403
|
+
assetFileNames: '[name].[ext]',
|
|
404
|
+
manualChunks: undefined,
|
|
405
|
+
inlineDynamicImports: true,
|
|
406
|
+
}
|
|
407
|
+
},
|
|
408
|
+
},
|
|
409
|
+
plugins: [
|
|
410
|
+
{
|
|
411
|
+
name: 'wrap-service-script',
|
|
412
|
+
generateBundle(options, bundle) {
|
|
413
|
+
for (const fileName in bundle) {
|
|
414
|
+
const chunk = bundle[fileName];
|
|
415
|
+
if (chunk.type === 'chunk' && chunk.code) {
|
|
416
|
+
let code = chunk.code;
|
|
417
|
+
code = code.replace(/import\s+([\w$]+)\s+from\s*['"]axios['"]\s*;?\n?/g, 'const $1=axiosAdapter;\n');
|
|
418
|
+
code = code.replace(/import\s*\{([^}]+)\}\s*from\s*['"]axios['"]\s*;?\n?/g, (_, imports) => imports.split(',').map((part) => {
|
|
419
|
+
const [orig, alias] = part.trim().split(/\s+as\s+/).map((s) => s.trim());
|
|
420
|
+
return `const ${alias || orig}=axiosAdapter${orig === 'default' || !alias ? '' : `.${orig}`};\n`;
|
|
421
|
+
}).join(''));
|
|
422
|
+
chunk.code = code;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
]
|
|
428
|
+
});
|
|
429
|
+
return result;
|
|
430
|
+
}
|
|
431
|
+
catch (error) {
|
|
432
|
+
throw error;
|
|
433
|
+
}
|
|
434
|
+
});
|
|
435
|
+
const serviceResults = await Promise.allSettled(buildServices);
|
|
436
|
+
const failedServices = serviceResults.filter(r => r.status === 'rejected');
|
|
437
|
+
if (failedServices.length > 0) {
|
|
438
|
+
console.error('\n❌ Failed to build services:');
|
|
439
|
+
failedServices.forEach((result, index) => {
|
|
440
|
+
const failedIndices = serviceResults.map((r, i) => r.status === 'rejected' ? i : -1).filter(i => i >= 0);
|
|
441
|
+
const svc = services[failedIndices[index]];
|
|
442
|
+
const reason = result.reason;
|
|
443
|
+
console.error(`\n Service: ${svc.name}`);
|
|
444
|
+
console.error(` Input: ${svc.script}`);
|
|
445
|
+
console.error(formatBuildError(reason));
|
|
446
|
+
});
|
|
447
|
+
throw new Error('Service build failed. See errors above.');
|
|
448
|
+
}
|
|
449
|
+
}
|
|
336
450
|
console.log("✅ All builds completed successfully");
|
|
337
451
|
}
|
|
338
452
|
console.log("Packaging app...");
|
|
@@ -372,16 +486,25 @@ class ForgeCommand {
|
|
|
372
486
|
}
|
|
373
487
|
}
|
|
374
488
|
async runDev(options) {
|
|
375
|
-
const { path, platformUrl, mode } = options;
|
|
489
|
+
const { path: rawPath, platformUrl, mode, env, view: viewFlag } = options;
|
|
490
|
+
const path = isAbsolute(rawPath) ? rawPath : join(process.cwd(), rawPath);
|
|
376
491
|
const host = Util.getCurrentProfile().host;
|
|
377
|
-
// Load ptkl.config.js to discover views and app name
|
|
492
|
+
// Load ptkl.config.js to discover views, services, and app name
|
|
378
493
|
let appName;
|
|
379
494
|
let views;
|
|
495
|
+
let rawViews;
|
|
496
|
+
let services;
|
|
497
|
+
let appType;
|
|
380
498
|
try {
|
|
381
|
-
console.log(`${path}/ptkl.config.js`);
|
|
382
499
|
const configModule = await import(`${path}/ptkl.config.js`);
|
|
383
500
|
appName = configModule.default?.name;
|
|
384
|
-
|
|
501
|
+
rawViews = configModule.default?.views;
|
|
502
|
+
// Normalize: extract entry path regardless of whether view is a string or object
|
|
503
|
+
views = rawViews
|
|
504
|
+
? Object.fromEntries(Object.entries(rawViews).map(([k, v]) => [k, typeof v === 'string' ? v : v.entry]))
|
|
505
|
+
: undefined;
|
|
506
|
+
services = configModule.default?.services;
|
|
507
|
+
appType = configModule.default?.type || 'platform';
|
|
385
508
|
}
|
|
386
509
|
catch (err) {
|
|
387
510
|
// no manifest found – continue without view watch publishing
|
|
@@ -393,26 +516,116 @@ class ForgeCommand {
|
|
|
393
516
|
console.log(hubStatus === 'started'
|
|
394
517
|
? `🔌 Dev hub started on http://localhost:${DEV_HUB_PORT}`
|
|
395
518
|
: `🔌 Reusing existing dev hub on http://localhost:${DEV_HUB_PORT}`);
|
|
396
|
-
//
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
519
|
+
// Resolve the entry for the selected view
|
|
520
|
+
const selectedView = viewFlag ?? 'main';
|
|
521
|
+
let viewEntry;
|
|
522
|
+
if (views && views[selectedView]) {
|
|
523
|
+
viewEntry = views[selectedView];
|
|
524
|
+
if (viewEntry.startsWith(path)) {
|
|
525
|
+
viewEntry = '/' + viewEntry.slice(path.length).replace(/^[/\\]+/, '');
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
else if (viewFlag) {
|
|
529
|
+
const available = views ? Object.keys(views).join(', ') : 'none';
|
|
530
|
+
console.error(`❌ View "${selectedView}" not found in manifest. Available views: ${available}`);
|
|
531
|
+
process.exit(1);
|
|
532
|
+
}
|
|
533
|
+
// Find a free port for the service dev proxy so multiple apps can run in parallel
|
|
534
|
+
let servicePort;
|
|
535
|
+
if (services && services.length > 0) {
|
|
536
|
+
const net = await import('net');
|
|
537
|
+
servicePort = await new Promise((resolve, reject) => {
|
|
538
|
+
const srv = net.default.createServer();
|
|
539
|
+
srv.listen(0, () => {
|
|
540
|
+
const port = srv.address().port;
|
|
541
|
+
srv.close(() => resolve(port));
|
|
542
|
+
});
|
|
543
|
+
srv.on('error', reject);
|
|
544
|
+
});
|
|
545
|
+
}
|
|
546
|
+
// Start Vite dev server
|
|
400
547
|
const server = await createServer({
|
|
401
548
|
root: path,
|
|
402
549
|
mode: mode ?? 'development',
|
|
550
|
+
resolve: {
|
|
551
|
+
// One React instance even when @ptkl/components is npm-linked (the
|
|
552
|
+
// linked repo carries its own node_modules/react) — two copies break
|
|
553
|
+
// hooks ("Invalid hook call") as soon as app code renders JSX.
|
|
554
|
+
dedupe: ['react', 'react-dom'],
|
|
555
|
+
},
|
|
403
556
|
define: {
|
|
404
557
|
__ENV_VARIABLES__: JSON.stringify({
|
|
405
558
|
API_HOST: host,
|
|
406
559
|
INTEGRATION_API: `${host}/luma/integrations`,
|
|
407
560
|
PROJECT_API_TOKEN: Util.getCurrentProfile().token,
|
|
561
|
+
PROJECT_ENV: env ?? "dev",
|
|
562
|
+
...(servicePort ? { FORGE_DEV_SERVICE_URL: `http://localhost:${servicePort}` } : {}),
|
|
408
563
|
}),
|
|
409
564
|
DEV_HUB_PORT
|
|
410
565
|
},
|
|
411
|
-
plugins: [
|
|
566
|
+
plugins: [
|
|
567
|
+
forgeDevKernelPlugin(appName, platformUrl),
|
|
568
|
+
{
|
|
569
|
+
// Console bridge (dev only): when the app runs EMBEDDED (e.g. the
|
|
570
|
+
// Studio's Preview iframe), forward console output + uncaught errors
|
|
571
|
+
// to the parent via postMessage so the host can show the app's OWN
|
|
572
|
+
// browser console. No-op when the page is top-level.
|
|
573
|
+
name: 'ptkl-console-bridge',
|
|
574
|
+
transformIndexHtml() {
|
|
575
|
+
return [
|
|
576
|
+
{
|
|
577
|
+
tag: 'script',
|
|
578
|
+
injectTo: 'head-prepend',
|
|
579
|
+
children: `(function () {
|
|
580
|
+
if (window.parent === window) return;
|
|
581
|
+
var send = function (level, args) {
|
|
582
|
+
try {
|
|
583
|
+
var msg = args.map(function (a) {
|
|
584
|
+
if (typeof a === 'string') return a;
|
|
585
|
+
if (a instanceof Error) return a.stack || a.message;
|
|
586
|
+
try { return JSON.stringify(a); } catch (e) { return String(a); }
|
|
587
|
+
}).join(' ');
|
|
588
|
+
window.parent.postMessage({ type: 'ptkl-console', level: level, message: msg }, '*');
|
|
589
|
+
} catch (e) { /* never break the app over logging */ }
|
|
590
|
+
};
|
|
591
|
+
['log', 'info', 'warn', 'error', 'debug'].forEach(function (k) {
|
|
592
|
+
var orig = console[k];
|
|
593
|
+
console[k] = function () {
|
|
594
|
+
send(k, Array.prototype.slice.call(arguments));
|
|
595
|
+
return orig.apply(console, arguments);
|
|
596
|
+
};
|
|
597
|
+
});
|
|
598
|
+
window.addEventListener('error', function (e) {
|
|
599
|
+
send('error', [e.message + (e.filename ? ' (' + e.filename + ':' + e.lineno + ')' : '')]);
|
|
600
|
+
});
|
|
601
|
+
window.addEventListener('unhandledrejection', function (e) {
|
|
602
|
+
var r = e.reason;
|
|
603
|
+
send('error', ['Unhandled rejection: ' + (r && r.message ? r.message : String(r))]);
|
|
604
|
+
});
|
|
605
|
+
})();`,
|
|
606
|
+
},
|
|
607
|
+
];
|
|
608
|
+
},
|
|
609
|
+
},
|
|
610
|
+
// Swap the entry in index.html to the selected view's entry
|
|
611
|
+
...(viewFlag && viewEntry ? [{
|
|
612
|
+
name: 'ptkl-view-entry',
|
|
613
|
+
transformIndexHtml(html) {
|
|
614
|
+
// Find the actual app entry script in index.html and replace its src.
|
|
615
|
+
// Can't use a generic regex — Vite injects /@vite/client as another
|
|
616
|
+
// <script type="module" src="..."> before the app entry.
|
|
617
|
+
let mainEntry = views?.['main'];
|
|
618
|
+
if (mainEntry?.startsWith(path)) {
|
|
619
|
+
mainEntry = '/' + mainEntry.slice(path.length).replace(/^[/\\]+/, '');
|
|
620
|
+
}
|
|
621
|
+
return html.replace(mainEntry, viewEntry);
|
|
622
|
+
},
|
|
623
|
+
}] : []),
|
|
624
|
+
],
|
|
412
625
|
});
|
|
413
626
|
await server.listen();
|
|
414
627
|
console.log('Current profile:', Util.getCurrentProfile().name);
|
|
415
|
-
console.log(
|
|
628
|
+
console.log(`Dev server running at: ${server?.resolvedUrls?.local[0]}${viewFlag ? ` (view: ${selectedView})` : ''}`);
|
|
416
629
|
// Build every view declared in ptkl.config.js in watch mode.
|
|
417
630
|
// On each successful rebuild the bundle is pushed to the dev hub so any
|
|
418
631
|
// other locally-running app that embeds this view via AppView picks it up instantly.
|
|
@@ -423,8 +636,20 @@ class ForgeCommand {
|
|
|
423
636
|
// Build output goes to a per-app temp dir so concurrent forge dev runs don't clash
|
|
424
637
|
const tmpDir = join(os.default.tmpdir(), `ptkl-dev-${appName}`);
|
|
425
638
|
mkdirSync(tmpDir, { recursive: true });
|
|
426
|
-
|
|
427
|
-
|
|
639
|
+
// Only watch-build platform views (not main, not public) — those are the ones
|
|
640
|
+
// embeddable via AppView in other apps. Main and public views are standalone.
|
|
641
|
+
const embeddableViews = Object.keys(views).filter(name => {
|
|
642
|
+
if (name === 'main')
|
|
643
|
+
return false;
|
|
644
|
+
const raw = rawViews?.[name];
|
|
645
|
+
if (typeof raw === 'object' && raw.access === 'public')
|
|
646
|
+
return false;
|
|
647
|
+
return true;
|
|
648
|
+
});
|
|
649
|
+
if (embeddableViews.length > 0) {
|
|
650
|
+
console.log(`👁️ Watching embeddable views for "${appName}": [${embeddableViews.join(', ')}]`);
|
|
651
|
+
}
|
|
652
|
+
for (const viewName of embeddableViews) {
|
|
428
653
|
// Use a per-view output dir so each view's assets don't collide
|
|
429
654
|
// (two views could otherwise both emit a file named from their input, e.g. `index.css`)
|
|
430
655
|
const viewOutDir = join(tmpDir, viewName);
|
|
@@ -487,6 +712,332 @@ class ForgeCommand {
|
|
|
487
712
|
});
|
|
488
713
|
}
|
|
489
714
|
}
|
|
715
|
+
// --- Local service dev server ---
|
|
716
|
+
if (appName && services && services.length > 0) {
|
|
717
|
+
const os = await import('os');
|
|
718
|
+
const http = await import('http');
|
|
719
|
+
const { join } = await import('path');
|
|
720
|
+
const { readFileSync, existsSync, mkdirSync } = await import('fs');
|
|
721
|
+
const { randomUUID } = await import('crypto');
|
|
722
|
+
const profile = Util.getCurrentProfile();
|
|
723
|
+
const serviceDir = join(os.default.tmpdir(), `ptkl-dev-${appName}`, '_services');
|
|
724
|
+
mkdirSync(serviceDir, { recursive: true });
|
|
725
|
+
// In-memory map of service name → latest bundled code
|
|
726
|
+
const serviceBundles = {};
|
|
727
|
+
console.log(`⚙️ Building services for "${appName}": [${services.map((s) => s.name).join(', ')}]`);
|
|
728
|
+
// Build each service in watch mode
|
|
729
|
+
for (const svc of services) {
|
|
730
|
+
const svcOutDir = join(serviceDir, svc.name);
|
|
731
|
+
mkdirSync(svcOutDir, { recursive: true });
|
|
732
|
+
const watcher = (await build({
|
|
733
|
+
root: path,
|
|
734
|
+
mode: mode ?? 'production',
|
|
735
|
+
logLevel: 'silent',
|
|
736
|
+
build: {
|
|
737
|
+
outDir: svcOutDir,
|
|
738
|
+
emptyOutDir: false,
|
|
739
|
+
target: 'esnext',
|
|
740
|
+
watch: {},
|
|
741
|
+
rollupOptions: {
|
|
742
|
+
input: svc.script,
|
|
743
|
+
external: ['axios'],
|
|
744
|
+
output: {
|
|
745
|
+
format: 'esm',
|
|
746
|
+
entryFileNames: `${svc.name}.js`,
|
|
747
|
+
manualChunks: undefined,
|
|
748
|
+
inlineDynamicImports: true,
|
|
749
|
+
},
|
|
750
|
+
},
|
|
751
|
+
},
|
|
752
|
+
plugins: [
|
|
753
|
+
{
|
|
754
|
+
name: 'wrap-service-dev',
|
|
755
|
+
generateBundle(_options, bundle) {
|
|
756
|
+
for (const fileName in bundle) {
|
|
757
|
+
const chunk = bundle[fileName];
|
|
758
|
+
if (chunk.type === 'chunk' && chunk.code) {
|
|
759
|
+
let code = chunk.code;
|
|
760
|
+
code = code.replace(/import\s+([\w$]+)\s+from\s*['"]axios['"]\s*;?\n?/g, 'const $1=axiosAdapter;\n');
|
|
761
|
+
code = code.replace(/import\s*\{([^}]+)\}\s*from\s*['"]axios['"]\s*;?\n?/g, (_, imports) => imports.split(',').map((part) => {
|
|
762
|
+
const [orig, alias] = part.trim().split(/\s+as\s+/).map((s) => s.trim());
|
|
763
|
+
return `const ${alias || orig}=axiosAdapter${orig === 'default' || !alias ? '' : `.${orig}`};\n`;
|
|
764
|
+
}).join(''));
|
|
765
|
+
chunk.code = code;
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
},
|
|
769
|
+
},
|
|
770
|
+
],
|
|
771
|
+
}));
|
|
772
|
+
// Seed from the initial build (BUNDLE_END may have fired before the listener below is attached)
|
|
773
|
+
const initialFile = join(svcOutDir, `${svc.name}.js`);
|
|
774
|
+
if (existsSync(initialFile)) {
|
|
775
|
+
const content = readFileSync(initialFile, 'utf-8');
|
|
776
|
+
if (content.trim()) {
|
|
777
|
+
serviceBundles[svc.name] = content;
|
|
778
|
+
console.log(`✅ [${appName}/${svc.name}] service built`);
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
watcher.on('event', (event) => {
|
|
782
|
+
if (event.code === 'BUNDLE_END') {
|
|
783
|
+
const file = join(svcOutDir, `${svc.name}.js`);
|
|
784
|
+
if (existsSync(file)) {
|
|
785
|
+
serviceBundles[svc.name] = readFileSync(file, 'utf-8');
|
|
786
|
+
console.log(`🔄 [${appName}/${svc.name}] service rebuilt`);
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
if (event.code === 'ERROR') {
|
|
790
|
+
console.error(`❌ [${appName}/${svc.name}] service build error:`, event.error?.message ?? event.error);
|
|
791
|
+
}
|
|
792
|
+
});
|
|
793
|
+
}
|
|
794
|
+
// Build a lookup of service config by name
|
|
795
|
+
const serviceConfig = {};
|
|
796
|
+
for (const svc of services) {
|
|
797
|
+
serviceConfig[svc.name] = svc;
|
|
798
|
+
}
|
|
799
|
+
const SERVICE_PORT = servicePort;
|
|
800
|
+
const server = http.default.createServer(async (req, res) => {
|
|
801
|
+
// CORS
|
|
802
|
+
res.setHeader('Access-Control-Allow-Origin', '*');
|
|
803
|
+
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
|
|
804
|
+
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
|
|
805
|
+
if (req.method === 'OPTIONS') {
|
|
806
|
+
res.writeHead(204);
|
|
807
|
+
res.end();
|
|
808
|
+
return;
|
|
809
|
+
}
|
|
810
|
+
const url = new URL(req.url || '/', `http://localhost:${SERVICE_PORT}`);
|
|
811
|
+
const serviceName = url.pathname.replace(/^\//, '').replace(/\/$/, '');
|
|
812
|
+
if (!serviceName || serviceName === '') {
|
|
813
|
+
// List available services
|
|
814
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
815
|
+
res.end(JSON.stringify({
|
|
816
|
+
app: appName,
|
|
817
|
+
type: appType,
|
|
818
|
+
services: services.map((s) => ({
|
|
819
|
+
name: s.name,
|
|
820
|
+
access: s.access || 'public',
|
|
821
|
+
url: `http://localhost:${SERVICE_PORT}/${s.name}`,
|
|
822
|
+
})),
|
|
823
|
+
}, null, 2));
|
|
824
|
+
return;
|
|
825
|
+
}
|
|
826
|
+
const code = serviceBundles[serviceName];
|
|
827
|
+
if (!code) {
|
|
828
|
+
res.writeHead(404, { 'Content-Type': 'application/json' });
|
|
829
|
+
res.end(JSON.stringify({ error: `Service "${serviceName}" not found` }));
|
|
830
|
+
return;
|
|
831
|
+
}
|
|
832
|
+
// Read request body
|
|
833
|
+
const chunks = [];
|
|
834
|
+
for await (const chunk of req)
|
|
835
|
+
chunks.push(chunk);
|
|
836
|
+
const rawBody = Buffer.concat(chunks).toString();
|
|
837
|
+
let parsedBody = {};
|
|
838
|
+
try {
|
|
839
|
+
parsedBody = rawBody ? JSON.parse(rawBody) : {};
|
|
840
|
+
}
|
|
841
|
+
catch {
|
|
842
|
+
parsedBody = rawBody;
|
|
843
|
+
}
|
|
844
|
+
// Parse query params
|
|
845
|
+
const query = {};
|
|
846
|
+
url.searchParams.forEach((v, k) => { query[k] = v; });
|
|
847
|
+
// Build request headers object
|
|
848
|
+
const reqHeaders = {};
|
|
849
|
+
for (const [k, v] of Object.entries(req.headers)) {
|
|
850
|
+
if (typeof v === 'string')
|
|
851
|
+
reqHeaders[k] = v;
|
|
852
|
+
}
|
|
853
|
+
const svcConf = serviceConfig[serviceName];
|
|
854
|
+
const executionId = randomUUID();
|
|
855
|
+
console.log(`→ ${req.method} /${serviceName} (${executionId.slice(0, 8)})`);
|
|
856
|
+
try {
|
|
857
|
+
const evalResponse = await axios.post(`${profile.host}/luma/forge-runtime/api/services/exec`, {
|
|
858
|
+
expression: code,
|
|
859
|
+
project_uuid: 'dev',
|
|
860
|
+
env: env ?? 'dev',
|
|
861
|
+
actor: profile.token,
|
|
862
|
+
context: {
|
|
863
|
+
appUuid: `dev-${appName}`,
|
|
864
|
+
appName,
|
|
865
|
+
serviceName,
|
|
866
|
+
executionId,
|
|
867
|
+
access: svcConf?.access || 'public',
|
|
868
|
+
},
|
|
869
|
+
input: parsedBody,
|
|
870
|
+
body: parsedBody,
|
|
871
|
+
query,
|
|
872
|
+
headers: reqHeaders,
|
|
873
|
+
}, {
|
|
874
|
+
headers: {
|
|
875
|
+
'Content-Type': 'application/json',
|
|
876
|
+
'Authorization': `Bearer ${profile.token}`,
|
|
877
|
+
},
|
|
878
|
+
timeout: 310000,
|
|
879
|
+
validateStatus: () => true,
|
|
880
|
+
});
|
|
881
|
+
const data = evalResponse.data;
|
|
882
|
+
if (data.logs?.length) {
|
|
883
|
+
data.logs.forEach((log) => console.log(` 📋 [${serviceName}] ${log}`));
|
|
884
|
+
}
|
|
885
|
+
if (data.error) {
|
|
886
|
+
res.writeHead(evalResponse.status || 500, { 'Content-Type': 'application/json' });
|
|
887
|
+
res.end(JSON.stringify({ error: data.error, logs: data.logs }));
|
|
888
|
+
console.log(` ❌ [${serviceName}] ${data.error}`);
|
|
889
|
+
}
|
|
890
|
+
else if (data.response) {
|
|
891
|
+
const resp = data.response;
|
|
892
|
+
const status = resp.statusCode || 200;
|
|
893
|
+
const contentType = resp.contentType || 'application/json';
|
|
894
|
+
res.writeHead(status, { 'Content-Type': contentType });
|
|
895
|
+
res.end(typeof resp.body === 'string' ? resp.body : JSON.stringify(resp.body));
|
|
896
|
+
console.log(` ✅ [${serviceName}] ${status} ${contentType}`);
|
|
897
|
+
}
|
|
898
|
+
else {
|
|
899
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
900
|
+
res.end(JSON.stringify(data));
|
|
901
|
+
console.log(` ✅ [${serviceName}] 200`);
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
catch (err) {
|
|
905
|
+
const msg = err.response?.data?.message || err.message;
|
|
906
|
+
res.writeHead(502, { 'Content-Type': 'application/json' });
|
|
907
|
+
res.end(JSON.stringify({ error: `Eval server error: ${msg}` }));
|
|
908
|
+
console.error(` ❌ [${serviceName}] ${msg}`);
|
|
909
|
+
}
|
|
910
|
+
});
|
|
911
|
+
server.listen(SERVICE_PORT, () => {
|
|
912
|
+
console.log(`\n⚡ Service dev server running at http://localhost:${SERVICE_PORT}`);
|
|
913
|
+
for (const svc of services) {
|
|
914
|
+
console.log(` POST http://localhost:${SERVICE_PORT}/${svc.name}`);
|
|
915
|
+
}
|
|
916
|
+
console.log('');
|
|
917
|
+
});
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
async setup(options) {
|
|
921
|
+
const { path: rawPath, name: nameOpt, type: typeOpt, install } = options;
|
|
922
|
+
const path = isAbsolute(rawPath) ? rawPath : join(process.cwd(), rawPath);
|
|
923
|
+
mkdirSync(join(path, 'src', 'components'), { recursive: true });
|
|
924
|
+
const folder = path.split(/[/\\]/).filter(Boolean).pop() || 'my-app';
|
|
925
|
+
const name = (nameOpt || folder)
|
|
926
|
+
.toLowerCase()
|
|
927
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
928
|
+
.replace(/^-+|-+$/g, '') || 'my-app';
|
|
929
|
+
const type = typeOpt === 'public' ? 'public' : 'platform';
|
|
930
|
+
// @ptkl/components is a NORMAL npm dependency (pulled on `npm install`,
|
|
931
|
+
// resolved from node_modules): it provides both the reusable Forge
|
|
932
|
+
// components AND the runtime (renderView + the neutral renderer + the
|
|
933
|
+
// component registry) via its `@ptkl/components/runtime` subpath — see
|
|
934
|
+
// src/main.tsx. Runtime + components are thus versioned once, in
|
|
935
|
+
// @ptkl/components, and the Studio canvas and the built app render the same.
|
|
936
|
+
const files = {
|
|
937
|
+
'package.json': JSON.stringify({
|
|
938
|
+
name,
|
|
939
|
+
private: true,
|
|
940
|
+
version: '0.1.0',
|
|
941
|
+
type: 'module',
|
|
942
|
+
scripts: { dev: 'ptkl forge dev -p .', bundle: 'ptkl forge bundle -p .' },
|
|
943
|
+
dependencies: {
|
|
944
|
+
'@ptkl/components': '^0.13.0',
|
|
945
|
+
react: '^19.0.0',
|
|
946
|
+
'react-dom': '^19.0.0',
|
|
947
|
+
},
|
|
948
|
+
devDependencies: {
|
|
949
|
+
vite: '^7.0.0',
|
|
950
|
+
'@vitejs/plugin-react': '^4.0.0',
|
|
951
|
+
typescript: '^5.0.0',
|
|
952
|
+
'@types/react': '^19.0.0',
|
|
953
|
+
'@types/react-dom': '^19.0.0',
|
|
954
|
+
},
|
|
955
|
+
}, null, 2) + '\n',
|
|
956
|
+
// dedupe: one React instance even when @ptkl/components is npm-linked
|
|
957
|
+
// (the linked repo has its own node_modules/react) — two copies break hooks.
|
|
958
|
+
'vite.config.js': `import { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\nexport default defineConfig({\n plugins: [react()],\n resolve: { dedupe: ['react', 'react-dom'] },\n})\n`,
|
|
959
|
+
'index.html': `<!doctype html>\n<html lang="en">\n <head>\n <meta charset="UTF-8" />\n <meta name="viewport" content="width=device-width, initial-scale=1.0" />\n <title>${name}</title>\n </head>\n <body>\n <div id="root"></div>\n <script type="module" src="/src/main.tsx"></script>\n </body>\n</html>\n`,
|
|
960
|
+
'tsconfig.json': JSON.stringify({
|
|
961
|
+
compilerOptions: {
|
|
962
|
+
target: 'ES2020',
|
|
963
|
+
useDefineForClassFields: true,
|
|
964
|
+
lib: ['ES2020', 'DOM', 'DOM.Iterable'],
|
|
965
|
+
module: 'ESNext',
|
|
966
|
+
skipLibCheck: true,
|
|
967
|
+
moduleResolution: 'bundler',
|
|
968
|
+
resolveJsonModule: true,
|
|
969
|
+
jsx: 'react-jsx',
|
|
970
|
+
strict: true,
|
|
971
|
+
noEmit: true,
|
|
972
|
+
},
|
|
973
|
+
include: ['src'],
|
|
974
|
+
}, null, 2) + '\n',
|
|
975
|
+
'.gitignore': 'node_modules\ndist\n',
|
|
976
|
+
'ptkl.config.js': `export default {\n name: '${name}',\n version: '0.1.0',\n type: '${type}',\n label: { en_US: '${name}' },\n icon: 'icon.svg',\n views: {\n main: 'src/main.tsx',\n },\n}\n`,
|
|
977
|
+
'icon.svg': `<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="#6C63FF"/><text x="32" y="42" font-family="system-ui, sans-serif" font-size="34" font-weight="700" fill="#fff" text-anchor="middle">P</text></svg>\n`,
|
|
978
|
+
// GENERATED entry — constant boilerplate. Renders this view's document with
|
|
979
|
+
// the Protokol runtime. Platform apps compose SessionProvider (user +
|
|
980
|
+
// permissions from the Forge host); public apps don't. Regenerated by the
|
|
981
|
+
// Studio on save; never hand-edit.
|
|
982
|
+
'src/main.tsx': type === 'platform'
|
|
983
|
+
? `import { renderView } from '@ptkl/components/runtime'\nimport { SessionProvider } from '@ptkl/components'\nimport doc from '../_studio_/views/main.json'\nimport studio from '../ptkl.studio.json'\n\nrenderView(document.getElementById('root')!, doc, studio, { providers: [SessionProvider] })\n`
|
|
984
|
+
: `import { renderView } from '@ptkl/components/runtime'\nimport doc from '../_studio_/views/main.json'\nimport studio from '../ptkl.studio.json'\n\nrenderView(document.getElementById('root')!, doc, studio)\n`,
|
|
985
|
+
// Minimal empty view; the Studio overwrites this with the authored tree.
|
|
986
|
+
'_studio_/views/main.json': JSON.stringify({
|
|
987
|
+
mode: 'visual',
|
|
988
|
+
access: type === 'public' ? 'public' : 'platform',
|
|
989
|
+
routes: {
|
|
990
|
+
index: {
|
|
991
|
+
path: '/',
|
|
992
|
+
rootId: 'root',
|
|
993
|
+
nodes: {
|
|
994
|
+
root: { id: 'root', type: '@protokol/ui/Stack', props: {}, children: [] },
|
|
995
|
+
},
|
|
996
|
+
},
|
|
997
|
+
},
|
|
998
|
+
defaultRoute: 'index',
|
|
999
|
+
routeOrder: ['index'],
|
|
1000
|
+
}, null, 2) + '\n',
|
|
1001
|
+
'ptkl.studio.json': JSON.stringify({ theme: { colors: [] }, customCss: '', components: {} }, null, 2) + '\n',
|
|
1002
|
+
};
|
|
1003
|
+
for (const [rel, content] of Object.entries(files)) {
|
|
1004
|
+
const full = join(path, rel);
|
|
1005
|
+
mkdirSync(dirname(full), { recursive: true }); // nested paths (_studio_/views/…)
|
|
1006
|
+
if (!existsSync(full))
|
|
1007
|
+
writeFileSync(full, content); // never clobber existing files
|
|
1008
|
+
}
|
|
1009
|
+
console.log(`✅ Scaffolded Forge app "${name}" (${type}) in ${path}`);
|
|
1010
|
+
if (install !== false) {
|
|
1011
|
+
console.log('📦 Installing dependencies…');
|
|
1012
|
+
try {
|
|
1013
|
+
execSync('npm install', { cwd: path, stdio: 'inherit' });
|
|
1014
|
+
}
|
|
1015
|
+
catch (err) {
|
|
1016
|
+
console.error(`⚠️ npm install failed: ${err.message}`);
|
|
1017
|
+
}
|
|
1018
|
+
// Local dev: prefer a globally-linked @ptkl/components build if one exists
|
|
1019
|
+
// (`npm link` in the protokol-components repo), so the app resolves
|
|
1020
|
+
// @ptkl/components/runtime before that version is published. Harmless no-op
|
|
1021
|
+
// when there is no global link — the declared published version is used.
|
|
1022
|
+
try {
|
|
1023
|
+
execSync('npm link @ptkl/components', { cwd: path, stdio: 'ignore' });
|
|
1024
|
+
}
|
|
1025
|
+
catch {
|
|
1026
|
+
/* no global link — fall back to the installed @ptkl/components */
|
|
1027
|
+
}
|
|
1028
|
+
// The app's entry imports @ptkl/components/runtime; verify the resolved
|
|
1029
|
+
// package actually ships it (the currently PUBLISHED 0.13.0 does not — it
|
|
1030
|
+
// needs the local link until a runtime-bearing version is published).
|
|
1031
|
+
// Without this check the failure surfaces later as an opaque Vite error.
|
|
1032
|
+
const runtimeOk = existsSync(join(path, 'node_modules', '@ptkl', 'components', 'dist', 'runtime.esm.js')) ||
|
|
1033
|
+
existsSync(join(path, 'node_modules', '@ptkl', 'components', 'dist', 'runtime.js'));
|
|
1034
|
+
if (!runtimeOk) {
|
|
1035
|
+
console.warn('⚠️ The installed @ptkl/components has no "runtime" export — `ptkl forge dev` will fail.\n' +
|
|
1036
|
+
' Fix: run `npm link` in your local protokol-components repo (after `npm run build`),\n' +
|
|
1037
|
+
' or publish a @ptkl/components version that includes ./runtime.');
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
console.log('\nNext: ptkl forge dev -p .');
|
|
490
1041
|
}
|
|
491
1042
|
async removeVersion(options) {
|
|
492
1043
|
const { ref, version } = options;
|
|
@@ -502,7 +1053,8 @@ class ForgeCommand {
|
|
|
502
1053
|
console.log(data);
|
|
503
1054
|
}
|
|
504
1055
|
async install(options) {
|
|
505
|
-
const { path, env, bundle } = options;
|
|
1056
|
+
const { path: rawPath, env, bundle } = options;
|
|
1057
|
+
const path = isAbsolute(rawPath) ? rawPath : join(process.cwd(), rawPath);
|
|
506
1058
|
if (bundle)
|
|
507
1059
|
await this.bundle({ path, upload: false });
|
|
508
1060
|
const envs = env ? [env] : ['dev', 'live'];
|
|
@@ -511,7 +1063,8 @@ class ForgeCommand {
|
|
|
511
1063
|
}
|
|
512
1064
|
}
|
|
513
1065
|
async uninstall(options) {
|
|
514
|
-
const { path, env, bundle } = options;
|
|
1066
|
+
const { path: rawPath, env, bundle } = options;
|
|
1067
|
+
const path = isAbsolute(rawPath) ? rawPath : join(process.cwd(), rawPath);
|
|
515
1068
|
if (bundle)
|
|
516
1069
|
await this.bundle({ path, upload: false });
|
|
517
1070
|
const envs = env ? [env] : ['dev', 'live'];
|
|
@@ -520,6 +1073,7 @@ class ForgeCommand {
|
|
|
520
1073
|
}
|
|
521
1074
|
}
|
|
522
1075
|
static async _runScript(appPath, scriptType, env = 'dev') {
|
|
1076
|
+
appPath = isAbsolute(appPath) ? appPath : join(process.cwd(), appPath);
|
|
523
1077
|
const module = await import(`${appPath}/ptkl.config.js`);
|
|
524
1078
|
const { name, distPath, scripts } = module.default ?? {};
|
|
525
1079
|
if (!name)
|
|
@@ -556,7 +1110,7 @@ class ForgeCommand {
|
|
|
556
1110
|
delete global.window;
|
|
557
1111
|
delete global.axiosAdapter;
|
|
558
1112
|
if (result && result._error_) {
|
|
559
|
-
const displayMessage = result.message ||
|
|
1113
|
+
const displayMessage = result?.response?.data?.message || result.message ||
|
|
560
1114
|
(result.errors && result.errors.length > 0
|
|
561
1115
|
? result.errors.map((e) => e.message || e.code).filter(Boolean).join(', ')
|
|
562
1116
|
: result.name) ||
|