@ptkl/toolkit 0.11.0 → 1.0.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,11 +2,23 @@ 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';
11
+ import * as sdk from "../lib/sdk.js";
12
+ import { registerCommand, withProfile } from "../lib/scaffold.js";
13
+ function parseJSON(label, raw) {
14
+ try {
15
+ return JSON.parse(raw);
16
+ }
17
+ catch {
18
+ console.error(`${label} must be valid JSON`);
19
+ process.exit(1);
20
+ }
21
+ }
10
22
  function formatBuildError(reason) {
11
23
  const lines = [];
12
24
  if (reason.id || reason.loc) {
@@ -81,7 +93,16 @@ class ForgeCommand {
81
93
  .requiredOption("-p, --path <path>", "Path is directory where app is located.")
82
94
  .option("--platform-url <url>", "Platform UI URL (e.g. http://localhost:8081) — required for window.requestForgePermissions in dev mode")
83
95
  .option("-m, --mode <mode>", "Vite mode (controls which .env.[mode] files are loaded). Defaults to 'development'.")
96
+ .option("--env <env>", "Run for a specific env only (dev or live)")
97
+ .option("--view <view>", "Which view to serve (defaults to 'main')")
84
98
  .action(this.runDev))
99
+ .addCommand(new Command("setup")
100
+ .description("Scaffold a new Forge app in a directory (ptkl.config.js, vite, index.html, entry, deps)")
101
+ .requiredOption("-p, --path <path>", "Directory to create the app in (created if missing).")
102
+ .option("-n, --name <name>", "App name (kebab-case). Defaults to the folder name.")
103
+ .option("-t, --type <type>", "App type: platform | public. Defaults to platform.")
104
+ .option("--no-install", "Skip running npm install after scaffolding.")
105
+ .action(this.setup))
85
106
  .addCommand(new Command("list")
86
107
  .description("List all available apps")
87
108
  .action(this.listApps))
@@ -96,17 +117,121 @@ class ForgeCommand {
96
117
  .requiredOption("-p, --path <path>", "Path to the app directory (where ptkl.config.js is located)")
97
118
  .option("--env <env>", "Run for a specific env only (dev or live). Omit to run for both.")
98
119
  .option("-b, --bundle", "Build the bundle before running the uninstall script")
99
- .action((options) => this.uninstall(options)));
120
+ .action((options) => this.uninstall(options)))
121
+ // --- Deployed-app management (appservice) -------------------------------------------
122
+ // These subcommands use the shared scaffold (src/lib/sdk.ts + src/lib/scaffold.ts) and
123
+ // the SDK `Forge` client (@ptkl/sdk/beta), unlike bundle/dev/setup/list/install/uninstall
124
+ // above, which predate that scaffold and talk to a v0.9 client via Util.getClientForProfile().
125
+ // `services`/`variables`/`run` are wrapped named methods on the v0.10 `Forge` client;
126
+ // `domains` has no named methods yet, so it goes through the client's underlying
127
+ // authenticated AxiosInstance (`.client`, a public property on every SDK client) — the same
128
+ // stopgap pattern used by `ptkl functions create` / `ptkl project billing-modes`.
129
+ .addCommand(registerCommand(new Command("services")
130
+ .description("List services declared by a Forge app")
131
+ .argument("<ref>", "App reference (uuid or name)")).action(withProfile(async (profile, ref) => {
132
+ const res = await sdk.platform(profile).forge().listServices(ref);
133
+ return res.data;
134
+ })))
135
+ .addCommand(this.registerVariables())
136
+ .addCommand(this.registerDomains())
137
+ .addCommand(registerCommand(new Command("run")
138
+ .description("Invoke a deployed Forge service app. A bare name runs the CURRENT app's service; " +
139
+ "a PRN (prn:forge:{ref}:service/{name}) runs another app's service, where ref is an app name or uuid.")
140
+ .argument("<service>", "Service name (current app) or PRN: prn:forge:{ref}:service/{name}")
141
+ .option("-b, --body <json>", "Request body as a JSON string, sent as the POST payload")
142
+ .option("-q, --query <json>", "Query params as a JSON object string")
143
+ .option("-H, --headers <json>", "Extra request headers as a JSON object string")).action(withProfile(async (profile, service, opts) => {
144
+ const body = opts.body ? parseJSON("--body", opts.body) : undefined;
145
+ const query = opts.query ? parseJSON("--query", opts.query) : undefined;
146
+ const headers = opts.headers ? parseJSON("--headers", opts.headers) : undefined;
147
+ const res = await sdk.platform(profile).forge().runService(service, body, { query, headers });
148
+ return res.data;
149
+ })));
150
+ }
151
+ /** `forge variables get|set|add <ref>` — get/replace/merge a Forge app's variables
152
+ * (getVariables/updateVariables/addVariable on the SDK `Forge` client). */
153
+ registerVariables() {
154
+ const variables = new Command("variables").description("Manage a Forge app's variables");
155
+ variables.addCommand(registerCommand(new Command("get")
156
+ .description("Get all variables for a Forge app")
157
+ .argument("<ref>", "App reference (uuid or name)")).action(withProfile(async (profile, ref) => {
158
+ const res = await sdk.platform(profile).forge().getVariables(ref);
159
+ return res.data;
160
+ })));
161
+ variables.addCommand(registerCommand(new Command("set")
162
+ .description("Replace ALL variables for a Forge app (full overwrite, not a merge)")
163
+ .argument("<ref>", "App reference (uuid or name)")
164
+ .requiredOption("-d, --data <json>", "Full variables object as a JSON string (replaces all existing variables)")).action(withProfile(async (profile, ref, opts) => {
165
+ const payload = parseJSON("--data", opts.data);
166
+ const res = await sdk.platform(profile).forge().updateVariables(ref, payload);
167
+ return res.data;
168
+ })));
169
+ variables.addCommand(registerCommand(new Command("add")
170
+ .description("Add or update a single variable on a Forge app (merges into existing variables)")
171
+ .argument("<ref>", "App reference (uuid or name)")
172
+ .argument("<key>", "Variable key")
173
+ .argument("<value>", "Variable value (parsed as JSON if it's valid JSON, otherwise kept as a string)")).action(withProfile(async (profile, ref, key, value) => {
174
+ let parsedValue = value;
175
+ try {
176
+ parsedValue = JSON.parse(value);
177
+ }
178
+ catch { /* not JSON — keep the raw string */ }
179
+ const res = await sdk.platform(profile).forge().addVariable(ref, key, parsedValue);
180
+ return res.data;
181
+ })));
182
+ return variables;
183
+ }
184
+ /** `forge domains add|verify|refresh|remove <ref> <domain>` — custom-domain lifecycle for
185
+ * public Forge apps (appservice `POST/DELETE /luma/appservice/v1/forge/:ref/domain[/verify|/refresh]`,
186
+ * see platform-docs/docs/forge/custom-domains.md). No named SDK method exists yet, so this calls
187
+ * the SDK `Forge` client's underlying authenticated AxiosInstance directly (`.client`, see the
188
+ * stopgap-pattern note above `services`). */
189
+ registerDomains() {
190
+ const domains = new Command("domains").description("Manage custom domains for a public Forge app");
191
+ domains.addCommand(registerCommand(new Command("add")
192
+ .description("Register a custom domain (returns a DNS TXT validationKey to prove ownership)")
193
+ .argument("<ref>", "App reference (uuid or name)")
194
+ .argument("<domain>", "Custom domain, e.g. app.example.com")).action(withProfile(async (profile, ref, domain) => {
195
+ const client = sdk.platform(profile).forge();
196
+ const res = await client.client.post(`/luma/appservice/v1/forge/${ref}/domain`, { domain });
197
+ return res.data;
198
+ })));
199
+ domains.addCommand(registerCommand(new Command("verify")
200
+ .description("Verify a custom domain's DNS TXT record against its validation key")
201
+ .argument("<ref>", "App reference (uuid or name)")
202
+ .argument("<domain>", "Custom domain to verify")).action(withProfile(async (profile, ref, domain) => {
203
+ const client = sdk.platform(profile).forge();
204
+ const res = await client.client.post(`/luma/appservice/v1/forge/${ref}/domain/verify`, { domain });
205
+ return res.data;
206
+ })));
207
+ domains.addCommand(registerCommand(new Command("refresh")
208
+ .description("Refresh an expired validation key for an unvalidated custom domain")
209
+ .argument("<ref>", "App reference (uuid or name)")
210
+ .argument("<domain>", "Custom domain")).action(withProfile(async (profile, ref, domain) => {
211
+ const client = sdk.platform(profile).forge();
212
+ const res = await client.client.post(`/luma/appservice/v1/forge/${ref}/domain/refresh`, { domain });
213
+ return res.data;
214
+ })));
215
+ domains.addCommand(registerCommand(new Command("remove")
216
+ .description("Remove a custom domain")
217
+ .argument("<ref>", "App reference (uuid or name)")
218
+ .argument("<domain>", "Custom domain to remove")).action(withProfile(async (profile, ref, domain) => {
219
+ const client = sdk.platform(profile).forge();
220
+ const res = await client.client.delete(`/luma/appservice/v1/forge/${ref}/domain`, { data: { domain } });
221
+ return res.data;
222
+ })));
223
+ return domains;
100
224
  }
101
225
  async bundle(options) {
102
- const { path, upload, mode } = options;
226
+ const { path: rawPath, upload, mode } = options;
227
+ const path = isAbsolute(rawPath) ? rawPath : join(process.cwd(), rawPath);
103
228
  // Store original working directory
104
229
  const originalCwd = process.cwd();
105
230
  try {
106
231
  // Change to the app directory
107
232
  process.chdir(path);
108
233
  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 ?? {};
234
+ 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
235
  const iconBase64 = encodeIcon(icon, path);
111
236
  // Clean dist folder before building to remove stale files
112
237
  if (existsSync(distPath)) {
@@ -118,11 +243,23 @@ class ForgeCommand {
118
243
  if (rtPerms.length + ents.length > 100) {
119
244
  throw new Error(`Combined runtime_permissions (${rtPerms.length}) and entitlements (${ents.length}) must not exceed 100 entries`);
120
245
  }
246
+ // Normalize views: support both string entries and object entries with access/permissions
247
+ const normalizedViews = {};
248
+ if (views) {
249
+ for (const [viewName, viewDef] of Object.entries(views)) {
250
+ if (typeof viewDef === 'string') {
251
+ normalizedViews[viewName] = { entry: viewDef };
252
+ }
253
+ else {
254
+ normalizedViews[viewName] = viewDef;
255
+ }
256
+ }
257
+ }
121
258
  // build manifest file
122
259
  const manifest = {
123
260
  name,
124
261
  version,
125
- views: {},
262
+ ...(type !== 'service' && { views: {} }),
126
263
  label,
127
264
  icon: iconBase64,
128
265
  permissions,
@@ -131,9 +268,20 @@ class ForgeCommand {
131
268
  entitlements: entitlements ?? [],
132
269
  requires: requires ?? null,
133
270
  scripts: {},
134
- type: type || 'platform', // default to 'platform' if not specified
271
+ type: type || 'platform',
135
272
  ssrRenderer,
136
273
  };
274
+ // Add services to manifest if defined
275
+ if (services && services.length > 0) {
276
+ manifest.services = services.map((svc) => ({
277
+ name: svc.name,
278
+ script: `services/${svc.name}.js`,
279
+ access: svc.access || 'public',
280
+ ...(svc.label && { label: svc.label }),
281
+ ...(svc.description && { description: svc.description }),
282
+ ...(svc.permissions && { permissions: svc.permissions }),
283
+ }));
284
+ }
137
285
  // Different build approach for public vs platform apps
138
286
  if (type === 'public') {
139
287
  // Public apps: standard SPA build with index.html
@@ -194,26 +342,56 @@ class ForgeCommand {
194
342
  console.log("✅ All builds completed successfully");
195
343
  }
196
344
  else {
197
- // Platform apps: custom bundle format with views and scripts
345
+ // Platform/service apps: custom bundle format with views, scripts, and services
198
346
  const bundleBasePath = `/luma/appservice/v1/forge/static/bundle/${name}/${version}/`;
199
- const buildViews = Object.keys(views).map(async (view) => {
200
- manifest.views[view] = `${view}.bundle.js`;
347
+ const buildViews = Object.keys(normalizedViews).map(async (view) => {
348
+ const viewDef = normalizedViews[view];
349
+ // Store view with access info in manifest
350
+ if (viewDef.access || viewDef.permissions) {
351
+ manifest.views[view] = {
352
+ entry: `${view}.bundle.js`,
353
+ access: viewDef.access || (type === 'public' ? 'public' : 'platform'),
354
+ ...(viewDef.permissions && { permissions: viewDef.permissions }),
355
+ };
356
+ }
357
+ else {
358
+ manifest.views[view] = `${view}.bundle.js`;
359
+ }
201
360
  try {
361
+ const bundleMode = mode ?? 'production';
202
362
  const result = await build({
203
363
  root: path,
204
- mode: mode ?? 'production',
364
+ mode: bundleMode,
205
365
  base: bundleBasePath,
366
+ // Keep the JSX transform and React runtime on the same side even if
367
+ // the invoking shell exports NODE_ENV=development (Vite derives
368
+ // isProduction from NODE_ENV, not from mode). A split ships jsxDEV()
369
+ // calls against production React → "jsxDEV is not a function".
370
+ esbuild: {
371
+ jsxDev: bundleMode !== 'production',
372
+ },
373
+ define: {
374
+ 'process.env.NODE_ENV': JSON.stringify(bundleMode),
375
+ },
376
+ resolve: {
377
+ // One React copy even when @ptkl/components is npm-linked (the
378
+ // linked repo carries its own node_modules/react).
379
+ dedupe: ['react', 'react-dom', 'react/jsx-runtime', 'react/jsx-dev-runtime'],
380
+ },
206
381
  build: {
207
382
  outDir: distPath,
208
383
  emptyOutDir: false,
209
384
  rollupOptions: {
210
- input: views[view],
385
+ input: viewDef.entry,
211
386
  output: {
212
387
  format: 'esm',
213
- entryFileNames: `[name].bundle.js`,
214
- assetFileNames: (assetInfo) => {
215
- return '[name].[ext]'; // Example: Customize the output file name format
216
- },
388
+ // Name outputs by the view KEY, not the entry file's basename —
389
+ // the manifest and AppView resolve `${view}.bundle.js` / `${view}.css`,
390
+ // so an entry named index.tsx must still emit `${view}.*`.
391
+ // Other assets keep a hashed name: all views share distPath, so
392
+ // entry-derived names (e.g. index.css from two views) collide.
393
+ entryFileNames: `${view}.bundle.js`,
394
+ assetFileNames: (assetInfo) => assetInfo.name?.endsWith('.css') ? `${view}.css` : `[name]-[hash].[ext]`,
217
395
  manualChunks: undefined,
218
396
  inlineDynamicImports: true,
219
397
  }
@@ -306,12 +484,12 @@ class ForgeCommand {
306
484
  if (failedViews.length > 0) {
307
485
  console.error('\n❌ Failed to build views:');
308
486
  failedViews.forEach((result, index) => {
309
- const viewNames = Object.keys(views);
487
+ const viewNames = Object.keys(normalizedViews);
310
488
  const failedIndices = viewResults.map((r, i) => r.status === 'rejected' ? i : -1).filter(i => i >= 0);
311
489
  const viewName = viewNames[failedIndices[index]];
312
490
  const reason = result.reason;
313
491
  console.error(`\n View: ${viewName}`);
314
- console.error(` Input: ${views[viewName]}`);
492
+ console.error(` Input: ${normalizedViews[viewName].entry}`);
315
493
  console.error(formatBuildError(reason));
316
494
  });
317
495
  throw new Error('View build failed. See errors above.');
@@ -333,6 +511,75 @@ class ForgeCommand {
333
511
  throw new Error('Script build failed. See errors above.');
334
512
  }
335
513
  }
514
+ // Build service scripts
515
+ if (services && services.length > 0) {
516
+ const servicesDir = join(distPath, 'services');
517
+ if (!existsSync(servicesDir)) {
518
+ mkdirSync(servicesDir, { recursive: true });
519
+ }
520
+ const buildServices = services.map(async (svc) => {
521
+ try {
522
+ const result = await build({
523
+ root: path,
524
+ mode: mode ?? 'production',
525
+ base: bundleBasePath,
526
+ build: {
527
+ outDir: servicesDir,
528
+ emptyOutDir: false,
529
+ target: 'esnext',
530
+ rollupOptions: {
531
+ input: svc.script,
532
+ external: ['axios'],
533
+ output: {
534
+ format: 'esm',
535
+ entryFileNames: `${svc.name}.js`,
536
+ assetFileNames: '[name].[ext]',
537
+ manualChunks: undefined,
538
+ inlineDynamicImports: true,
539
+ }
540
+ },
541
+ },
542
+ plugins: [
543
+ {
544
+ name: 'wrap-service-script',
545
+ generateBundle(options, bundle) {
546
+ for (const fileName in bundle) {
547
+ const chunk = bundle[fileName];
548
+ if (chunk.type === 'chunk' && chunk.code) {
549
+ let code = chunk.code;
550
+ code = code.replace(/import\s+([\w$]+)\s+from\s*['"]axios['"]\s*;?\n?/g, 'const $1=axiosAdapter;\n');
551
+ code = code.replace(/import\s*\{([^}]+)\}\s*from\s*['"]axios['"]\s*;?\n?/g, (_, imports) => imports.split(',').map((part) => {
552
+ const [orig, alias] = part.trim().split(/\s+as\s+/).map((s) => s.trim());
553
+ return `const ${alias || orig}=axiosAdapter${orig === 'default' || !alias ? '' : `.${orig}`};\n`;
554
+ }).join(''));
555
+ chunk.code = code;
556
+ }
557
+ }
558
+ }
559
+ }
560
+ ]
561
+ });
562
+ return result;
563
+ }
564
+ catch (error) {
565
+ throw error;
566
+ }
567
+ });
568
+ const serviceResults = await Promise.allSettled(buildServices);
569
+ const failedServices = serviceResults.filter(r => r.status === 'rejected');
570
+ if (failedServices.length > 0) {
571
+ console.error('\n❌ Failed to build services:');
572
+ failedServices.forEach((result, index) => {
573
+ const failedIndices = serviceResults.map((r, i) => r.status === 'rejected' ? i : -1).filter(i => i >= 0);
574
+ const svc = services[failedIndices[index]];
575
+ const reason = result.reason;
576
+ console.error(`\n Service: ${svc.name}`);
577
+ console.error(` Input: ${svc.script}`);
578
+ console.error(formatBuildError(reason));
579
+ });
580
+ throw new Error('Service build failed. See errors above.');
581
+ }
582
+ }
336
583
  console.log("✅ All builds completed successfully");
337
584
  }
338
585
  console.log("Packaging app...");
@@ -372,16 +619,25 @@ class ForgeCommand {
372
619
  }
373
620
  }
374
621
  async runDev(options) {
375
- const { path, platformUrl, mode } = options;
622
+ const { path: rawPath, platformUrl, mode, env, view: viewFlag } = options;
623
+ const path = isAbsolute(rawPath) ? rawPath : join(process.cwd(), rawPath);
376
624
  const host = Util.getCurrentProfile().host;
377
- // Load ptkl.config.js to discover views and app name
625
+ // Load ptkl.config.js to discover views, services, and app name
378
626
  let appName;
379
627
  let views;
628
+ let rawViews;
629
+ let services;
630
+ let appType;
380
631
  try {
381
- console.log(`${path}/ptkl.config.js`);
382
632
  const configModule = await import(`${path}/ptkl.config.js`);
383
633
  appName = configModule.default?.name;
384
- views = configModule.default?.views;
634
+ rawViews = configModule.default?.views;
635
+ // Normalize: extract entry path regardless of whether view is a string or object
636
+ views = rawViews
637
+ ? Object.fromEntries(Object.entries(rawViews).map(([k, v]) => [k, typeof v === 'string' ? v : v.entry]))
638
+ : undefined;
639
+ services = configModule.default?.services;
640
+ appType = configModule.default?.type || 'platform';
385
641
  }
386
642
  catch (err) {
387
643
  // no manifest found – continue without view watch publishing
@@ -393,26 +649,116 @@ class ForgeCommand {
393
649
  console.log(hubStatus === 'started'
394
650
  ? `🔌 Dev hub started on http://localhost:${DEV_HUB_PORT}`
395
651
  : `🔌 Reusing existing dev hub on http://localhost:${DEV_HUB_PORT}`);
396
- // Start Vite dev server for the app, injecting window.__PTKL_DEV_HUB__ so AppView
397
- // inside this app automatically knows where to fetch local view bundles from.
398
- // The forgeDevKernelPlugin polyfills window.requestForgePermissions and other forge
399
- // kernel globals that normally come from the platform-forge runtime.
652
+ // Resolve the entry for the selected view
653
+ const selectedView = viewFlag ?? 'main';
654
+ let viewEntry;
655
+ if (views && views[selectedView]) {
656
+ viewEntry = views[selectedView];
657
+ if (viewEntry.startsWith(path)) {
658
+ viewEntry = '/' + viewEntry.slice(path.length).replace(/^[/\\]+/, '');
659
+ }
660
+ }
661
+ else if (viewFlag) {
662
+ const available = views ? Object.keys(views).join(', ') : 'none';
663
+ console.error(`❌ View "${selectedView}" not found in manifest. Available views: ${available}`);
664
+ process.exit(1);
665
+ }
666
+ // Find a free port for the service dev proxy so multiple apps can run in parallel
667
+ let servicePort;
668
+ if (services && services.length > 0) {
669
+ const net = await import('net');
670
+ servicePort = await new Promise((resolve, reject) => {
671
+ const srv = net.default.createServer();
672
+ srv.listen(0, () => {
673
+ const port = srv.address().port;
674
+ srv.close(() => resolve(port));
675
+ });
676
+ srv.on('error', reject);
677
+ });
678
+ }
679
+ // Start Vite dev server
400
680
  const server = await createServer({
401
681
  root: path,
402
682
  mode: mode ?? 'development',
683
+ resolve: {
684
+ // One React instance even when @ptkl/components is npm-linked (the
685
+ // linked repo carries its own node_modules/react) — two copies break
686
+ // hooks ("Invalid hook call") as soon as app code renders JSX.
687
+ dedupe: ['react', 'react-dom'],
688
+ },
403
689
  define: {
404
690
  __ENV_VARIABLES__: JSON.stringify({
405
691
  API_HOST: host,
406
692
  INTEGRATION_API: `${host}/luma/integrations`,
407
693
  PROJECT_API_TOKEN: Util.getCurrentProfile().token,
694
+ PROJECT_ENV: env ?? "dev",
695
+ ...(servicePort ? { FORGE_DEV_SERVICE_URL: `http://localhost:${servicePort}` } : {}),
408
696
  }),
409
697
  DEV_HUB_PORT
410
698
  },
411
- plugins: [forgeDevKernelPlugin(appName, platformUrl)],
699
+ plugins: [
700
+ forgeDevKernelPlugin(appName, platformUrl, DEV_HUB_PORT),
701
+ {
702
+ // Console bridge (dev only): when the app runs EMBEDDED (e.g. the
703
+ // Studio's Preview iframe), forward console output + uncaught errors
704
+ // to the parent via postMessage so the host can show the app's OWN
705
+ // browser console. No-op when the page is top-level.
706
+ name: 'ptkl-console-bridge',
707
+ transformIndexHtml() {
708
+ return [
709
+ {
710
+ tag: 'script',
711
+ injectTo: 'head-prepend',
712
+ children: `(function () {
713
+ if (window.parent === window) return;
714
+ var send = function (level, args) {
715
+ try {
716
+ var msg = args.map(function (a) {
717
+ if (typeof a === 'string') return a;
718
+ if (a instanceof Error) return a.stack || a.message;
719
+ try { return JSON.stringify(a); } catch (e) { return String(a); }
720
+ }).join(' ');
721
+ window.parent.postMessage({ type: 'ptkl-console', level: level, message: msg }, '*');
722
+ } catch (e) { /* never break the app over logging */ }
723
+ };
724
+ ['log', 'info', 'warn', 'error', 'debug'].forEach(function (k) {
725
+ var orig = console[k];
726
+ console[k] = function () {
727
+ send(k, Array.prototype.slice.call(arguments));
728
+ return orig.apply(console, arguments);
729
+ };
730
+ });
731
+ window.addEventListener('error', function (e) {
732
+ send('error', [e.message + (e.filename ? ' (' + e.filename + ':' + e.lineno + ')' : '')]);
733
+ });
734
+ window.addEventListener('unhandledrejection', function (e) {
735
+ var r = e.reason;
736
+ send('error', ['Unhandled rejection: ' + (r && r.message ? r.message : String(r))]);
737
+ });
738
+ })();`,
739
+ },
740
+ ];
741
+ },
742
+ },
743
+ // Swap the entry in index.html to the selected view's entry
744
+ ...(viewFlag && viewEntry ? [{
745
+ name: 'ptkl-view-entry',
746
+ transformIndexHtml(html) {
747
+ // Find the actual app entry script in index.html and replace its src.
748
+ // Can't use a generic regex — Vite injects /@vite/client as another
749
+ // <script type="module" src="..."> before the app entry.
750
+ let mainEntry = views?.['main'];
751
+ if (mainEntry?.startsWith(path)) {
752
+ mainEntry = '/' + mainEntry.slice(path.length).replace(/^[/\\]+/, '');
753
+ }
754
+ return html.replace(mainEntry, viewEntry);
755
+ },
756
+ }] : []),
757
+ ],
412
758
  });
413
759
  await server.listen();
414
760
  console.log('Current profile:', Util.getCurrentProfile().name);
415
- console.log('Dev server running at:', server?.resolvedUrls?.local[0]);
761
+ console.log(`Dev server running at: ${server?.resolvedUrls?.local[0]}${viewFlag ? ` (view: ${selectedView})` : ''}`);
416
762
  // Build every view declared in ptkl.config.js in watch mode.
417
763
  // On each successful rebuild the bundle is pushed to the dev hub so any
418
764
  // other locally-running app that embeds this view via AppView picks it up instantly.
@@ -423,8 +769,20 @@ class ForgeCommand {
423
769
  // Build output goes to a per-app temp dir so concurrent forge dev runs don't clash
424
770
  const tmpDir = join(os.default.tmpdir(), `ptkl-dev-${appName}`);
425
771
  mkdirSync(tmpDir, { recursive: true });
426
- console.log(`👁️ Watching views for "${appName}": [${Object.keys(views).join(', ')}]`);
427
- for (const viewName of Object.keys(views)) {
772
+ // Only watch-build platform views (not main, not public) — those are the ones
773
+ // embeddable via AppView in other apps. Main and public views are standalone.
774
+ const embeddableViews = Object.keys(views).filter(name => {
775
+ if (name === 'main')
776
+ return false;
777
+ const raw = rawViews?.[name];
778
+ if (typeof raw === 'object' && raw.access === 'public')
779
+ return false;
780
+ return true;
781
+ });
782
+ if (embeddableViews.length > 0) {
783
+ console.log(`👁️ Watching embeddable views for "${appName}": [${embeddableViews.join(', ')}]`);
784
+ }
785
+ for (const viewName of embeddableViews) {
428
786
  // Use a per-view output dir so each view's assets don't collide
429
787
  // (two views could otherwise both emit a file named from their input, e.g. `index.css`)
430
788
  const viewOutDir = join(tmpDir, viewName);
@@ -434,9 +792,17 @@ class ForgeCommand {
434
792
  mode: 'production',
435
793
  logLevel: 'silent',
436
794
  plugins: [],
437
- // Explicitly define NODE_ENV for this build so esbuild strips dev-only
438
- // code paths (e.g. React dev warnings) in the view bundle, regardless
439
- // of what process.env.NODE_ENV is set to in the surrounding process.
795
+ // The dev hub serves PRODUCTION builds of views. The dev server created
796
+ // above set process.env.NODE_ENV=development for this whole process, and
797
+ // Vite derives isProduction from NODE_ENV (not from mode) — so both the
798
+ // JSX transform and React's runtime must be forced to production TOGETHER:
799
+ // - jsxDev:false → esbuild emits jsx() from react/jsx-runtime
800
+ // - define → React resolves its production runtime
801
+ // Forcing only the define ships dev jsxDEV() calls against production
802
+ // React, where jsxDEV is undefined → "_a.jsxDEV is not a function".
803
+ esbuild: {
804
+ jsxDev: false,
805
+ },
440
806
  define: {
441
807
  'process.env.NODE_ENV': '"production"',
442
808
  },
@@ -487,6 +853,332 @@ class ForgeCommand {
487
853
  });
488
854
  }
489
855
  }
856
+ // --- Local service dev server ---
857
+ if (appName && services && services.length > 0) {
858
+ const os = await import('os');
859
+ const http = await import('http');
860
+ const { join } = await import('path');
861
+ const { readFileSync, existsSync, mkdirSync } = await import('fs');
862
+ const { randomUUID } = await import('crypto');
863
+ const profile = Util.getCurrentProfile();
864
+ const serviceDir = join(os.default.tmpdir(), `ptkl-dev-${appName}`, '_services');
865
+ mkdirSync(serviceDir, { recursive: true });
866
+ // In-memory map of service name → latest bundled code
867
+ const serviceBundles = {};
868
+ console.log(`⚙️ Building services for "${appName}": [${services.map((s) => s.name).join(', ')}]`);
869
+ // Build each service in watch mode
870
+ for (const svc of services) {
871
+ const svcOutDir = join(serviceDir, svc.name);
872
+ mkdirSync(svcOutDir, { recursive: true });
873
+ const watcher = (await build({
874
+ root: path,
875
+ mode: mode ?? 'production',
876
+ logLevel: 'silent',
877
+ build: {
878
+ outDir: svcOutDir,
879
+ emptyOutDir: false,
880
+ target: 'esnext',
881
+ watch: {},
882
+ rollupOptions: {
883
+ input: svc.script,
884
+ external: ['axios'],
885
+ output: {
886
+ format: 'esm',
887
+ entryFileNames: `${svc.name}.js`,
888
+ manualChunks: undefined,
889
+ inlineDynamicImports: true,
890
+ },
891
+ },
892
+ },
893
+ plugins: [
894
+ {
895
+ name: 'wrap-service-dev',
896
+ generateBundle(_options, bundle) {
897
+ for (const fileName in bundle) {
898
+ const chunk = bundle[fileName];
899
+ if (chunk.type === 'chunk' && chunk.code) {
900
+ let code = chunk.code;
901
+ code = code.replace(/import\s+([\w$]+)\s+from\s*['"]axios['"]\s*;?\n?/g, 'const $1=axiosAdapter;\n');
902
+ code = code.replace(/import\s*\{([^}]+)\}\s*from\s*['"]axios['"]\s*;?\n?/g, (_, imports) => imports.split(',').map((part) => {
903
+ const [orig, alias] = part.trim().split(/\s+as\s+/).map((s) => s.trim());
904
+ return `const ${alias || orig}=axiosAdapter${orig === 'default' || !alias ? '' : `.${orig}`};\n`;
905
+ }).join(''));
906
+ chunk.code = code;
907
+ }
908
+ }
909
+ },
910
+ },
911
+ ],
912
+ }));
913
+ // Seed from the initial build (BUNDLE_END may have fired before the listener below is attached)
914
+ const initialFile = join(svcOutDir, `${svc.name}.js`);
915
+ if (existsSync(initialFile)) {
916
+ const content = readFileSync(initialFile, 'utf-8');
917
+ if (content.trim()) {
918
+ serviceBundles[svc.name] = content;
919
+ console.log(`✅ [${appName}/${svc.name}] service built`);
920
+ }
921
+ }
922
+ watcher.on('event', (event) => {
923
+ if (event.code === 'BUNDLE_END') {
924
+ const file = join(svcOutDir, `${svc.name}.js`);
925
+ if (existsSync(file)) {
926
+ serviceBundles[svc.name] = readFileSync(file, 'utf-8');
927
+ console.log(`🔄 [${appName}/${svc.name}] service rebuilt`);
928
+ }
929
+ }
930
+ if (event.code === 'ERROR') {
931
+ console.error(`❌ [${appName}/${svc.name}] service build error:`, event.error?.message ?? event.error);
932
+ }
933
+ });
934
+ }
935
+ // Build a lookup of service config by name
936
+ const serviceConfig = {};
937
+ for (const svc of services) {
938
+ serviceConfig[svc.name] = svc;
939
+ }
940
+ const SERVICE_PORT = servicePort;
941
+ const server = http.default.createServer(async (req, res) => {
942
+ // CORS
943
+ res.setHeader('Access-Control-Allow-Origin', '*');
944
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
945
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
946
+ if (req.method === 'OPTIONS') {
947
+ res.writeHead(204);
948
+ res.end();
949
+ return;
950
+ }
951
+ const url = new URL(req.url || '/', `http://localhost:${SERVICE_PORT}`);
952
+ const serviceName = url.pathname.replace(/^\//, '').replace(/\/$/, '');
953
+ if (!serviceName || serviceName === '') {
954
+ // List available services
955
+ res.writeHead(200, { 'Content-Type': 'application/json' });
956
+ res.end(JSON.stringify({
957
+ app: appName,
958
+ type: appType,
959
+ services: services.map((s) => ({
960
+ name: s.name,
961
+ access: s.access || 'public',
962
+ url: `http://localhost:${SERVICE_PORT}/${s.name}`,
963
+ })),
964
+ }, null, 2));
965
+ return;
966
+ }
967
+ const code = serviceBundles[serviceName];
968
+ if (!code) {
969
+ res.writeHead(404, { 'Content-Type': 'application/json' });
970
+ res.end(JSON.stringify({ error: `Service "${serviceName}" not found` }));
971
+ return;
972
+ }
973
+ // Read request body
974
+ const chunks = [];
975
+ for await (const chunk of req)
976
+ chunks.push(chunk);
977
+ const rawBody = Buffer.concat(chunks).toString();
978
+ let parsedBody = {};
979
+ try {
980
+ parsedBody = rawBody ? JSON.parse(rawBody) : {};
981
+ }
982
+ catch {
983
+ parsedBody = rawBody;
984
+ }
985
+ // Parse query params
986
+ const query = {};
987
+ url.searchParams.forEach((v, k) => { query[k] = v; });
988
+ // Build request headers object
989
+ const reqHeaders = {};
990
+ for (const [k, v] of Object.entries(req.headers)) {
991
+ if (typeof v === 'string')
992
+ reqHeaders[k] = v;
993
+ }
994
+ const svcConf = serviceConfig[serviceName];
995
+ const executionId = randomUUID();
996
+ console.log(`→ ${req.method} /${serviceName} (${executionId.slice(0, 8)})`);
997
+ try {
998
+ const evalResponse = await axios.post(`${profile.host}/luma/forge-runtime/api/services/exec`, {
999
+ expression: code,
1000
+ project_uuid: 'dev',
1001
+ env: env ?? 'dev',
1002
+ actor: profile.token,
1003
+ context: {
1004
+ appUuid: `dev-${appName}`,
1005
+ appName,
1006
+ serviceName,
1007
+ executionId,
1008
+ access: svcConf?.access || 'public',
1009
+ },
1010
+ input: parsedBody,
1011
+ body: parsedBody,
1012
+ query,
1013
+ headers: reqHeaders,
1014
+ }, {
1015
+ headers: {
1016
+ 'Content-Type': 'application/json',
1017
+ 'Authorization': `Bearer ${profile.token}`,
1018
+ },
1019
+ timeout: 310000,
1020
+ validateStatus: () => true,
1021
+ });
1022
+ const data = evalResponse.data;
1023
+ if (data.logs?.length) {
1024
+ data.logs.forEach((log) => console.log(` 📋 [${serviceName}] ${log}`));
1025
+ }
1026
+ if (data.error) {
1027
+ res.writeHead(evalResponse.status || 500, { 'Content-Type': 'application/json' });
1028
+ res.end(JSON.stringify({ error: data.error, logs: data.logs }));
1029
+ console.log(` ❌ [${serviceName}] ${data.error}`);
1030
+ }
1031
+ else if (data.response) {
1032
+ const resp = data.response;
1033
+ const status = resp.statusCode || 200;
1034
+ const contentType = resp.contentType || 'application/json';
1035
+ res.writeHead(status, { 'Content-Type': contentType });
1036
+ res.end(typeof resp.body === 'string' ? resp.body : JSON.stringify(resp.body));
1037
+ console.log(` ✅ [${serviceName}] ${status} ${contentType}`);
1038
+ }
1039
+ else {
1040
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1041
+ res.end(JSON.stringify(data));
1042
+ console.log(` ✅ [${serviceName}] 200`);
1043
+ }
1044
+ }
1045
+ catch (err) {
1046
+ const msg = err.response?.data?.message || err.message;
1047
+ res.writeHead(502, { 'Content-Type': 'application/json' });
1048
+ res.end(JSON.stringify({ error: `Eval server error: ${msg}` }));
1049
+ console.error(` ❌ [${serviceName}] ${msg}`);
1050
+ }
1051
+ });
1052
+ server.listen(SERVICE_PORT, () => {
1053
+ console.log(`\n⚡ Service dev server running at http://localhost:${SERVICE_PORT}`);
1054
+ for (const svc of services) {
1055
+ console.log(` POST http://localhost:${SERVICE_PORT}/${svc.name}`);
1056
+ }
1057
+ console.log('');
1058
+ });
1059
+ }
1060
+ }
1061
+ async setup(options) {
1062
+ const { path: rawPath, name: nameOpt, type: typeOpt, install } = options;
1063
+ const path = isAbsolute(rawPath) ? rawPath : join(process.cwd(), rawPath);
1064
+ mkdirSync(join(path, 'src', 'components'), { recursive: true });
1065
+ const folder = path.split(/[/\\]/).filter(Boolean).pop() || 'my-app';
1066
+ const name = (nameOpt || folder)
1067
+ .toLowerCase()
1068
+ .replace(/[^a-z0-9]+/g, '-')
1069
+ .replace(/^-+|-+$/g, '') || 'my-app';
1070
+ const type = typeOpt === 'public' ? 'public' : 'platform';
1071
+ // @ptkl/components is a NORMAL npm dependency (pulled on `npm install`,
1072
+ // resolved from node_modules): it provides both the reusable Forge
1073
+ // components AND the runtime (renderView + the neutral renderer + the
1074
+ // component registry) via its `@ptkl/components/runtime` subpath — see
1075
+ // src/main.tsx. Runtime + components are thus versioned once, in
1076
+ // @ptkl/components, and the Studio canvas and the built app render the same.
1077
+ const files = {
1078
+ 'package.json': JSON.stringify({
1079
+ name,
1080
+ private: true,
1081
+ version: '0.1.0',
1082
+ type: 'module',
1083
+ scripts: { dev: 'ptkl forge dev -p .', bundle: 'ptkl forge bundle -p .' },
1084
+ dependencies: {
1085
+ '@ptkl/components': '^0.13.0',
1086
+ react: '^19.0.0',
1087
+ 'react-dom': '^19.0.0',
1088
+ },
1089
+ devDependencies: {
1090
+ vite: '^7.0.0',
1091
+ '@vitejs/plugin-react': '^4.0.0',
1092
+ typescript: '^5.0.0',
1093
+ '@types/react': '^19.0.0',
1094
+ '@types/react-dom': '^19.0.0',
1095
+ },
1096
+ }, null, 2) + '\n',
1097
+ // dedupe: one React instance even when @ptkl/components is npm-linked
1098
+ // (the linked repo has its own node_modules/react) — two copies break hooks.
1099
+ '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`,
1100
+ '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`,
1101
+ 'tsconfig.json': JSON.stringify({
1102
+ compilerOptions: {
1103
+ target: 'ES2020',
1104
+ useDefineForClassFields: true,
1105
+ lib: ['ES2020', 'DOM', 'DOM.Iterable'],
1106
+ module: 'ESNext',
1107
+ skipLibCheck: true,
1108
+ moduleResolution: 'bundler',
1109
+ resolveJsonModule: true,
1110
+ jsx: 'react-jsx',
1111
+ strict: true,
1112
+ noEmit: true,
1113
+ },
1114
+ include: ['src'],
1115
+ }, null, 2) + '\n',
1116
+ '.gitignore': 'node_modules\ndist\n',
1117
+ '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`,
1118
+ '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`,
1119
+ // GENERATED entry — constant boilerplate. Renders this view's document with
1120
+ // the Protokol runtime. Platform apps compose SessionProvider (user +
1121
+ // permissions from the Forge host); public apps don't. Regenerated by the
1122
+ // Studio on save; never hand-edit.
1123
+ 'src/main.tsx': type === 'platform'
1124
+ ? `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`
1125
+ : `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`,
1126
+ // Minimal empty view; the Studio overwrites this with the authored tree.
1127
+ '_studio_/views/main.json': JSON.stringify({
1128
+ mode: 'visual',
1129
+ access: type === 'public' ? 'public' : 'platform',
1130
+ routes: {
1131
+ index: {
1132
+ path: '/',
1133
+ rootId: 'root',
1134
+ nodes: {
1135
+ root: { id: 'root', type: '@protokol/ui/Stack', props: {}, children: [] },
1136
+ },
1137
+ },
1138
+ },
1139
+ defaultRoute: 'index',
1140
+ routeOrder: ['index'],
1141
+ }, null, 2) + '\n',
1142
+ 'ptkl.studio.json': JSON.stringify({ theme: { colors: [] }, customCss: '', components: {} }, null, 2) + '\n',
1143
+ };
1144
+ for (const [rel, content] of Object.entries(files)) {
1145
+ const full = join(path, rel);
1146
+ mkdirSync(dirname(full), { recursive: true }); // nested paths (_studio_/views/…)
1147
+ if (!existsSync(full))
1148
+ writeFileSync(full, content); // never clobber existing files
1149
+ }
1150
+ console.log(`✅ Scaffolded Forge app "${name}" (${type}) in ${path}`);
1151
+ if (install !== false) {
1152
+ console.log('📦 Installing dependencies…');
1153
+ try {
1154
+ execSync('npm install', { cwd: path, stdio: 'inherit' });
1155
+ }
1156
+ catch (err) {
1157
+ console.error(`⚠️ npm install failed: ${err.message}`);
1158
+ }
1159
+ // Local dev: prefer a globally-linked @ptkl/components build if one exists
1160
+ // (`npm link` in the protokol-components repo), so the app resolves
1161
+ // @ptkl/components/runtime before that version is published. Harmless no-op
1162
+ // when there is no global link — the declared published version is used.
1163
+ try {
1164
+ execSync('npm link @ptkl/components', { cwd: path, stdio: 'ignore' });
1165
+ }
1166
+ catch {
1167
+ /* no global link — fall back to the installed @ptkl/components */
1168
+ }
1169
+ // The app's entry imports @ptkl/components/runtime; verify the resolved
1170
+ // package actually ships it (the currently PUBLISHED 0.13.0 does not — it
1171
+ // needs the local link until a runtime-bearing version is published).
1172
+ // Without this check the failure surfaces later as an opaque Vite error.
1173
+ const runtimeOk = existsSync(join(path, 'node_modules', '@ptkl', 'components', 'dist', 'runtime.esm.js')) ||
1174
+ existsSync(join(path, 'node_modules', '@ptkl', 'components', 'dist', 'runtime.js'));
1175
+ if (!runtimeOk) {
1176
+ console.warn('⚠️ The installed @ptkl/components has no "runtime" export — `ptkl forge dev` will fail.\n' +
1177
+ ' Fix: run `npm link` in your local protokol-components repo (after `npm run build`),\n' +
1178
+ ' or publish a @ptkl/components version that includes ./runtime.');
1179
+ }
1180
+ }
1181
+ console.log('\nNext: ptkl forge dev -p .');
490
1182
  }
491
1183
  async removeVersion(options) {
492
1184
  const { ref, version } = options;
@@ -502,7 +1194,8 @@ class ForgeCommand {
502
1194
  console.log(data);
503
1195
  }
504
1196
  async install(options) {
505
- const { path, env, bundle } = options;
1197
+ const { path: rawPath, env, bundle } = options;
1198
+ const path = isAbsolute(rawPath) ? rawPath : join(process.cwd(), rawPath);
506
1199
  if (bundle)
507
1200
  await this.bundle({ path, upload: false });
508
1201
  const envs = env ? [env] : ['dev', 'live'];
@@ -511,7 +1204,8 @@ class ForgeCommand {
511
1204
  }
512
1205
  }
513
1206
  async uninstall(options) {
514
- const { path, env, bundle } = options;
1207
+ const { path: rawPath, env, bundle } = options;
1208
+ const path = isAbsolute(rawPath) ? rawPath : join(process.cwd(), rawPath);
515
1209
  if (bundle)
516
1210
  await this.bundle({ path, upload: false });
517
1211
  const envs = env ? [env] : ['dev', 'live'];
@@ -520,6 +1214,7 @@ class ForgeCommand {
520
1214
  }
521
1215
  }
522
1216
  static async _runScript(appPath, scriptType, env = 'dev') {
1217
+ appPath = isAbsolute(appPath) ? appPath : join(process.cwd(), appPath);
523
1218
  const module = await import(`${appPath}/ptkl.config.js`);
524
1219
  const { name, distPath, scripts } = module.default ?? {};
525
1220
  if (!name)
@@ -556,7 +1251,7 @@ class ForgeCommand {
556
1251
  delete global.window;
557
1252
  delete global.axiosAdapter;
558
1253
  if (result && result._error_) {
559
- const displayMessage = result.message ||
1254
+ const displayMessage = result?.response?.data?.message || result.message ||
560
1255
  (result.errors && result.errors.length > 0
561
1256
  ? result.errors.map((e) => e.message || e.code).filter(Boolean).join(', ')
562
1257
  : result.name) ||