@ptkl/toolkit 0.9.0 → 0.9.3

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.
@@ -28,7 +28,9 @@ process.on('uncaughtException', (err) => {
28
28
  const { response } = err;
29
29
  if (response && response.data) {
30
30
  console.error(response.data.message);
31
- return;
31
+ }
32
+ else {
33
+ console.error(err.message || String(err));
32
34
  }
33
35
  process.exit(1);
34
36
  });
@@ -6,6 +6,30 @@ import { writeFileSync, readFileSync, rmSync, existsSync } from "fs";
6
6
  import axios from 'axios';
7
7
  import Util from "../lib/util.js";
8
8
  import { join } from 'path';
9
+ import { forgeDevKernelPlugin } from '../lib/forgeDevKernelPlugin.js';
10
+ function formatBuildError(reason) {
11
+ const lines = [];
12
+ if (reason.id || reason.loc) {
13
+ const file = reason.id || reason.loc?.file || '';
14
+ const loc = reason.loc ? `:${reason.loc.line}:${reason.loc.column}` : '';
15
+ if (file)
16
+ lines.push(` File: ${file}${loc}`);
17
+ }
18
+ if (reason.plugin) {
19
+ lines.push(` Plugin: ${reason.plugin}`);
20
+ }
21
+ if (reason.message) {
22
+ lines.push(` Error: ${reason.message}`);
23
+ }
24
+ if (reason.frame) {
25
+ lines.push('');
26
+ lines.push(reason.frame);
27
+ }
28
+ if (!reason.frame && reason.cause) {
29
+ lines.push(` Cause: ${reason.cause?.message || String(reason.cause)}`);
30
+ }
31
+ return lines.join('\n') || String(reason);
32
+ }
9
33
  class ForgeCommand {
10
34
  register() {
11
35
  return new Command("forge")
@@ -24,6 +48,7 @@ class ForgeCommand {
24
48
  .addCommand(new Command("dev")
25
49
  .description("Run dev app")
26
50
  .requiredOption("-p, --path <path>", "Path is directory where app is located.")
51
+ .option("--platform-url <url>", "Platform UI URL (e.g. http://localhost:8081) — required for window.requestForgePermissions in dev mode")
27
52
  .action(this.runDev))
28
53
  .addCommand(new Command("list")
29
54
  .description("List all available apps")
@@ -77,20 +102,27 @@ class ForgeCommand {
77
102
  ssrRenderer,
78
103
  };
79
104
  const client = Util.getClientForProfile();
80
- // get base url of the platform client
105
+ // get base url of the platform cliente
81
106
  const baseUrl = client.getPlatformBaseURL();
82
107
  // Different build approach for public vs platform apps
83
108
  if (type === 'public') {
84
109
  // Public apps: standard SPA build with index.html
85
110
  manifest.icon = icon;
86
111
  console.log("Building public app...");
87
- await build({
88
- root: path,
89
- build: {
90
- outDir: distPath,
91
- emptyOutDir: true,
92
- }
93
- });
112
+ try {
113
+ await build({
114
+ root: path,
115
+ build: {
116
+ outDir: distPath,
117
+ emptyOutDir: true,
118
+ }
119
+ });
120
+ }
121
+ catch (error) {
122
+ console.error('\n❌ Public app build failed:');
123
+ console.error(formatBuildError(error));
124
+ throw new Error('Public app build failed.');
125
+ }
94
126
  console.log("✅ Public app build completed successfully");
95
127
  // Build SSR renderer if specified for public apps
96
128
  if (ssrRenderer) {
@@ -123,7 +155,8 @@ class ForgeCommand {
123
155
  console.log('✓ SSR renderer built successfully');
124
156
  }
125
157
  catch (error) {
126
- console.error('✗ Failed to build SSR renderer:', error.message || error);
158
+ console.error('\n❌ Failed to build SSR renderer:');
159
+ console.error(formatBuildError(error));
127
160
  throw new Error('SSR renderer build failed.');
128
161
  }
129
162
  }
@@ -221,7 +254,7 @@ class ForgeCommand {
221
254
  return `const ${alias || orig}=axiosAdapter${orig === 'default' || !alias ? '' : `.${orig}`};\n`;
222
255
  }).join(''));
223
256
  // Wrap in async function so sandbox (isolate-vm / new Function) gets a callable back
224
- chunk.code = `return async()=>{try{${code}}catch(err){const errorObj={_error_:true,message:err.message,name:err.name||'Error',stack:err.stack};Object.keys(err).forEach(key=>{errorObj[key]=err[key]});if(err.data)errorObj.data=err.data;if(err.statusCode)errorObj.statusCode=err.statusCode;if(err.response)errorObj.response=err.response;if(err.code)errorObj.code=err.code;return errorObj}}`;
257
+ chunk.code = `return async()=>{try{${code}}catch(err){const errorObj={_error_:true,message:err.message,name:err.name||'Error',stack:err.stack};Object.keys(err).forEach(key=>{errorObj[key]=err[key]});if(err.data)errorObj.data=err.data;if(err.statusCode)errorObj.statusCode=err.statusCode;if(err.response)errorObj.response=err.response;if(err.code)errorObj.code=err.code;if(err.errors)errorObj.errors=err.errors.map(e=>({message:e.message,code:e.code}));return errorObj}}`;
225
258
  }
226
259
  }
227
260
  }
@@ -245,10 +278,7 @@ class ForgeCommand {
245
278
  const reason = result.reason;
246
279
  console.error(`\n View: ${viewName}`);
247
280
  console.error(` Input: ${views[viewName]}`);
248
- console.error(` Error: ${reason?.message || String(reason)}`);
249
- if (reason?.stack) {
250
- console.error(`\n${reason.stack}`);
251
- }
281
+ console.error(formatBuildError(reason));
252
282
  });
253
283
  throw new Error('View build failed. See errors above.');
254
284
  }
@@ -264,10 +294,7 @@ class ForgeCommand {
264
294
  const reason = result.reason;
265
295
  console.error(`\n Script: ${scriptName}`);
266
296
  console.error(` Input: ${scripts[scriptName]}`);
267
- console.error(` Error: ${reason?.message || String(reason)}`);
268
- if (reason?.stack) {
269
- console.error(`\n${reason.stack}`);
270
- }
297
+ console.error(formatBuildError(reason));
271
298
  });
272
299
  throw new Error('Script build failed. See errors above.');
273
300
  }
@@ -310,7 +337,7 @@ class ForgeCommand {
310
337
  }
311
338
  }
312
339
  async runDev(options) {
313
- const { path } = options;
340
+ const { path, platformUrl } = options;
314
341
  const host = Util.getCurrentProfile().host;
315
342
  // Load ptkl.config.js to discover views and app name
316
343
  let appName;
@@ -333,6 +360,8 @@ class ForgeCommand {
333
360
  : `🔌 Reusing existing dev hub on http://localhost:${DEV_HUB_PORT}`);
334
361
  // Start Vite dev server for the app, injecting window.__PTKL_DEV_HUB__ so AppView
335
362
  // inside this app automatically knows where to fetch local view bundles from.
363
+ // The forgeDevKernelPlugin polyfills window.requestForgePermissions and other forge
364
+ // kernel globals that normally come from the platform-forge runtime.
336
365
  const server = await createServer({
337
366
  root: path,
338
367
  define: {
@@ -343,7 +372,7 @@ class ForgeCommand {
343
372
  }),
344
373
  DEV_HUB_PORT
345
374
  },
346
- plugins: [],
375
+ plugins: [forgeDevKernelPlugin(appName, platformUrl)],
347
376
  });
348
377
  await server.listen();
349
378
  console.log('Current profile:', Util.getCurrentProfile().name);
@@ -359,11 +388,6 @@ class ForgeCommand {
359
388
  const tmpDir = join(os.default.tmpdir(), `ptkl-dev-${appName}`);
360
389
  mkdirSync(tmpDir, { recursive: true });
361
390
  console.log(`👁️ Watching views for "${appName}": [${Object.keys(views).join(', ')}]`);
362
- // createServer() sets process.env.NODE_ENV='development'.
363
- // Vite 7 uses process.env.NODE_ENV (not config.mode) to determine isProduction,
364
- // which controls jsxDev in esbuild. Force production here so the watch build
365
- // compiles JSX without dev helpers (_store, _source, etc.).
366
- process.env.NODE_ENV = 'production';
367
391
  for (const viewName of Object.keys(views)) {
368
392
  // Use a per-view output dir so each view's assets don't collide
369
393
  // (two views could otherwise both emit a file named from their input, e.g. `index.css`)
@@ -374,6 +398,12 @@ class ForgeCommand {
374
398
  mode: 'production',
375
399
  logLevel: 'silent',
376
400
  plugins: [],
401
+ // Explicitly define NODE_ENV for this build so esbuild strips dev-only
402
+ // code paths (e.g. React dev warnings) in the view bundle, regardless
403
+ // of what process.env.NODE_ENV is set to in the surrounding process.
404
+ define: {
405
+ 'process.env.NODE_ENV': '"production"',
406
+ },
377
407
  resolve: {
378
408
  // Force all react/* imports to resolve from the app's own node_modules,
379
409
  // preventing a second React instance from symlinked deps (e.g. @ptkl/components)
@@ -490,7 +520,16 @@ class ForgeCommand {
490
520
  delete global.window;
491
521
  delete global.axiosAdapter;
492
522
  if (result && result._error_) {
493
- console.error(`❌ Script error: ${result.message}`);
523
+ const displayMessage = result.message ||
524
+ (result.errors && result.errors.length > 0
525
+ ? result.errors.map((e) => e.message || e.code).filter(Boolean).join(', ')
526
+ : result.name) ||
527
+ 'Unknown error';
528
+ console.error(`❌ Script error: ${displayMessage}`);
529
+ if (result.errors && result.errors.length > 0) {
530
+ console.error(' Caused by:');
531
+ result.errors.forEach((e) => console.error(` - ${e.message || e.code}`));
532
+ }
494
533
  if (result.stack)
495
534
  console.error(result.stack);
496
535
  process.exit(1);
@@ -0,0 +1,213 @@
1
+ /**
2
+ * Vite plugin that injects the forge kernel window globals into the dev server HTML.
3
+ * In production these come from the platform-forge runtime loaded by the platform UI,
4
+ * but in `ptkl forge dev` the app runs standalone so we polyfill them here.
5
+ *
6
+ * The injected requestForgePermissions implementation mirrors the production version
7
+ * in platform-forge/src/lib/dynamicImport.ts — uses a DOM overlay with an iframe
8
+ * instead of a popup window to avoid popup blockers.
9
+ */
10
+ export function forgeDevKernelPlugin(appName, platformUrl) {
11
+ const appRef = appName ?? '';
12
+ const platUrl = platformUrl ? platformUrl.replace(/\/$/, '') : null;
13
+ const scriptContent = platUrl
14
+ ? `(function(){
15
+ var _appRef=${JSON.stringify(appRef)};
16
+ var _platformUrl=${JSON.stringify(platUrl)};
17
+ window.forge=window.forge||{};
18
+ window.forge.requestPermissions=function(permissions,reason){
19
+ var appName=_appRef||sessionStorage.getItem('forge_app_name')||'';
20
+ var params=new URLSearchParams();
21
+ params.set('app_ref',appName);
22
+ if(reason)params.set('reason',reason);
23
+ permissions.forEach(function(p){params.append('permissions[]',p);});
24
+ var consentUrl=_platformUrl+'/forge/consent?'+params.toString();
25
+ return new Promise(function(resolve,reject){
26
+ // Overlay backdrop
27
+ var overlay=document.createElement('div');
28
+ overlay.style.cssText='position:fixed;inset:0;z-index:99999;background:rgba(0,0,0,0.72);display:flex;align-items:center;justify-content:center;';
29
+ // Dialog shell
30
+ var dialog=document.createElement('div');
31
+ dialog.style.cssText='position:relative;width:520px;max-width:calc(100vw - 2rem);height:640px;max-height:calc(100vh - 4rem);border-radius:16px;overflow:hidden;box-shadow:0 32px 80px rgba(0,0,0,0.8);';
32
+ // Close button
33
+ var closeBtn=document.createElement('button');
34
+ closeBtn.textContent='\u00D7';
35
+ closeBtn.style.cssText='position:absolute;top:10px;right:12px;z-index:3;background:rgba(255,255,255,0.12);border:1px solid rgba(255,255,255,0.15);color:#fff;font-size:1.25rem;line-height:1;width:30px;height:30px;border-radius:50%;cursor:pointer;display:flex;align-items:center;justify-content:center;';
36
+ // Loader
37
+ var loader=document.createElement('div');
38
+ loader.style.cssText='position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:#0f0f10;z-index:2;pointer-events:none;';
39
+ var spinner=document.createElement('div');
40
+ spinner.style.cssText='width:36px;height:36px;border:3px solid rgba(255,255,255,0.12);border-top-color:#fff;border-radius:50%;animation:forge-spin 0.7s linear infinite;';
41
+ var style=document.createElement('style');
42
+ style.textContent='@keyframes forge-spin{to{transform:rotate(360deg)}}';
43
+ loader.appendChild(style);
44
+ loader.appendChild(spinner);
45
+ // iframe
46
+ var iframe=document.createElement('iframe');
47
+ iframe.style.cssText='width:100%;height:100%;border:none;display:block;';
48
+ iframe.addEventListener('load',function(){loader.style.display='none';});
49
+ dialog.appendChild(closeBtn);
50
+ dialog.appendChild(loader);
51
+ dialog.appendChild(iframe);
52
+ overlay.appendChild(dialog);
53
+ document.body.appendChild(overlay);
54
+ // Set src after DOM attach to prevent premature about:blank load event
55
+ setTimeout(function(){iframe.src=consentUrl;},0);
56
+ function cleanup(){
57
+ window.removeEventListener('message',onMessage);
58
+ overlay.remove();
59
+ }
60
+ function onMessage(e){
61
+ if(e.origin!==_platformUrl)return;
62
+ if(!e.data)return;
63
+ if(e.data.type==='forge_consent_token'){
64
+ cleanup();
65
+ sessionStorage.setItem('forge_actor_token',e.data.token);
66
+ resolve(e.data.permissions||[]);
67
+ return;
68
+ }
69
+ if(e.data.type==='forge_consent_denied'){
70
+ cleanup();
71
+ reject(new Error('[ptkl forge dev] Consent denied.'));
72
+ }
73
+ }
74
+ window.addEventListener('message',onMessage);
75
+ closeBtn.addEventListener('click',function(){
76
+ cleanup();
77
+ reject(new Error('[ptkl forge dev] Consent dialog closed without approving.'));
78
+ });
79
+ overlay.addEventListener('click',function(e){
80
+ if(e.target===overlay){
81
+ cleanup();
82
+ reject(new Error('[ptkl forge dev] Consent dialog closed without approving.'));
83
+ }
84
+ });
85
+ });
86
+ };
87
+ console.log('[ptkl forge dev] window.forge ready (platform: '+_platformUrl+')'); window.forge.dynamicImport=function(url){return import(url).then(function(){});}; window.forge.dynamicImportCSS=function(url){return new Promise(function(resolve,reject){var link=document.createElement('link');link.rel='stylesheet';link.href=url;link.onload=function(){resolve();};link.onerror=function(){reject(new Error('Failed to load CSS: '+url));};document.head.appendChild(link);});};
88
+ window.forge.requestMarketplaceInstall=function(itemId,itemType,options){
89
+ var appName=(options&&options.initiator)||sessionStorage.getItem('forge_app_name')||'';
90
+ var params=new URLSearchParams();
91
+ params.set('id',itemId);
92
+ params.set('type',itemType);
93
+ if(appName)params.set('initiator',appName);
94
+ var installUrl=_platformUrl+'/marketplace/install?'+params.toString();
95
+ return new Promise(function(resolve,reject){
96
+ var overlay=document.createElement('div');
97
+ overlay.style.cssText='position:fixed;inset:0;z-index:99999;background:rgba(0,0,0,0.72);display:flex;align-items:center;justify-content:center;';
98
+ var dialog=document.createElement('div');
99
+ dialog.style.cssText='position:relative;width:520px;max-width:calc(100vw - 2rem);height:640px;max-height:calc(100vh - 4rem);border-radius:16px;overflow:hidden;box-shadow:0 32px 80px rgba(0,0,0,0.8);';
100
+ var closeBtn=document.createElement('button');
101
+ closeBtn.textContent='\u00D7';
102
+ closeBtn.style.cssText='position:absolute;top:10px;right:12px;z-index:3;background:rgba(255,255,255,0.12);border:1px solid rgba(255,255,255,0.15);color:#fff;font-size:1.25rem;line-height:1;width:30px;height:30px;border-radius:50%;cursor:pointer;display:flex;align-items:center;justify-content:center;';
103
+ var loader=document.createElement('div');
104
+ loader.style.cssText='position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:#0f0f10;z-index:2;pointer-events:none;';
105
+ var spinner=document.createElement('div');
106
+ spinner.style.cssText='width:36px;height:36px;border:3px solid rgba(255,255,255,0.12);border-top-color:#fff;border-radius:50%;animation:forge-spin 0.7s linear infinite;';
107
+ var style=document.createElement('style');
108
+ style.textContent='@keyframes forge-spin{to{transform:rotate(360deg)}}';
109
+ loader.appendChild(style);
110
+ loader.appendChild(spinner);
111
+ var iframe=document.createElement('iframe');
112
+ iframe.style.cssText='width:100%;height:100%;border:none;display:block;';
113
+ iframe.addEventListener('load',function(){loader.style.display='none';});
114
+ dialog.appendChild(closeBtn);
115
+ dialog.appendChild(loader);
116
+ dialog.appendChild(iframe);
117
+ overlay.appendChild(dialog);
118
+ document.body.appendChild(overlay);
119
+ setTimeout(function(){iframe.src=installUrl;},0);
120
+ function cleanup(){
121
+ window.removeEventListener('message',onMessage);
122
+ overlay.remove();
123
+ }
124
+ function onMessage(e){
125
+ if(e.origin!==_platformUrl)return;
126
+ if(!e.data)return;
127
+ if(e.data.type==='marketplace_install_done'){
128
+ cleanup();
129
+ resolve({id:e.data.item_id,type:e.data.item_type,already_installed:e.data.already_installed||false});
130
+ return;
131
+ }
132
+ if(e.data.type==='marketplace_install_denied'){
133
+ cleanup();
134
+ reject(new Error('[ptkl forge dev] Installation cancelled.'));
135
+ }
136
+ }
137
+ window.addEventListener('message',onMessage);
138
+ closeBtn.addEventListener('click',function(){
139
+ cleanup();
140
+ reject(new Error('[ptkl forge dev] Marketplace install dialog closed.'));
141
+ });
142
+ overlay.addEventListener('click',function(e){
143
+ if(e.target===overlay){
144
+ cleanup();
145
+ reject(new Error('[ptkl forge dev] Marketplace install dialog closed.'));
146
+ }
147
+ });
148
+ });
149
+ };
150
+ window.forge.openDeveloperIntegrations=function(){
151
+ var integrationsUrl=_platformUrl+'/admin/developer/integrations';
152
+ return new Promise(function(resolve){
153
+ var overlay=document.createElement('div');
154
+ overlay.style.cssText='position:fixed;inset:0;z-index:99999;background:rgba(0,0,0,0.72);display:flex;align-items:center;justify-content:center;';
155
+ var dialog=document.createElement('div');
156
+ dialog.style.cssText='position:relative;width:860px;max-width:calc(100vw - 2rem);height:80vh;max-height:calc(100vh - 4rem);border-radius:16px;overflow:hidden;box-shadow:0 32px 80px rgba(0,0,0,0.8);';
157
+ var closeBtn=document.createElement('button');
158
+ closeBtn.textContent='\u00D7';
159
+ closeBtn.style.cssText='position:absolute;top:10px;right:12px;z-index:3;background:rgba(255,255,255,0.12);border:1px solid rgba(255,255,255,0.15);color:#fff;font-size:1.25rem;line-height:1;width:30px;height:30px;border-radius:50%;cursor:pointer;display:flex;align-items:center;justify-content:center;';
160
+ var loader=document.createElement('div');
161
+ loader.style.cssText='position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:#0f0f10;z-index:2;pointer-events:none;';
162
+ var spinner=document.createElement('div');
163
+ spinner.style.cssText='width:36px;height:36px;border:3px solid rgba(255,255,255,0.12);border-top-color:#fff;border-radius:50%;animation:forge-spin 0.7s linear infinite;';
164
+ var style=document.createElement('style');
165
+ style.textContent='@keyframes forge-spin{to{transform:rotate(360deg)}}';
166
+ loader.appendChild(style);
167
+ loader.appendChild(spinner);
168
+ var iframe=document.createElement('iframe');
169
+ iframe.style.cssText='width:100%;height:100%;border:none;display:block;';
170
+ iframe.addEventListener('load',function(){loader.style.display='none';});
171
+ dialog.appendChild(closeBtn);
172
+ dialog.appendChild(loader);
173
+ dialog.appendChild(iframe);
174
+ overlay.appendChild(dialog);
175
+ document.body.appendChild(overlay);
176
+ setTimeout(function(){iframe.src=integrationsUrl;},0);
177
+ function cleanup(){overlay.remove();resolve();}
178
+ closeBtn.addEventListener('click',cleanup);
179
+ overlay.addEventListener('click',function(e){if(e.target===overlay)cleanup();});
180
+ });
181
+ };
182
+ })();`
183
+ : `(function(){
184
+ window.forge=window.forge||{};
185
+ window.forge.requestPermissions=function(){
186
+ console.warn('[ptkl forge dev] window.forge.requestPermissions unavailable — pass --platform-url <url> to enable.');
187
+ return Promise.reject(new Error('requestPermissions requires --platform-url in ptkl forge dev'));
188
+ };
189
+ window.forge.requestMarketplaceInstall=function(){
190
+ console.warn('[ptkl forge dev] window.forge.requestMarketplaceInstall unavailable — pass --platform-url <url> to enable.');
191
+ return Promise.reject(new Error('requestMarketplaceInstall requires --platform-url in ptkl forge dev'));
192
+ };
193
+ window.forge.openDeveloperIntegrations=function(){
194
+ console.warn('[ptkl forge dev] window.forge.openDeveloperIntegrations unavailable — pass --platform-url <url> to enable.');
195
+ return Promise.resolve();
196
+ };
197
+ window.forge.dynamicImport=function(url){return import(url).then(function(){});};
198
+ window.forge.dynamicImportCSS=function(url){return new Promise(function(resolve,reject){var link=document.createElement('link');link.rel='stylesheet';link.href=url;link.onload=function(){resolve();};link.onerror=function(){reject(new Error('Failed to load CSS: '+url));};document.head.appendChild(link);});};}
199
+ })();`;
200
+ return {
201
+ name: 'ptkl-forge-dev-kernel',
202
+ transformIndexHtml() {
203
+ return [
204
+ {
205
+ tag: 'script',
206
+ attrs: { type: 'text/javascript' },
207
+ children: scriptContent,
208
+ injectTo: 'head-prepend',
209
+ },
210
+ ];
211
+ },
212
+ };
213
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ptkl/toolkit",
3
- "version": "0.9.0",
3
+ "version": "0.9.3",
4
4
  "description": "A command-line toolkit for managing Protokol platform applications, profiles, functions, and components",
5
5
  "keywords": [
6
6
  "protokol",