@ptkl/toolkit 0.10.4 → 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.
@@ -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 = [];
@@ -69,6 +70,7 @@ class ForgeCommand {
69
70
  .description("Bundle app")
70
71
  .requiredOption("-p, --path <path>", "Path is directory where app is located.")
71
72
  .option("-u, --upload", "Upload bundle")
73
+ .option("-m, --mode <mode>", "Vite build mode (controls which .env.[mode] files are loaded). Defaults to 'production'.")
72
74
  .action(this.bundle))
73
75
  .addCommand(new Command("remove-version")
74
76
  .description("Remove version of app")
@@ -79,7 +81,17 @@ class ForgeCommand {
79
81
  .description("Run dev app")
80
82
  .requiredOption("-p, --path <path>", "Path is directory where app is located.")
81
83
  .option("--platform-url <url>", "Platform UI URL (e.g. http://localhost:8081) — required for window.requestForgePermissions in dev mode")
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')")
82
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))
83
95
  .addCommand(new Command("list")
84
96
  .description("List all available apps")
85
97
  .action(this.listApps))
@@ -97,14 +109,15 @@ class ForgeCommand {
97
109
  .action((options) => this.uninstall(options)));
98
110
  }
99
111
  async bundle(options) {
100
- const { path, upload } = options;
112
+ const { path: rawPath, upload, mode } = options;
113
+ const path = isAbsolute(rawPath) ? rawPath : join(process.cwd(), rawPath);
101
114
  // Store original working directory
102
115
  const originalCwd = process.cwd();
103
116
  try {
104
117
  // Change to the app directory
105
118
  process.chdir(path);
106
119
  const module = await import(`${path}/ptkl.config.js`);
107
- 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 ?? {};
108
121
  const iconBase64 = encodeIcon(icon, path);
109
122
  // Clean dist folder before building to remove stale files
110
123
  if (existsSync(distPath)) {
@@ -116,11 +129,23 @@ class ForgeCommand {
116
129
  if (rtPerms.length + ents.length > 100) {
117
130
  throw new Error(`Combined runtime_permissions (${rtPerms.length}) and entitlements (${ents.length}) must not exceed 100 entries`);
118
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
+ }
119
144
  // build manifest file
120
145
  const manifest = {
121
146
  name,
122
147
  version,
123
- views: {},
148
+ ...(type !== 'service' && { views: {} }),
124
149
  label,
125
150
  icon: iconBase64,
126
151
  permissions,
@@ -129,9 +154,20 @@ class ForgeCommand {
129
154
  entitlements: entitlements ?? [],
130
155
  requires: requires ?? null,
131
156
  scripts: {},
132
- type: type || 'platform', // default to 'platform' if not specified
157
+ type: type || 'platform',
133
158
  ssrRenderer,
134
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
+ }
135
171
  // Different build approach for public vs platform apps
136
172
  if (type === 'public') {
137
173
  // Public apps: standard SPA build with index.html
@@ -139,6 +175,7 @@ class ForgeCommand {
139
175
  try {
140
176
  await build({
141
177
  root: path,
178
+ mode: mode ?? 'production',
142
179
  build: {
143
180
  outDir: distPath,
144
181
  emptyOutDir: true,
@@ -157,6 +194,7 @@ class ForgeCommand {
157
194
  console.log('Building SSR renderer...');
158
195
  await build({
159
196
  root: path,
197
+ mode: mode ?? 'production',
160
198
  build: {
161
199
  outDir: distPath,
162
200
  emptyOutDir: false,
@@ -190,22 +228,34 @@ class ForgeCommand {
190
228
  console.log("✅ All builds completed successfully");
191
229
  }
192
230
  else {
193
- // Platform apps: custom bundle format with views and scripts
231
+ // Platform/service apps: custom bundle format with views, scripts, and services
194
232
  const bundleBasePath = `/luma/appservice/v1/forge/static/bundle/${name}/${version}/`;
195
- const buildViews = Object.keys(views).map(async (view) => {
196
- manifest.views[view] = `${view}.bundle.js`;
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
+ }
197
246
  try {
198
247
  const result = await build({
199
248
  root: path,
249
+ mode: mode ?? 'production',
200
250
  base: bundleBasePath,
201
251
  build: {
202
252
  outDir: distPath,
203
253
  emptyOutDir: false,
204
254
  rollupOptions: {
205
- input: views[view],
255
+ input: viewDef.entry,
206
256
  output: {
207
257
  format: 'esm',
208
- entryFileNames: `[name].bundle.js`,
258
+ entryFileNames: `${view}.bundle.js`,
209
259
  assetFileNames: (assetInfo) => {
210
260
  return '[name].[ext]'; // Example: Customize the output file name format
211
261
  },
@@ -225,9 +275,9 @@ class ForgeCommand {
225
275
  const runtimeBaseResolver = `const __ptklForgeBundleBase=()=>{const env=typeof window!=='undefined'&&window.__ENV_VARIABLES__?window.__ENV_VARIABLES__.API_HOST:'';const host=typeof env==='string'?env.replace(/\\/$/,''):'';return host+'${bundleBasePath}';};\n`;
226
276
  chunk.code = runtimeBaseResolver + chunk.code;
227
277
  // Transform dynamic imports in the final bundled code
228
- chunk.code = chunk.code.replace(/import\(['"`]\.\/([^'"`]+)['"`]\)/g, `dynamicImport(__ptklForgeBundleBase() + '$1')`);
278
+ chunk.code = chunk.code.replace(/import\(['`"]\.\/([^'`"]+)['`"]\)/g, `dynamicImport(__ptklForgeBundleBase() + '$1')`);
229
279
  // Also handle relative paths without ./
230
- chunk.code = chunk.code.replace(/import\(['"`]([^'"`\/]+\.js)['"`]\)/g, `dynamicImport(__ptklForgeBundleBase() + '$1')`);
280
+ chunk.code = chunk.code.replace(/import\(['`"]([^'`"\/]+\.js)['`"]\)/g, `dynamicImport(__ptklForgeBundleBase() + '$1')`);
231
281
  }
232
282
  }
233
283
  }
@@ -245,6 +295,7 @@ class ForgeCommand {
245
295
  try {
246
296
  const result = await build({
247
297
  root: path,
298
+ mode: mode ?? 'production',
248
299
  base: bundleBasePath,
249
300
  build: {
250
301
  outDir: distPath,
@@ -300,12 +351,12 @@ class ForgeCommand {
300
351
  if (failedViews.length > 0) {
301
352
  console.error('\n❌ Failed to build views:');
302
353
  failedViews.forEach((result, index) => {
303
- const viewNames = Object.keys(views);
354
+ const viewNames = Object.keys(normalizedViews);
304
355
  const failedIndices = viewResults.map((r, i) => r.status === 'rejected' ? i : -1).filter(i => i >= 0);
305
356
  const viewName = viewNames[failedIndices[index]];
306
357
  const reason = result.reason;
307
358
  console.error(`\n View: ${viewName}`);
308
- console.error(` Input: ${views[viewName]}`);
359
+ console.error(` Input: ${normalizedViews[viewName].entry}`);
309
360
  console.error(formatBuildError(reason));
310
361
  });
311
362
  throw new Error('View build failed. See errors above.');
@@ -327,6 +378,75 @@ class ForgeCommand {
327
378
  throw new Error('Script build failed. See errors above.');
328
379
  }
329
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
+ }
330
450
  console.log("✅ All builds completed successfully");
331
451
  }
332
452
  console.log("Packaging app...");
@@ -366,16 +486,25 @@ class ForgeCommand {
366
486
  }
367
487
  }
368
488
  async runDev(options) {
369
- const { path, platformUrl } = options;
489
+ const { path: rawPath, platformUrl, mode, env, view: viewFlag } = options;
490
+ const path = isAbsolute(rawPath) ? rawPath : join(process.cwd(), rawPath);
370
491
  const host = Util.getCurrentProfile().host;
371
- // Load ptkl.config.js to discover views and app name
492
+ // Load ptkl.config.js to discover views, services, and app name
372
493
  let appName;
373
494
  let views;
495
+ let rawViews;
496
+ let services;
497
+ let appType;
374
498
  try {
375
- console.log(`${path}/ptkl.config.js`);
376
499
  const configModule = await import(`${path}/ptkl.config.js`);
377
500
  appName = configModule.default?.name;
378
- views = configModule.default?.views;
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';
379
508
  }
380
509
  catch (err) {
381
510
  // no manifest found – continue without view watch publishing
@@ -387,26 +516,116 @@ class ForgeCommand {
387
516
  console.log(hubStatus === 'started'
388
517
  ? `🔌 Dev hub started on http://localhost:${DEV_HUB_PORT}`
389
518
  : `🔌 Reusing existing dev hub on http://localhost:${DEV_HUB_PORT}`);
390
- // Start Vite dev server for the app, injecting window.__PTKL_DEV_HUB__ so AppView
391
- // inside this app automatically knows where to fetch local view bundles from.
392
- // The forgeDevKernelPlugin polyfills window.requestForgePermissions and other forge
393
- // kernel globals that normally come from the platform-forge runtime.
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
394
547
  const server = await createServer({
395
548
  root: path,
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
+ },
396
556
  define: {
397
557
  __ENV_VARIABLES__: JSON.stringify({
398
558
  API_HOST: host,
399
559
  INTEGRATION_API: `${host}/luma/integrations`,
400
560
  PROJECT_API_TOKEN: Util.getCurrentProfile().token,
401
- PLATFORM_URL: platformUrl ? platformUrl : "https://platform.protokol.io"
561
+ PROJECT_ENV: env ?? "dev",
562
+ ...(servicePort ? { FORGE_DEV_SERVICE_URL: `http://localhost:${servicePort}` } : {}),
402
563
  }),
403
564
  DEV_HUB_PORT
404
565
  },
405
- plugins: [forgeDevKernelPlugin(appName, platformUrl ?? 'https://platform.protokol.io')],
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
+ ],
406
625
  });
407
626
  await server.listen();
408
627
  console.log('Current profile:', Util.getCurrentProfile().name);
409
- console.log('Dev server running at:', server?.resolvedUrls?.local[0]);
628
+ console.log(`Dev server running at: ${server?.resolvedUrls?.local[0]}${viewFlag ? ` (view: ${selectedView})` : ''}`);
410
629
  // Build every view declared in ptkl.config.js in watch mode.
411
630
  // On each successful rebuild the bundle is pushed to the dev hub so any
412
631
  // other locally-running app that embeds this view via AppView picks it up instantly.
@@ -417,8 +636,20 @@ class ForgeCommand {
417
636
  // Build output goes to a per-app temp dir so concurrent forge dev runs don't clash
418
637
  const tmpDir = join(os.default.tmpdir(), `ptkl-dev-${appName}`);
419
638
  mkdirSync(tmpDir, { recursive: true });
420
- console.log(`👁️ Watching views for "${appName}": [${Object.keys(views).join(', ')}]`);
421
- for (const viewName of Object.keys(views)) {
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) {
422
653
  // Use a per-view output dir so each view's assets don't collide
423
654
  // (two views could otherwise both emit a file named from their input, e.g. `index.css`)
424
655
  const viewOutDir = join(tmpDir, viewName);
@@ -481,6 +712,332 @@ class ForgeCommand {
481
712
  });
482
713
  }
483
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 .');
484
1041
  }
485
1042
  async removeVersion(options) {
486
1043
  const { ref, version } = options;
@@ -496,7 +1053,8 @@ class ForgeCommand {
496
1053
  console.log(data);
497
1054
  }
498
1055
  async install(options) {
499
- const { path, env, bundle } = options;
1056
+ const { path: rawPath, env, bundle } = options;
1057
+ const path = isAbsolute(rawPath) ? rawPath : join(process.cwd(), rawPath);
500
1058
  if (bundle)
501
1059
  await this.bundle({ path, upload: false });
502
1060
  const envs = env ? [env] : ['dev', 'live'];
@@ -505,7 +1063,8 @@ class ForgeCommand {
505
1063
  }
506
1064
  }
507
1065
  async uninstall(options) {
508
- const { path, env, bundle } = options;
1066
+ const { path: rawPath, env, bundle } = options;
1067
+ const path = isAbsolute(rawPath) ? rawPath : join(process.cwd(), rawPath);
509
1068
  if (bundle)
510
1069
  await this.bundle({ path, upload: false });
511
1070
  const envs = env ? [env] : ['dev', 'live'];
@@ -514,6 +1073,7 @@ class ForgeCommand {
514
1073
  }
515
1074
  }
516
1075
  static async _runScript(appPath, scriptType, env = 'dev') {
1076
+ appPath = isAbsolute(appPath) ? appPath : join(process.cwd(), appPath);
517
1077
  const module = await import(`${appPath}/ptkl.config.js`);
518
1078
  const { name, distPath, scripts } = module.default ?? {};
519
1079
  if (!name)
@@ -550,7 +1110,7 @@ class ForgeCommand {
550
1110
  delete global.window;
551
1111
  delete global.axiosAdapter;
552
1112
  if (result && result._error_) {
553
- const displayMessage = result.message ||
1113
+ const displayMessage = result?.response?.data?.message || result.message ||
554
1114
  (result.errors && result.errors.length > 0
555
1115
  ? result.errors.map((e) => e.message || e.code).filter(Boolean).join(', ')
556
1116
  : result.name) ||