@ptkl/toolkit 1.4.4 ā 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -1
- package/dist/commands/__tests__/capabilities.test.js +83 -0
- package/dist/commands/__tests__/componentRunAs.test.js +65 -0
- package/dist/commands/__tests__/forge-bundle-layout.test.js +58 -0
- package/dist/commands/__tests__/forge-bundle-path.test.js +29 -0
- package/dist/commands/__tests__/forge-tools.test.js +64 -0
- package/dist/commands/__tests__/forge-variables.test.js +16 -0
- package/dist/commands/__tests__/kortexPlaybook.test.js +328 -0
- package/dist/commands/__tests__/role.test.js +83 -0
- package/dist/commands/__tests__/runAs.test.js +63 -0
- package/dist/commands/__tests__/thunder.test.js +46 -0
- package/dist/commands/component.js +9 -3
- package/dist/commands/forge.js +262 -202
- package/dist/commands/functions.js +11 -5
- package/dist/commands/integrations/payments.js +11 -7
- package/dist/commands/kortex.js +8 -6
- package/dist/commands/kortexPlaybook.js +396 -0
- package/dist/commands/role.js +45 -54
- package/dist/commands/satellite.js +0 -5
- package/dist/commands/thunder.js +19 -12
- package/dist/commands/workflow.js +10 -4
- package/dist/lib/__tests__/apiError.test.js +18 -0
- package/dist/lib/__tests__/apiErrorCapabilities.test.js +23 -0
- package/dist/lib/__tests__/forgeDevKernelPlugin.test.js +34 -0
- package/dist/lib/__tests__/forgeDevServiceExec.test.js +61 -0
- package/dist/lib/__tests__/forgeDevServiceServer.test.js +113 -0
- package/dist/lib/__tests__/forgeDevToken.test.js +85 -0
- package/dist/lib/__tests__/runIdentity.test.js +101 -0
- package/dist/lib/__tests__/thunder.test.js +101 -0
- package/dist/lib/apiError.js +94 -1
- package/dist/lib/forgeDevKernelPlugin.js +90 -4
- package/dist/lib/forgeDevServiceExec.js +49 -0
- package/dist/lib/forgeDevServiceServer.js +163 -0
- package/dist/lib/forgeDevToken.js +126 -0
- package/dist/lib/kortex/__tests__/fixtures/sse-and-persistence.test.js +1 -1
- package/dist/lib/kortex/__tests__/playbookRules.test.js +120 -0
- package/dist/lib/kortex/__tests__/resultSchemaChecker.test.js +37 -0
- package/dist/lib/kortex/playbookValidator.js +297 -0
- package/dist/lib/kortex/providers/protokol.js +1 -1
- package/dist/lib/kortex/resultSchemaChecker.js +188 -0
- package/dist/lib/kortex/session.js +1 -3
- package/dist/lib/oauth/ScopePreset.js +4 -3
- package/dist/lib/oauth/__tests__/oauth.test.js +6 -3
- package/dist/lib/runIdentity.js +51 -0
- package/dist/lib/thunder.js +98 -0
- package/package.json +2 -2
package/dist/commands/forge.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Command } from "commander";
|
|
2
|
+
import { forbiddenDetails } from "../lib/apiError.js";
|
|
2
3
|
import { build, createServer } from 'vite';
|
|
3
4
|
import { c } from 'tar';
|
|
4
5
|
import { Writable } from "stream";
|
|
@@ -8,6 +9,9 @@ import axios from 'axios';
|
|
|
8
9
|
import Util from "../lib/util.js";
|
|
9
10
|
import { dirname, extname, isAbsolute, join } from 'path';
|
|
10
11
|
import { forgeDevKernelPlugin } from '../lib/forgeDevKernelPlugin.js';
|
|
12
|
+
import { ForgeDevToken } from '../lib/forgeDevToken.js';
|
|
13
|
+
import { ForgeDevServiceExec } from '../lib/forgeDevServiceExec.js';
|
|
14
|
+
import { ForgeDevServiceServer } from '../lib/forgeDevServiceServer.js';
|
|
11
15
|
import { kortexDevPlugin } from '../lib/kortexDevPlugin.js';
|
|
12
16
|
import * as sdk from "../lib/sdk.js";
|
|
13
17
|
import { registerCommand, withProfile } from "../lib/scaffold.js";
|
|
@@ -41,6 +45,198 @@ function assertPermissionBytesWithinBudget(runtimePermissions = [], entitlements
|
|
|
41
45
|
throw new Error(`Declared permissions total ${bytes} bytes across ${all.length} entries, exceeding the ${MAX_PERMISSION_BYTES} byte limit`);
|
|
42
46
|
}
|
|
43
47
|
}
|
|
48
|
+
/**
|
|
49
|
+
* Validates the default variables an app declares: dev and live objects of plain values and
|
|
50
|
+
* secretgen:: generators. A secret:: value would be published with the revision, so it is refused
|
|
51
|
+
* here as it is at ship (appservice is the authority).
|
|
52
|
+
*/
|
|
53
|
+
export function assertVariablesAreDefaults(variables) {
|
|
54
|
+
if (variables === undefined || variables === null)
|
|
55
|
+
return;
|
|
56
|
+
const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
57
|
+
if (!isObject(variables))
|
|
58
|
+
throw new Error("variables must be an object with dev and live");
|
|
59
|
+
const walk = (node, path) => {
|
|
60
|
+
for (const [key, value] of Object.entries(node)) {
|
|
61
|
+
const at = `${path}.${key}`;
|
|
62
|
+
if (isObject(value)) {
|
|
63
|
+
walk(value, at);
|
|
64
|
+
}
|
|
65
|
+
else if (typeof value === "string" && /^(secret|secretref|enc)::/.test(value)) {
|
|
66
|
+
throw new Error(`${at}: an app declares defaults only (plain values or secretgen::); a secret:: value would be published with the app`);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
for (const [env, tree] of Object.entries(variables)) {
|
|
71
|
+
if (env !== "dev" && env !== "live")
|
|
72
|
+
throw new Error(`variables.${env}: unknown environment`);
|
|
73
|
+
if (!isObject(tree))
|
|
74
|
+
throw new Error(`variables.${env} must be an object`);
|
|
75
|
+
walk(tree, `variables.${env}`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Builds the scripts of a services or tools section to outDir, one file per entry named after it.
|
|
80
|
+
* Runs in the sandbox: axios is replaced by the platform's axiosAdapter.
|
|
81
|
+
*/
|
|
82
|
+
async function buildServerScripts(path, mode, outDir, items, kind) {
|
|
83
|
+
if (!items || items.length === 0)
|
|
84
|
+
return;
|
|
85
|
+
if (!existsSync(outDir)) {
|
|
86
|
+
mkdirSync(outDir, { recursive: true });
|
|
87
|
+
}
|
|
88
|
+
const builds = items.map(async (item) => {
|
|
89
|
+
return await build({
|
|
90
|
+
root: path,
|
|
91
|
+
mode: mode ?? 'production',
|
|
92
|
+
base: '/',
|
|
93
|
+
build: {
|
|
94
|
+
outDir,
|
|
95
|
+
emptyOutDir: false,
|
|
96
|
+
target: 'esnext',
|
|
97
|
+
rollupOptions: {
|
|
98
|
+
input: item.script,
|
|
99
|
+
external: ['axios'],
|
|
100
|
+
output: {
|
|
101
|
+
format: 'esm',
|
|
102
|
+
entryFileNames: `${item.name}.js`,
|
|
103
|
+
assetFileNames: '[name].[ext]',
|
|
104
|
+
manualChunks: undefined,
|
|
105
|
+
inlineDynamicImports: true,
|
|
106
|
+
}
|
|
107
|
+
},
|
|
108
|
+
},
|
|
109
|
+
plugins: [
|
|
110
|
+
{
|
|
111
|
+
name: 'wrap-service-script',
|
|
112
|
+
generateBundle(options, bundle) {
|
|
113
|
+
for (const fileName in bundle) {
|
|
114
|
+
const chunk = bundle[fileName];
|
|
115
|
+
if (chunk.type === 'chunk' && chunk.code) {
|
|
116
|
+
let code = chunk.code;
|
|
117
|
+
code = code.replace(/import\s+([\w$]+)\s+from\s*['"]axios['"]\s*;?\n?/g, 'const $1=axiosAdapter;\n');
|
|
118
|
+
code = code.replace(/import\s*\{([^}]+)\}\s*from\s*['"]axios['"]\s*;?\n?/g, (_, imports) => imports.split(',').map((part) => {
|
|
119
|
+
const [orig, alias] = part.trim().split(/\s+as\s+/).map((s) => s.trim());
|
|
120
|
+
return `const ${alias || orig}=axiosAdapter${orig === 'default' || !alias ? '' : `.${orig}`};\n`;
|
|
121
|
+
}).join(''));
|
|
122
|
+
chunk.code = code;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
]
|
|
128
|
+
});
|
|
129
|
+
});
|
|
130
|
+
const results = await Promise.allSettled(builds);
|
|
131
|
+
const failed = results.flatMap((r, i) => (r.status === 'rejected' ? [{ item: items[i], reason: r.reason }] : []));
|
|
132
|
+
if (failed.length > 0) {
|
|
133
|
+
console.error(`\nā Failed to build ${kind.toLowerCase()}s:`);
|
|
134
|
+
failed.forEach(({ item, reason }) => {
|
|
135
|
+
console.error(`\n ${kind}: ${item.name}`);
|
|
136
|
+
console.error(` Input: ${item.script}`);
|
|
137
|
+
console.error(formatBuildError(reason));
|
|
138
|
+
});
|
|
139
|
+
throw new Error(`${kind} build failed. See errors above.`);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
const TOOL_NAME = /^[a-z][a-z0-9_]{0,63}$/;
|
|
143
|
+
const TOOLS_MAX = 50;
|
|
144
|
+
const TOOL_SCHEMA_MAX_BYTES = 16 * 1024;
|
|
145
|
+
/**
|
|
146
|
+
* Validates the `tools` section of ptkl.config.js (agent tools, separate from services).
|
|
147
|
+
* Mirrors the appservice rules so a build that passes here is not refused at upload.
|
|
148
|
+
*/
|
|
149
|
+
export function assertToolsAreValid(tools, runtimePermissions = []) {
|
|
150
|
+
if (tools === undefined || tools === null)
|
|
151
|
+
return;
|
|
152
|
+
if (!Array.isArray(tools))
|
|
153
|
+
throw new Error("tools must be an array");
|
|
154
|
+
if (tools.length > TOOLS_MAX)
|
|
155
|
+
throw new Error(`tools: at most ${TOOLS_MAX} tools per app (got ${tools.length})`);
|
|
156
|
+
const declared = new Set(Array.isArray(runtimePermissions) ? runtimePermissions.filter((p) => typeof p === "string") : []);
|
|
157
|
+
const seen = new Set();
|
|
158
|
+
tools.forEach((tool, i) => {
|
|
159
|
+
if (typeof tool !== "object" || tool === null || Array.isArray(tool)) {
|
|
160
|
+
throw new Error(`tools[${i}] must be an object`);
|
|
161
|
+
}
|
|
162
|
+
const at = `tools[${i}]`;
|
|
163
|
+
if (typeof tool.name !== "string" || !TOOL_NAME.test(tool.name)) {
|
|
164
|
+
throw new Error(`${at}.name must match ${TOOL_NAME} (lowercase letters, digits, underscores; starts with a letter; max 64)`);
|
|
165
|
+
}
|
|
166
|
+
if (seen.has(tool.name))
|
|
167
|
+
throw new Error(`${at}.name "${tool.name}" is declared twice`);
|
|
168
|
+
seen.add(tool.name);
|
|
169
|
+
const name = `tool "${tool.name}"`;
|
|
170
|
+
if (typeof tool.description !== "string" || tool.description.length < 1 || tool.description.length > 1024) {
|
|
171
|
+
throw new Error(`${name}: description is required, 1 to 1024 characters`);
|
|
172
|
+
}
|
|
173
|
+
const schema = tool.input_schema;
|
|
174
|
+
if (typeof schema !== "object" || schema === null || Array.isArray(schema) || schema.type !== "object") {
|
|
175
|
+
throw new Error(`${name}: input_schema must be a JSON Schema object with type "object"`);
|
|
176
|
+
}
|
|
177
|
+
const plain = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
178
|
+
if (schema.properties !== undefined && !plain(schema.properties)) {
|
|
179
|
+
throw new Error(`${name}: input_schema.properties must be an object`);
|
|
180
|
+
}
|
|
181
|
+
if (schema.required !== undefined && (!Array.isArray(schema.required) || schema.required.some((r) => typeof r !== "string"))) {
|
|
182
|
+
throw new Error(`${name}: input_schema.required must be an array of strings`);
|
|
183
|
+
}
|
|
184
|
+
if (Buffer.byteLength(JSON.stringify(schema), "utf-8") > TOOL_SCHEMA_MAX_BYTES) {
|
|
185
|
+
throw new Error(`${name}: input_schema is larger than 16 KB`);
|
|
186
|
+
}
|
|
187
|
+
for (const flag of ["read_only", "destructive"]) {
|
|
188
|
+
if (tool[flag] !== undefined && typeof tool[flag] !== "boolean")
|
|
189
|
+
throw new Error(`${name}: ${flag} must be a boolean`);
|
|
190
|
+
}
|
|
191
|
+
if (tool.read_only === true && tool.destructive === true) {
|
|
192
|
+
throw new Error(`${name}: a tool cannot be both read_only and destructive`);
|
|
193
|
+
}
|
|
194
|
+
if (tool.permissions !== undefined) {
|
|
195
|
+
if (!Array.isArray(tool.permissions) || tool.permissions.some((p) => typeof p !== "string")) {
|
|
196
|
+
throw new Error(`${name}: permissions must be an array of strings`);
|
|
197
|
+
}
|
|
198
|
+
const extra = tool.permissions.filter((p) => !declared.has(p));
|
|
199
|
+
if (extra.length > 0) {
|
|
200
|
+
throw new Error(`${name}: permissions not in runtime_permissions: ${extra.join(", ")}`);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
if (typeof tool.script !== "string" || tool.script.trim() === "") {
|
|
204
|
+
throw new Error(`${name}: script is required`);
|
|
205
|
+
}
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
/** The `manifest.tools` entries for a validated tools section. */
|
|
209
|
+
export function toolsManifest(tools) {
|
|
210
|
+
return tools.map((t) => ({
|
|
211
|
+
name: t.name,
|
|
212
|
+
description: t.description,
|
|
213
|
+
input_schema: t.input_schema,
|
|
214
|
+
read_only: t.read_only ?? false,
|
|
215
|
+
destructive: t.destructive ?? false,
|
|
216
|
+
permissions: t.permissions ?? [],
|
|
217
|
+
script: `tools/${t.name}.js`,
|
|
218
|
+
}));
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* Where a built bundle keeps one of its files. Layout 2 (what `forge bundle` writes) splits the
|
|
222
|
+
* bundle into browser/ and server/; layout 1 was one flat folder and is still what an older build
|
|
223
|
+
* on disk looks like. The platform reads the layout off the manifest and prefixes the path the same
|
|
224
|
+
* way (appservice BundleLayoutService), so anything reading a bundle locally has to read it too ā
|
|
225
|
+
* reading a path the bundler no longer writes is how `forge install` stopped finding its script.
|
|
226
|
+
*
|
|
227
|
+
* An unreadable manifest means nothing is built: it resolves flat and the caller reports the miss
|
|
228
|
+
* against the file it actually wanted, which is the more useful error than one about the manifest.
|
|
229
|
+
*/
|
|
230
|
+
export function bundleFilePath(distDir, kind, file) {
|
|
231
|
+
let layout;
|
|
232
|
+
try {
|
|
233
|
+
layout = JSON.parse(readFileSync(join(distDir, "manifest.json"), "utf-8"))?.layout;
|
|
234
|
+
}
|
|
235
|
+
catch {
|
|
236
|
+
layout = undefined;
|
|
237
|
+
}
|
|
238
|
+
return layout === 2 ? join(distDir, kind, file) : join(distDir, file);
|
|
239
|
+
}
|
|
44
240
|
/**
|
|
45
241
|
* Validates requires.integrations. Codes are not checked against the live option
|
|
46
242
|
* set ā it can change after an app ships, and an unknown code is reported at
|
|
@@ -285,6 +481,14 @@ class ForgeCommand {
|
|
|
285
481
|
.argument("<ref>", "App reference (uuid or name)")).action(withProfile(async (profile, ref) => {
|
|
286
482
|
const res = await sdk.platform(profile).forge().listServices(ref);
|
|
287
483
|
return res.data;
|
|
484
|
+
})))
|
|
485
|
+
.addCommand(registerCommand(new Command("tools")
|
|
486
|
+
.description("List agent tools declared by a Forge app")
|
|
487
|
+
.argument("<ref>", "App reference (uuid or name)")).action(withProfile(async (profile, ref, opts) => {
|
|
488
|
+
// No named SDK method yet: same stopgap as `domains`. --env (the shared option) picks the approved revision.
|
|
489
|
+
const client = sdk.platform(profile).forge();
|
|
490
|
+
const res = await client.client.get(`/luma/appservice/v1/forge/${ref}/tools`, { params: { env: opts.env } });
|
|
491
|
+
return res.data;
|
|
288
492
|
})))
|
|
289
493
|
.addCommand(this.registerVariables())
|
|
290
494
|
.addCommand(this.registerDomains())
|
|
@@ -385,17 +589,22 @@ class ForgeCommand {
|
|
|
385
589
|
// Change to the app directory
|
|
386
590
|
process.chdir(path);
|
|
387
591
|
const module = await import(`${path}/ptkl.config.js`);
|
|
388
|
-
const { views, name, version, distPath: distPath = join(path, 'dist'), icon, type, label, permissions, install_permissions, runtime_permissions, entitlements, requires, scripts, services, ssrRenderer, } = module.default ?? {};
|
|
592
|
+
const { views, name, version, distPath: distPath = join(path, 'dist'), icon, type, label, permissions, install_permissions, runtime_permissions, entitlements, requires, variables, scripts, services, tools, ssrRenderer, } = module.default ?? {};
|
|
389
593
|
const iconBase64 = encodeIcon(icon, path);
|
|
390
594
|
// Clean dist folder before building to remove stale files
|
|
391
595
|
if (existsSync(distPath)) {
|
|
392
596
|
rmSync(distPath, { recursive: true, force: true });
|
|
393
597
|
}
|
|
598
|
+
// Layout 2: browser-served files and server-side files never share a folder.
|
|
599
|
+
const browserDir = join(distPath, 'browser');
|
|
600
|
+
const serverDir = join(distPath, 'server');
|
|
394
601
|
// Validate the declared permission budget. Mirrors assertPermissionBytesWithinBudget in
|
|
395
602
|
// appservice and assertPermissionSetWithinBudget in platform-api ā same 64 KB, so a build
|
|
396
603
|
// that passes here is not rejected at publish or at a user's app launch.
|
|
397
604
|
assertPermissionBytesWithinBudget(runtime_permissions ?? [], entitlements ?? []);
|
|
398
605
|
assertRequiresIsValid(requires);
|
|
606
|
+
assertVariablesAreDefaults(variables);
|
|
607
|
+
assertToolsAreValid(tools, runtime_permissions);
|
|
399
608
|
// Normalize views: support both string entries and object entries with access/permissions
|
|
400
609
|
const normalizedViews = {};
|
|
401
610
|
if (views) {
|
|
@@ -410,6 +619,7 @@ class ForgeCommand {
|
|
|
410
619
|
}
|
|
411
620
|
// build manifest file
|
|
412
621
|
const manifest = {
|
|
622
|
+
layout: 2,
|
|
413
623
|
name,
|
|
414
624
|
version,
|
|
415
625
|
...(type !== 'service' && { views: {} }),
|
|
@@ -420,6 +630,7 @@ class ForgeCommand {
|
|
|
420
630
|
runtime_permissions: runtime_permissions ?? [],
|
|
421
631
|
entitlements: entitlements ?? [],
|
|
422
632
|
requires: requires ?? null,
|
|
633
|
+
...(variables && { variables }),
|
|
423
634
|
scripts: {},
|
|
424
635
|
type: type || 'platform',
|
|
425
636
|
ssrRenderer,
|
|
@@ -435,6 +646,10 @@ class ForgeCommand {
|
|
|
435
646
|
...(svc.permissions && { permissions: svc.permissions }),
|
|
436
647
|
}));
|
|
437
648
|
}
|
|
649
|
+
// Tools are listed only when declared, so an app without tools keeps its manifest as before.
|
|
650
|
+
if (tools && tools.length > 0) {
|
|
651
|
+
manifest.tools = toolsManifest(tools);
|
|
652
|
+
}
|
|
438
653
|
// Different build approach for public vs platform apps
|
|
439
654
|
if (type === 'public') {
|
|
440
655
|
// Public apps: standard SPA build with index.html
|
|
@@ -444,7 +659,7 @@ class ForgeCommand {
|
|
|
444
659
|
root: path,
|
|
445
660
|
mode: mode ?? 'production',
|
|
446
661
|
build: {
|
|
447
|
-
outDir:
|
|
662
|
+
outDir: browserDir,
|
|
448
663
|
emptyOutDir: true,
|
|
449
664
|
}
|
|
450
665
|
});
|
|
@@ -463,7 +678,7 @@ class ForgeCommand {
|
|
|
463
678
|
root: path,
|
|
464
679
|
mode: mode ?? 'production',
|
|
465
680
|
build: {
|
|
466
|
-
outDir:
|
|
681
|
+
outDir: serverDir,
|
|
467
682
|
emptyOutDir: false,
|
|
468
683
|
target: 'esnext',
|
|
469
684
|
ssr: ssrRenderer, // Mark this as an SSR build with the entry point
|
|
@@ -496,7 +711,6 @@ class ForgeCommand {
|
|
|
496
711
|
}
|
|
497
712
|
else {
|
|
498
713
|
// Platform/service apps: custom bundle format with views, scripts, and services
|
|
499
|
-
const bundleBasePath = `/luma/appservice/v1/forge/static/bundle/${name}/${version}/`;
|
|
500
714
|
const buildViews = Object.keys(normalizedViews).map(async (view) => {
|
|
501
715
|
const viewDef = normalizedViews[view];
|
|
502
716
|
// Store view with access info in manifest
|
|
@@ -515,7 +729,7 @@ class ForgeCommand {
|
|
|
515
729
|
const result = await build({
|
|
516
730
|
root: path,
|
|
517
731
|
mode: bundleMode,
|
|
518
|
-
base:
|
|
732
|
+
base: '/',
|
|
519
733
|
// Keep the JSX transform and React runtime on the same side even if
|
|
520
734
|
// the invoking shell exports NODE_ENV=development (Vite derives
|
|
521
735
|
// isProduction from NODE_ENV, not from mode). A split ships jsxDEV()
|
|
@@ -532,7 +746,7 @@ class ForgeCommand {
|
|
|
532
746
|
dedupe: ['react', 'react-dom', 'react/jsx-runtime', 'react/jsx-dev-runtime'],
|
|
533
747
|
},
|
|
534
748
|
build: {
|
|
535
|
-
outDir:
|
|
749
|
+
outDir: browserDir,
|
|
536
750
|
emptyOutDir: false,
|
|
537
751
|
rollupOptions: {
|
|
538
752
|
input: viewDef.entry,
|
|
@@ -541,7 +755,7 @@ class ForgeCommand {
|
|
|
541
755
|
// Name outputs by the view KEY, not the entry file's basename ā
|
|
542
756
|
// the manifest and AppView resolve `${view}.bundle.js` / `${view}.css`,
|
|
543
757
|
// so an entry named index.tsx must still emit `${view}.*`.
|
|
544
|
-
// Other assets keep a hashed name: all views share
|
|
758
|
+
// Other assets keep a hashed name: all views share browserDir, so
|
|
545
759
|
// entry-derived names (e.g. index.css from two views) collide.
|
|
546
760
|
entryFileNames: `${view}.bundle.js`,
|
|
547
761
|
assetFileNames: (assetInfo) => assetInfo.name?.endsWith('.css') ? `${view}.css` : `[name]-[hash].[ext]`,
|
|
@@ -558,7 +772,8 @@ class ForgeCommand {
|
|
|
558
772
|
for (const fileName in bundle) {
|
|
559
773
|
const chunk = bundle[fileName];
|
|
560
774
|
if (chunk.type === 'chunk' && chunk.code) {
|
|
561
|
-
|
|
775
|
+
// The shell sets $forge.filesBase (same-origin /_app/...) before loading the bundle.
|
|
776
|
+
const runtimeBaseResolver = `const __ptklForgeBundleBase=()=>{const b=typeof window!=='undefined'&&window.$forge&&window.$forge.filesBase;if(!b)throw new Error('Forge shell did not provide filesBase');return b;};\n`;
|
|
562
777
|
chunk.code = runtimeBaseResolver + chunk.code;
|
|
563
778
|
// Transform dynamic imports in the final bundled code
|
|
564
779
|
chunk.code = chunk.code.replace(/import\(['`"]\.\/([^'`"]+)['`"]\)/g, `dynamicImport(__ptklForgeBundleBase() + '$1')`);
|
|
@@ -582,9 +797,9 @@ class ForgeCommand {
|
|
|
582
797
|
const result = await build({
|
|
583
798
|
root: path,
|
|
584
799
|
mode: mode ?? 'production',
|
|
585
|
-
base:
|
|
800
|
+
base: '/',
|
|
586
801
|
build: {
|
|
587
|
-
outDir:
|
|
802
|
+
outDir: serverDir,
|
|
588
803
|
emptyOutDir: false,
|
|
589
804
|
target: 'esnext',
|
|
590
805
|
rollupOptions: {
|
|
@@ -592,7 +807,11 @@ class ForgeCommand {
|
|
|
592
807
|
external: ['axios'],
|
|
593
808
|
output: {
|
|
594
809
|
format: 'esm',
|
|
595
|
-
|
|
810
|
+
// Named for the manifest KEY, not the entry file: the manifest records
|
|
811
|
+
// `${script}.script.js`, so `install: 'src/setup.ts'` emitted setup.script.js
|
|
812
|
+
// under a manifest that declared install.script.js ā a file nothing could find,
|
|
813
|
+
// locally or at publish.
|
|
814
|
+
entryFileNames: `${script}.script.js`,
|
|
596
815
|
assetFileNames: (assetInfo) => {
|
|
597
816
|
return '[name].[ext]';
|
|
598
817
|
},
|
|
@@ -664,75 +883,9 @@ class ForgeCommand {
|
|
|
664
883
|
throw new Error('Script build failed. See errors above.');
|
|
665
884
|
}
|
|
666
885
|
}
|
|
667
|
-
// Build service scripts
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
if (!existsSync(servicesDir)) {
|
|
671
|
-
mkdirSync(servicesDir, { recursive: true });
|
|
672
|
-
}
|
|
673
|
-
const buildServices = services.map(async (svc) => {
|
|
674
|
-
try {
|
|
675
|
-
const result = await build({
|
|
676
|
-
root: path,
|
|
677
|
-
mode: mode ?? 'production',
|
|
678
|
-
base: bundleBasePath,
|
|
679
|
-
build: {
|
|
680
|
-
outDir: servicesDir,
|
|
681
|
-
emptyOutDir: false,
|
|
682
|
-
target: 'esnext',
|
|
683
|
-
rollupOptions: {
|
|
684
|
-
input: svc.script,
|
|
685
|
-
external: ['axios'],
|
|
686
|
-
output: {
|
|
687
|
-
format: 'esm',
|
|
688
|
-
entryFileNames: `${svc.name}.js`,
|
|
689
|
-
assetFileNames: '[name].[ext]',
|
|
690
|
-
manualChunks: undefined,
|
|
691
|
-
inlineDynamicImports: true,
|
|
692
|
-
}
|
|
693
|
-
},
|
|
694
|
-
},
|
|
695
|
-
plugins: [
|
|
696
|
-
{
|
|
697
|
-
name: 'wrap-service-script',
|
|
698
|
-
generateBundle(options, bundle) {
|
|
699
|
-
for (const fileName in bundle) {
|
|
700
|
-
const chunk = bundle[fileName];
|
|
701
|
-
if (chunk.type === 'chunk' && chunk.code) {
|
|
702
|
-
let code = chunk.code;
|
|
703
|
-
code = code.replace(/import\s+([\w$]+)\s+from\s*['"]axios['"]\s*;?\n?/g, 'const $1=axiosAdapter;\n');
|
|
704
|
-
code = code.replace(/import\s*\{([^}]+)\}\s*from\s*['"]axios['"]\s*;?\n?/g, (_, imports) => imports.split(',').map((part) => {
|
|
705
|
-
const [orig, alias] = part.trim().split(/\s+as\s+/).map((s) => s.trim());
|
|
706
|
-
return `const ${alias || orig}=axiosAdapter${orig === 'default' || !alias ? '' : `.${orig}`};\n`;
|
|
707
|
-
}).join(''));
|
|
708
|
-
chunk.code = code;
|
|
709
|
-
}
|
|
710
|
-
}
|
|
711
|
-
}
|
|
712
|
-
}
|
|
713
|
-
]
|
|
714
|
-
});
|
|
715
|
-
return result;
|
|
716
|
-
}
|
|
717
|
-
catch (error) {
|
|
718
|
-
throw error;
|
|
719
|
-
}
|
|
720
|
-
});
|
|
721
|
-
const serviceResults = await Promise.allSettled(buildServices);
|
|
722
|
-
const failedServices = serviceResults.filter(r => r.status === 'rejected');
|
|
723
|
-
if (failedServices.length > 0) {
|
|
724
|
-
console.error('\nā Failed to build services:');
|
|
725
|
-
failedServices.forEach((result, index) => {
|
|
726
|
-
const failedIndices = serviceResults.map((r, i) => r.status === 'rejected' ? i : -1).filter(i => i >= 0);
|
|
727
|
-
const svc = services[failedIndices[index]];
|
|
728
|
-
const reason = result.reason;
|
|
729
|
-
console.error(`\n Service: ${svc.name}`);
|
|
730
|
-
console.error(` Input: ${svc.script}`);
|
|
731
|
-
console.error(formatBuildError(reason));
|
|
732
|
-
});
|
|
733
|
-
throw new Error('Service build failed. See errors above.');
|
|
734
|
-
}
|
|
735
|
-
}
|
|
886
|
+
// Build service and tool scripts (same Vite config and axios wrapper)
|
|
887
|
+
await buildServerScripts(path, mode, join(serverDir, 'services'), services, 'Service');
|
|
888
|
+
await buildServerScripts(path, mode, join(serverDir, 'tools'), tools, 'Tool');
|
|
736
889
|
console.log("ā
All builds completed successfully");
|
|
737
890
|
}
|
|
738
891
|
console.log("Packaging app...");
|
|
@@ -752,7 +905,7 @@ class ForgeCommand {
|
|
|
752
905
|
client.forge().bundleUpload(buffer).then(() => {
|
|
753
906
|
console.log('Bundle uploaded successfully');
|
|
754
907
|
}).catch((error) => {
|
|
755
|
-
console.error('\x1b[31m%s\x1b[0m', `Bundle upload failed: ${error.response?.data?.message || error.message}`);
|
|
908
|
+
console.error('\x1b[31m%s\x1b[0m', `Bundle upload failed: ${forbiddenDetails(error.response?.data) ?? (error.response?.data?.message || error.message)}`);
|
|
756
909
|
});
|
|
757
910
|
});
|
|
758
911
|
}
|
|
@@ -829,6 +982,17 @@ class ForgeCommand {
|
|
|
829
982
|
srv.on('error', reject);
|
|
830
983
|
});
|
|
831
984
|
}
|
|
985
|
+
// Two independent mints. The page is a view session and refreshes its own token in the
|
|
986
|
+
// browser, which a source-minted actor cannot do, so it is NOT source-minted. The service
|
|
987
|
+
// server runs submitted source and re-mints on 401/403 instead of refreshing.
|
|
988
|
+
const devEnv = env === 'live' ? 'live' : 'dev';
|
|
989
|
+
const pageToken = new ForgeDevToken(host, appName ?? '', devEnv, Util.getCurrentProfile().token, false);
|
|
990
|
+
const serviceToken = new ForgeDevToken(host, appName ?? '', devEnv, Util.getCurrentProfile().token, true);
|
|
991
|
+
// The page and services run as the app or not at all. The developer's token only mints.
|
|
992
|
+
if (!(await pageToken.current())) {
|
|
993
|
+
console.error(`ā ${pageToken.failureMessage()}`);
|
|
994
|
+
process.exit(1);
|
|
995
|
+
}
|
|
832
996
|
// Start Vite dev server
|
|
833
997
|
const server = await createServer({
|
|
834
998
|
root: path,
|
|
@@ -850,7 +1014,7 @@ class ForgeCommand {
|
|
|
850
1014
|
DEV_HUB_PORT
|
|
851
1015
|
},
|
|
852
1016
|
plugins: [
|
|
853
|
-
forgeDevKernelPlugin(appName, platformUrl, DEV_HUB_PORT),
|
|
1017
|
+
forgeDevKernelPlugin(appName, platformUrl, DEV_HUB_PORT, env ?? 'dev', host, pageToken),
|
|
854
1018
|
kortexDevPlugin({
|
|
855
1019
|
host,
|
|
856
1020
|
token: Util.getCurrentProfile().token,
|
|
@@ -1014,10 +1178,8 @@ class ForgeCommand {
|
|
|
1014
1178
|
// --- Local service dev server ---
|
|
1015
1179
|
if (appName && services && services.length > 0) {
|
|
1016
1180
|
const os = await import('os');
|
|
1017
|
-
const http = await import('http');
|
|
1018
1181
|
const { join } = await import('path');
|
|
1019
1182
|
const { readFileSync, existsSync, mkdirSync } = await import('fs');
|
|
1020
|
-
const { randomUUID } = await import('crypto');
|
|
1021
1183
|
const profile = Util.getCurrentProfile();
|
|
1022
1184
|
const serviceDir = join(os.default.tmpdir(), `ptkl-dev-${appName}`, '_services');
|
|
1023
1185
|
mkdirSync(serviceDir, { recursive: true });
|
|
@@ -1090,124 +1252,17 @@ class ForgeCommand {
|
|
|
1090
1252
|
}
|
|
1091
1253
|
});
|
|
1092
1254
|
}
|
|
1093
|
-
// Build a lookup of service config by name
|
|
1094
|
-
const serviceConfig = {};
|
|
1095
|
-
for (const svc of services) {
|
|
1096
|
-
serviceConfig[svc.name] = svc;
|
|
1097
|
-
}
|
|
1098
1255
|
const SERVICE_PORT = servicePort;
|
|
1099
|
-
const
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
const url = new URL(req.url || '/', `http://localhost:${SERVICE_PORT}`);
|
|
1110
|
-
const serviceName = url.pathname.replace(/^\//, '').replace(/\/$/, '');
|
|
1111
|
-
if (!serviceName || serviceName === '') {
|
|
1112
|
-
// List available services
|
|
1113
|
-
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
1114
|
-
res.end(JSON.stringify({
|
|
1115
|
-
app: appName,
|
|
1116
|
-
type: appType,
|
|
1117
|
-
services: services.map((s) => ({
|
|
1118
|
-
name: s.name,
|
|
1119
|
-
access: s.access || 'public',
|
|
1120
|
-
url: `http://localhost:${SERVICE_PORT}/${s.name}`,
|
|
1121
|
-
})),
|
|
1122
|
-
}, null, 2));
|
|
1123
|
-
return;
|
|
1124
|
-
}
|
|
1125
|
-
const code = serviceBundles[serviceName];
|
|
1126
|
-
if (!code) {
|
|
1127
|
-
res.writeHead(404, { 'Content-Type': 'application/json' });
|
|
1128
|
-
res.end(JSON.stringify({ error: `Service "${serviceName}" not found` }));
|
|
1129
|
-
return;
|
|
1130
|
-
}
|
|
1131
|
-
// Read request body
|
|
1132
|
-
const chunks = [];
|
|
1133
|
-
for await (const chunk of req)
|
|
1134
|
-
chunks.push(chunk);
|
|
1135
|
-
const rawBody = Buffer.concat(chunks).toString();
|
|
1136
|
-
let parsedBody = {};
|
|
1137
|
-
try {
|
|
1138
|
-
parsedBody = rawBody ? JSON.parse(rawBody) : {};
|
|
1139
|
-
}
|
|
1140
|
-
catch {
|
|
1141
|
-
parsedBody = rawBody;
|
|
1142
|
-
}
|
|
1143
|
-
// Parse query params
|
|
1144
|
-
const query = {};
|
|
1145
|
-
url.searchParams.forEach((v, k) => { query[k] = v; });
|
|
1146
|
-
// Build request headers object
|
|
1147
|
-
const reqHeaders = {};
|
|
1148
|
-
for (const [k, v] of Object.entries(req.headers)) {
|
|
1149
|
-
if (typeof v === 'string')
|
|
1150
|
-
reqHeaders[k] = v;
|
|
1151
|
-
}
|
|
1152
|
-
const svcConf = serviceConfig[serviceName];
|
|
1153
|
-
const executionId = randomUUID();
|
|
1154
|
-
console.log(`ā ${req.method} /${serviceName} (${executionId.slice(0, 8)})`);
|
|
1155
|
-
try {
|
|
1156
|
-
const evalResponse = await axios.post(`${profile.host}/luma/forge-runtime/api/services/exec`, {
|
|
1157
|
-
expression: code,
|
|
1158
|
-
project_uuid: 'dev',
|
|
1159
|
-
env: env ?? 'dev',
|
|
1160
|
-
actor: profile.token,
|
|
1161
|
-
context: {
|
|
1162
|
-
appUuid: `dev-${appName}`,
|
|
1163
|
-
appName,
|
|
1164
|
-
serviceName,
|
|
1165
|
-
executionId,
|
|
1166
|
-
access: svcConf?.access || 'public',
|
|
1167
|
-
},
|
|
1168
|
-
input: parsedBody,
|
|
1169
|
-
body: parsedBody,
|
|
1170
|
-
query,
|
|
1171
|
-
headers: reqHeaders,
|
|
1172
|
-
}, {
|
|
1173
|
-
headers: {
|
|
1174
|
-
'Content-Type': 'application/json',
|
|
1175
|
-
'Authorization': `Bearer ${profile.token}`,
|
|
1176
|
-
},
|
|
1177
|
-
timeout: 310000,
|
|
1178
|
-
validateStatus: () => true,
|
|
1179
|
-
});
|
|
1180
|
-
const data = evalResponse.data;
|
|
1181
|
-
if (data.logs?.length) {
|
|
1182
|
-
data.logs.forEach((log) => console.log(` š [${serviceName}] ${log}`));
|
|
1183
|
-
}
|
|
1184
|
-
if (data.error) {
|
|
1185
|
-
res.writeHead(evalResponse.status || 500, { 'Content-Type': 'application/json' });
|
|
1186
|
-
res.end(JSON.stringify({ error: data.error, logs: data.logs }));
|
|
1187
|
-
console.log(` ā [${serviceName}] ${data.error}`);
|
|
1188
|
-
}
|
|
1189
|
-
else if (data.response) {
|
|
1190
|
-
const resp = data.response;
|
|
1191
|
-
const status = resp.statusCode || 200;
|
|
1192
|
-
const contentType = resp.contentType || 'application/json';
|
|
1193
|
-
res.writeHead(status, { 'Content-Type': contentType });
|
|
1194
|
-
res.end(typeof resp.body === 'string' ? resp.body : JSON.stringify(resp.body));
|
|
1195
|
-
console.log(` ā
[${serviceName}] ${status} ${contentType}`);
|
|
1196
|
-
}
|
|
1197
|
-
else {
|
|
1198
|
-
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
1199
|
-
res.end(JSON.stringify(data));
|
|
1200
|
-
console.log(` ā
[${serviceName}] 200`);
|
|
1201
|
-
}
|
|
1202
|
-
}
|
|
1203
|
-
catch (err) {
|
|
1204
|
-
const msg = err.response?.data?.message || err.message;
|
|
1205
|
-
res.writeHead(502, { 'Content-Type': 'application/json' });
|
|
1206
|
-
res.end(JSON.stringify({ error: `Eval server error: ${msg}` }));
|
|
1207
|
-
console.error(` ā [${serviceName}] ${msg}`);
|
|
1208
|
-
}
|
|
1209
|
-
});
|
|
1210
|
-
server.listen(SERVICE_PORT, () => {
|
|
1256
|
+
const serviceExec = new ForgeDevServiceExec(`${profile.host}/luma/forge-runtime/api/services/exec`, serviceToken, (url, body, config) => axios.post(url, body, config));
|
|
1257
|
+
new ForgeDevServiceServer({
|
|
1258
|
+
port: SERVICE_PORT,
|
|
1259
|
+
appName,
|
|
1260
|
+
appType,
|
|
1261
|
+
env: env ?? 'dev',
|
|
1262
|
+
services: services,
|
|
1263
|
+
bundles: serviceBundles,
|
|
1264
|
+
exec: serviceExec,
|
|
1265
|
+
}).listen(() => {
|
|
1211
1266
|
console.log(`\nā” Service dev server running at http://localhost:${SERVICE_PORT}`);
|
|
1212
1267
|
for (const svc of services) {
|
|
1213
1268
|
console.log(` POST http://localhost:${SERVICE_PORT}/${svc.name}`);
|
|
@@ -1381,7 +1436,12 @@ class ForgeCommand {
|
|
|
1381
1436
|
console.log(`No '${scriptType}' script defined in ptkl.config.js`);
|
|
1382
1437
|
return;
|
|
1383
1438
|
}
|
|
1384
|
-
|
|
1439
|
+
// distPath may be relative in ptkl.config.js; bundle() resolves it by chdir'ing into the app
|
|
1440
|
+
// dir first, and this runs from wherever the developer invoked ptkl.
|
|
1441
|
+
const dist = distPath
|
|
1442
|
+
? (isAbsolute(distPath) ? distPath : join(appPath, distPath))
|
|
1443
|
+
: join(appPath, 'dist');
|
|
1444
|
+
const scriptFile = bundleFilePath(dist, 'server', `${scriptType}.script.js`);
|
|
1385
1445
|
let scriptCode;
|
|
1386
1446
|
try {
|
|
1387
1447
|
scriptCode = readFileSync(scriptFile, 'utf-8');
|