synthos 0.7.2 → 0.9.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 +215 -65
- package/default-pages/application/page.html +42 -0
- package/default-pages/application/page.json +10 -0
- package/default-pages/elevenlabs_effects_studio/page.html +1363 -0
- package/default-pages/elevenlabs_effects_studio/page.json +11 -0
- package/default-pages/elevenlabs_voice_studio/page.html +801 -0
- package/default-pages/elevenlabs_voice_studio/page.json +11 -0
- package/default-pages/{json_tools.html → json_tools/page.html} +13 -11
- package/default-pages/json_tools/page.json +10 -0
- package/default-pages/my_notes/notes/a1b2c3d4-e5f6-7890-abcd-ef1234567890.json +5 -0
- package/default-pages/my_notes/page.html +132 -0
- package/default-pages/{my_notes.json → my_notes/page.json} +2 -2
- package/default-pages/neon_asteroids/files/Ambient_Space.mp3 +0 -0
- package/default-pages/neon_asteroids/files/Ambient_Space2.mp3 +0 -0
- package/default-pages/neon_asteroids/files/Ambient_Space3.mp3 +0 -0
- package/default-pages/neon_asteroids/files/Asteroid_Explosion.mp3 +0 -0
- package/default-pages/neon_asteroids/files/Hyperspace_Jump.mp3 +0 -0
- package/default-pages/neon_asteroids/files/Laser_Fire.mp3 +0 -0
- package/default-pages/neon_asteroids/files/Menu_Navigate.mp3 +0 -0
- package/default-pages/neon_asteroids/files/Power_Up_Collect.mp3 +0 -0
- package/default-pages/neon_asteroids/files/Saucer_Alert.mp3 +0 -0
- package/default-pages/neon_asteroids/files/Ship_Thrust.mp3 +0 -0
- package/default-pages/neon_asteroids/files/effects.json +74 -0
- package/default-pages/neon_asteroids/page.html +1822 -0
- package/default-pages/{neon_asteroids.json → neon_asteroids/page.json} +3 -3
- package/default-pages/oregon_trail/page.html +323 -0
- package/default-pages/oregon_trail/page.json +12 -0
- package/default-pages/retro_game_starter/page.html +1308 -0
- package/default-pages/retro_game_starter/page.json +12 -0
- package/default-pages/{sidebar_builder.html → sidebar_page/page.html} +12 -10
- package/default-pages/sidebar_page/page.json +10 -0
- package/default-pages/{solar_explorer.html → solar_explorer/page.html} +24 -29
- package/default-pages/{solar_explorer.json → solar_explorer/page.json} +4 -4
- package/default-pages/{solar_tutorial.html → solar_tutorial/page.html} +12 -10
- package/default-pages/solar_tutorial/page.json +10 -0
- package/default-pages/{two-panel_builder.html → two-panel_page/page.html} +13 -11
- package/default-pages/two-panel_page/page.json +10 -0
- package/default-pages/us_map/page.html +193 -0
- package/default-pages/us_map/page.json +12 -0
- package/default-pages/us_map_1850/page.html +326 -0
- package/default-pages/us_map_1850/page.json +12 -0
- package/default-pages/western_cities_1850/page.html +527 -0
- package/default-pages/western_cities_1850/page.json +12 -0
- package/default-themes/aurora-dawn.json +19 -0
- package/default-themes/aurora-dawn.v3.css +198 -0
- package/default-themes/aurora-dusk.json +19 -0
- package/default-themes/aurora-dusk.v3.css +200 -0
- package/default-themes/cosmos-dawn.json +19 -0
- package/default-themes/cosmos-dawn.v3.css +198 -0
- package/default-themes/cosmos-dusk.json +19 -0
- package/default-themes/cosmos-dusk.v3.css +200 -0
- package/default-themes/high-contrast-dark.json +19 -0
- package/default-themes/high-contrast-dark.v3.css +200 -0
- package/default-themes/high-contrast-light.json +19 -0
- package/default-themes/high-contrast-light.v3.css +198 -0
- package/default-themes/{nebula-dawn.css → nebula-dawn.v2.css} +134 -0
- package/default-themes/nebula-dawn.v3.css +199 -0
- package/default-themes/{nebula-dusk.css → nebula-dusk.v2.css} +128 -0
- package/default-themes/nebula-dusk.v3.css +201 -0
- package/default-themes/solar-flare-dawn.json +19 -0
- package/default-themes/solar-flare-dawn.v3.css +198 -0
- package/default-themes/solar-flare-dusk.json +19 -0
- package/default-themes/solar-flare-dusk.v3.css +200 -0
- package/dist/agents/a2a/a2aProvider.d.ts.map +1 -0
- package/dist/agents/a2a/a2aProvider.js +126 -0
- package/dist/agents/a2a/a2aProvider.js.map +1 -0
- package/dist/agents/discovery.d.ts.map +1 -0
- package/dist/agents/discovery.js +52 -0
- package/dist/agents/discovery.js.map +1 -0
- package/dist/agents/index.d.ts +7 -0
- package/dist/agents/index.d.ts.map +1 -0
- package/dist/agents/index.js +20 -0
- package/dist/agents/index.js.map +1 -0
- package/dist/agents/openclaw/gatewayManager.d.ts +117 -0
- package/dist/agents/openclaw/gatewayManager.d.ts.map +1 -0
- package/dist/agents/openclaw/gatewayManager.js +486 -0
- package/dist/agents/openclaw/gatewayManager.js.map +1 -0
- package/dist/agents/openclaw/openclawProvider.d.ts.map +1 -0
- package/dist/agents/openclaw/openclawProvider.js +237 -0
- package/dist/agents/openclaw/openclawProvider.js.map +1 -0
- package/dist/agents/openclaw/sshTunnelManager.d.ts +25 -0
- package/dist/agents/openclaw/sshTunnelManager.d.ts.map +1 -0
- package/dist/agents/openclaw/sshTunnelManager.js +359 -0
- package/dist/agents/openclaw/sshTunnelManager.js.map +1 -0
- package/dist/agents/types.d.ts.map +1 -0
- package/dist/agents/types.js +6 -0
- package/dist/agents/types.js.map +1 -0
- package/dist/builders/anthropic.d.ts +31 -0
- package/dist/builders/anthropic.d.ts.map +1 -0
- package/dist/builders/anthropic.js +227 -0
- package/dist/builders/anthropic.js.map +1 -0
- package/dist/builders/fireworksai.d.ts +9 -0
- package/dist/builders/fireworksai.d.ts.map +1 -0
- package/dist/builders/fireworksai.js +57 -0
- package/dist/builders/fireworksai.js.map +1 -0
- package/dist/builders/index.d.ts +13 -0
- package/dist/builders/index.d.ts.map +1 -0
- package/dist/builders/index.js +31 -0
- package/dist/builders/index.js.map +1 -0
- package/dist/builders/openai.d.ts +8 -0
- package/dist/builders/openai.d.ts.map +1 -0
- package/dist/builders/openai.js +87 -0
- package/dist/builders/openai.js.map +1 -0
- package/dist/builders/types.d.ts +54 -0
- package/dist/builders/types.d.ts.map +1 -0
- package/dist/builders/types.js +211 -0
- package/dist/builders/types.js.map +1 -0
- package/dist/connectors/index.d.ts.map +1 -1
- package/dist/connectors/index.js +3 -2
- package/dist/connectors/index.js.map +1 -1
- package/dist/connectors/registry.d.ts +2 -1
- package/dist/connectors/registry.d.ts.map +1 -1
- package/dist/connectors/registry.js +65 -96
- package/dist/connectors/registry.js.map +1 -1
- package/dist/connectors/types.d.ts.map +1 -1
- package/dist/customizer/Customizer.d.ts +57 -0
- package/dist/customizer/Customizer.d.ts.map +1 -0
- package/dist/customizer/Customizer.js +124 -0
- package/dist/customizer/Customizer.js.map +1 -0
- package/dist/customizer/index.d.ts.map +1 -0
- package/dist/customizer/index.js +9 -0
- package/dist/customizer/index.js.map +1 -0
- package/dist/files.d.ts +17 -0
- package/dist/files.d.ts.map +1 -1
- package/dist/files.js +75 -1
- package/dist/files.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/init.d.ts +10 -6
- package/dist/init.d.ts.map +1 -1
- package/dist/init.js +97 -86
- package/dist/init.js.map +1 -1
- package/dist/migrations.d.ts.map +1 -1
- package/dist/migrations.js +142 -145
- package/dist/migrations.js.map +1 -1
- package/dist/models/anthropic.d.ts +24 -0
- package/dist/models/anthropic.d.ts.map +1 -0
- package/dist/models/anthropic.js +103 -0
- package/dist/models/anthropic.js.map +1 -0
- package/dist/models/chainOfThought.d.ts.map +1 -0
- package/dist/models/chainOfThought.js +45 -0
- package/dist/models/chainOfThought.js.map +1 -0
- package/dist/models/fireworksai.d.ts.map +1 -0
- package/dist/models/fireworksai.js +141 -0
- package/dist/models/fireworksai.js.map +1 -0
- package/dist/models/index.d.ts +7 -1
- package/dist/models/index.d.ts.map +1 -1
- package/dist/models/index.js +20 -1
- package/dist/models/index.js.map +1 -1
- package/dist/models/logCompletePrompt.d.ts.map +1 -0
- package/dist/models/logCompletePrompt.js +23 -0
- package/dist/models/logCompletePrompt.js.map +1 -0
- package/dist/models/openai.d.ts +24 -0
- package/dist/models/openai.d.ts.map +1 -0
- package/dist/models/openai.js +101 -0
- package/dist/models/openai.js.map +1 -0
- package/dist/models/providers.d.ts.map +1 -1
- package/dist/models/providers.js +12 -4
- package/dist/models/providers.js.map +1 -1
- package/dist/models/types.d.ts +53 -2
- package/dist/models/types.d.ts.map +1 -1
- package/dist/models/types.js +21 -0
- package/dist/models/types.js.map +1 -1
- package/dist/models/utils.d.ts.map +1 -0
- package/dist/models/utils.js +21 -0
- package/dist/models/utils.js.map +1 -0
- package/dist/pages.d.ts +30 -7
- package/dist/pages.d.ts.map +1 -1
- package/dist/pages.js +177 -55
- package/dist/pages.js.map +1 -1
- package/dist/scripts.d.ts.map +1 -1
- package/dist/scripts.js +4 -3
- package/dist/scripts.js.map +1 -1
- package/dist/service/createCompletePrompt.d.ts.map +1 -1
- package/dist/service/createCompletePrompt.js +9 -6
- package/dist/service/createCompletePrompt.js.map +1 -1
- package/dist/service/generateImage.d.ts.map +1 -1
- package/dist/service/generateImage.js +3 -3
- package/dist/service/generateImage.js.map +1 -1
- package/dist/service/server.d.ts.map +1 -1
- package/dist/service/server.js +39 -7
- package/dist/service/server.js.map +1 -1
- package/dist/service/transformPage.d.ts +47 -18
- package/dist/service/transformPage.d.ts.map +1 -1
- package/dist/service/transformPage.js +559 -270
- package/dist/service/transformPage.js.map +1 -1
- package/dist/service/useAgentRoutes.d.ts +5 -0
- package/dist/service/useAgentRoutes.d.ts.map +1 -0
- package/dist/service/useAgentRoutes.js +392 -0
- package/dist/service/useAgentRoutes.js.map +1 -0
- package/dist/service/useApiRoutes.d.ts.map +1 -1
- package/dist/service/useApiRoutes.js +380 -138
- package/dist/service/useApiRoutes.js.map +1 -1
- package/dist/service/useConnectorRoutes.d.ts.map +1 -1
- package/dist/service/useConnectorRoutes.js +20 -9
- package/dist/service/useConnectorRoutes.js.map +1 -1
- package/dist/service/useFileRoutes.d.ts +4 -0
- package/dist/service/useFileRoutes.d.ts.map +1 -0
- package/dist/service/useFileRoutes.js +122 -0
- package/dist/service/useFileRoutes.js.map +1 -0
- package/dist/service/usePageRoutes.d.ts.map +1 -1
- package/dist/service/usePageRoutes.js +660 -68
- package/dist/service/usePageRoutes.js.map +1 -1
- package/dist/service/useSharedDataRoutes.d.ts +4 -0
- package/dist/service/useSharedDataRoutes.d.ts.map +1 -0
- package/dist/service/useSharedDataRoutes.js +104 -0
- package/dist/service/useSharedDataRoutes.js.map +1 -0
- package/dist/service/useSharedFileRoutes.d.ts +4 -0
- package/dist/service/useSharedFileRoutes.d.ts.map +1 -0
- package/dist/service/useSharedFileRoutes.js +121 -0
- package/dist/service/useSharedFileRoutes.js.map +1 -0
- package/dist/settings.d.ts +3 -1
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +5 -8
- package/dist/settings.js.map +1 -1
- package/dist/synthos-cli.d.ts.map +1 -1
- package/dist/synthos-cli.js +4 -3
- package/dist/synthos-cli.js.map +1 -1
- package/dist/themes.d.ts +15 -0
- package/dist/themes.d.ts.map +1 -1
- package/dist/themes.js +106 -20
- package/dist/themes.js.map +1 -1
- package/migration-rules/v1-to-v2.md +193 -0
- package/migration-rules/v2-to-v3.md +481 -0
- package/package.json +15 -11
- package/required-pages/builder/page.html +43 -0
- package/required-pages/builder/page.json +10 -0
- package/required-pages/pages/page.html +924 -0
- package/required-pages/pages/page.json +10 -0
- package/required-pages/settings/page.html +1753 -0
- package/required-pages/settings/page.json +10 -0
- package/required-pages/synthos_apis/page.html +846 -0
- package/required-pages/synthos_apis/page.json +10 -0
- package/required-pages/{synthos_scripts.html → synthos_scripts/page.html} +13 -11
- package/required-pages/synthos_scripts/page.json +10 -0
- package/service-connectors/airtable/connector.json +27 -0
- package/service-connectors/alpha-vantage/connector.json +26 -0
- package/service-connectors/brave-search/connector.json +26 -0
- package/service-connectors/cloudinary/connector.json +27 -0
- package/service-connectors/deepl/connector.json +28 -0
- package/service-connectors/elevenlabs/connector.json +30 -0
- package/service-connectors/giphy/connector.json +27 -0
- package/service-connectors/github/connector.json +29 -0
- package/service-connectors/huggingface/connector.json +27 -0
- package/service-connectors/imgur/connector.json +29 -0
- package/service-connectors/instagram/connector.json +43 -0
- package/service-connectors/jira/connector.json +28 -0
- package/service-connectors/mapbox/connector.json +26 -0
- package/service-connectors/nasa/connector.json +27 -0
- package/service-connectors/newsapi/connector.json +27 -0
- package/service-connectors/notion/connector.json +28 -0
- package/service-connectors/open-exchange-rates/connector.json +27 -0
- package/service-connectors/openweathermap/connector.json +26 -0
- package/service-connectors/pexels/connector.json +27 -0
- package/service-connectors/resend/connector.json +29 -0
- package/service-connectors/rss2json/connector.json +27 -0
- package/service-connectors/sendgrid/connector.json +27 -0
- package/service-connectors/spoonacular/connector.json +28 -0
- package/service-connectors/stability-ai/connector.json +27 -0
- package/service-connectors/twilio/connector.json +28 -0
- package/service-connectors/unsplash/connector.json +27 -0
- package/service-connectors/wolfram-alpha/connector.json +26 -0
- package/service-connectors/youtube-data/connector.json +30 -0
- package/src/agents/a2a/a2aProvider.ts +110 -0
- package/src/agents/discovery.ts +74 -0
- package/src/agents/index.ts +6 -0
- package/src/agents/openclaw/gatewayManager.ts +570 -0
- package/src/agents/openclaw/openclawProvider.ts +259 -0
- package/src/agents/openclaw/sshTunnelManager.ts +393 -0
- package/src/agents/types.ts +82 -0
- package/src/builders/anthropic.ts +283 -0
- package/src/builders/fireworksai.ts +59 -0
- package/src/builders/index.ts +33 -0
- package/src/builders/openai.ts +89 -0
- package/src/builders/types.ts +261 -0
- package/src/connectors/index.ts +3 -1
- package/src/connectors/registry.ts +40 -96
- package/src/connectors/types.ts +25 -0
- package/src/customizer/Customizer.ts +151 -0
- package/src/customizer/index.ts +5 -0
- package/src/files.ts +71 -0
- package/src/index.ts +2 -1
- package/src/init.ts +138 -97
- package/src/migrations.ts +148 -145
- package/src/models/anthropic.ts +119 -0
- package/src/models/chainOfThought.ts +56 -0
- package/src/models/fireworksai.ts +143 -0
- package/src/models/index.ts +7 -1
- package/src/models/logCompletePrompt.ts +25 -0
- package/src/models/openai.ts +110 -0
- package/src/models/providers.ts +12 -3
- package/src/models/types.ts +97 -2
- package/src/models/utils.ts +16 -0
- package/src/pages.ts +176 -54
- package/src/scripts.ts +2 -2
- package/src/service/createCompletePrompt.ts +3 -1
- package/src/service/generateImage.ts +2 -2
- package/src/service/server.ts +39 -8
- package/src/service/transformPage.ts +605 -301
- package/src/service/useAgentRoutes.ts +428 -0
- package/src/service/useApiRoutes.ts +309 -45
- package/src/service/useConnectorRoutes.ts +21 -10
- package/src/service/useFileRoutes.ts +127 -0
- package/src/service/usePageRoutes.ts +736 -75
- package/src/service/useSharedDataRoutes.ts +106 -0
- package/src/service/useSharedFileRoutes.ts +126 -0
- package/src/settings.ts +8 -10
- package/src/synthos-cli.ts +4 -3
- package/src/themes.ts +103 -20
- package/static-files/favicon.svg +12 -0
- package/static-files/fluentlm-instructions.llmd +868 -0
- package/static-files/fluentlm-instructions.md +1595 -0
- package/static-files/fluentlm.css +4844 -0
- package/static-files/fluentlm.js +3602 -0
- package/static-files/fluentlm.min.css +1 -0
- package/static-files/fluentlm.min.js +1 -0
- package/static-files/helpers.v3.js +304 -0
- package/static-files/page.v3.js +1290 -0
- package/static-files/recommended-frameworks.llmd +81 -0
- package/static-files/recommended-frameworks.md +137 -0
- package/static-files/retro-game.js +877 -0
- package/static-files/shell.css +797 -0
- package/static-files/theme-dark.css +169 -0
- package/static-files/theme-light.css +169 -0
- package/tests/anthropic.spec.ts +84 -0
- package/tests/builders.spec.ts +139 -0
- package/tests/chainOfThought.spec.ts +108 -0
- package/tests/ensureScripts.spec.ts +82 -0
- package/tests/files.spec.ts +233 -0
- package/tests/fireworksai.spec.ts +92 -0
- package/tests/logCompletePrompt.spec.ts +74 -0
- package/tests/migrations.spec.ts +79 -1
- package/tests/openai.spec.ts +71 -0
- package/tests/pages.spec.ts +226 -1
- package/tests/providers.spec.ts +144 -0
- package/tests/scripts.spec.ts +209 -0
- package/tests/transformPage.spec.ts +456 -0
- package/tests/types.spec.ts +23 -0
- package/default-pages/app_builder.html +0 -40
- package/default-pages/app_builder.json +0 -1
- package/default-pages/json_tools.json +0 -1
- package/default-pages/my_notes.html +0 -33
- package/default-pages/neon_asteroids.html +0 -77
- package/default-pages/sidebar_builder.json +0 -1
- package/default-pages/solar_tutorial.json +0 -1
- package/default-pages/two-panel_builder.json +0 -1
- package/dist/connectors/index.d.ts +0 -3
- package/dist/connectors/types.d.ts +0 -61
- package/dist/index.d.ts +0 -7
- package/dist/migrations.d.ts +0 -11
- package/dist/models/providers.d.ts +0 -7
- package/dist/scripts.d.ts +0 -14
- package/dist/service/createCompletePrompt.d.ts +0 -5
- package/dist/service/debugLog.d.ts +0 -11
- package/dist/service/generateImage.d.ts +0 -32
- package/dist/service/index.d.ts +0 -8
- package/dist/service/modelInstructions.d.ts +0 -7
- package/dist/service/requiresSettings.d.ts +0 -3
- package/dist/service/server.d.ts +0 -4
- package/dist/service/useApiRoutes.d.ts +0 -4
- package/dist/service/useConnectorRoutes.d.ts +0 -4
- package/dist/service/useDataRoutes.d.ts +0 -4
- package/dist/service/usePageRoutes.d.ts +0 -5
- package/dist/synthos-cli.d.ts +0 -2
- package/images/home.png +0 -0
- package/images/page-management.png +0 -0
- package/images/settings.png +0 -0
- package/images/synthos-square.png +0 -0
- package/page-scripts/helpers-v2.js +0 -121
- package/page-scripts/page-v2.js +0 -615
- package/required-pages/builder.html +0 -74
- package/required-pages/builder.json +0 -1
- package/required-pages/pages.html +0 -196
- package/required-pages/pages.json +0 -1
- package/required-pages/settings.html +0 -841
- package/required-pages/settings.json +0 -1
- package/required-pages/synthos_apis.html +0 -272
- package/required-pages/synthos_apis.json +0 -1
- package/required-pages/synthos_scripts.json +0 -1
|
@@ -22,15 +22,22 @@ var __importStar = (this && this.__importStar) || function (mod) {
|
|
|
22
22
|
__setModuleDefault(result, mod);
|
|
23
23
|
return result;
|
|
24
24
|
};
|
|
25
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
26
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
27
|
+
};
|
|
25
28
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
26
29
|
exports.loadPageWithFallback = exports.usePageRoutes = void 0;
|
|
27
30
|
const pages_1 = require("../pages");
|
|
28
31
|
const settings_1 = require("../settings");
|
|
29
32
|
const transformPage_1 = require("./transformPage");
|
|
30
|
-
const modelInstructions_1 = require("./modelInstructions");
|
|
31
33
|
const createCompletePrompt_1 = require("./createCompletePrompt");
|
|
32
34
|
const debugLog_1 = require("./debugLog");
|
|
33
35
|
const themes_1 = require("../themes");
|
|
36
|
+
const builders_1 = require("../builders");
|
|
37
|
+
const connectors_1 = require("../connectors");
|
|
38
|
+
const scripts_1 = require("../scripts");
|
|
39
|
+
const path_1 = __importDefault(require("path"));
|
|
40
|
+
const files_1 = require("../files");
|
|
34
41
|
const cheerio = __importStar(require("cheerio"));
|
|
35
42
|
/**
|
|
36
43
|
* Required CDN imports that must be present on every v2 page.
|
|
@@ -38,6 +45,7 @@ const cheerio = __importStar(require("cheerio"));
|
|
|
38
45
|
*/
|
|
39
46
|
const REQUIRED_IMPORTS = [
|
|
40
47
|
{ selector: 'script[src*="marked"]', src: 'https://cdnjs.cloudflare.com/ajax/libs/marked/14.1.1/marked.min.js' },
|
|
48
|
+
{ selector: 'script[src*="html2canvas"]', src: 'https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js' },
|
|
41
49
|
];
|
|
42
50
|
/**
|
|
43
51
|
* Uses cheerio to ensure every required import is present in the page's <head>.
|
|
@@ -73,10 +81,11 @@ function injectPageHelpers(html, pageVersion) {
|
|
|
73
81
|
if (pageVersion < 2)
|
|
74
82
|
return html;
|
|
75
83
|
const tag = `<script id="page-helpers" src="/api/page-helpers.js?v=${pageVersion}"></script>`;
|
|
76
|
-
//
|
|
84
|
+
// Remove any existing page-helpers script (may be at wrong position from prior LLM output)
|
|
85
|
+
// so it gets re-injected at the correct position below.
|
|
77
86
|
const existing = html.match(/<script\s+id="page-helpers"[^>]*><\/script>/);
|
|
78
87
|
if (existing) {
|
|
79
|
-
|
|
88
|
+
html = html.replace(existing[0], '');
|
|
80
89
|
}
|
|
81
90
|
// Inject into <head> after page-info so helpers are available before inline body scripts
|
|
82
91
|
const pageInfo = html.indexOf('id="page-info"');
|
|
@@ -105,7 +114,341 @@ function injectPageScript(html, pageVersion) {
|
|
|
105
114
|
}
|
|
106
115
|
return html + '\n' + tag;
|
|
107
116
|
}
|
|
108
|
-
|
|
117
|
+
/**
|
|
118
|
+
* Wrap each inline <script> body in an IIFE so that top-level const/let
|
|
119
|
+
* declarations become function-scoped. This prevents "Identifier … has
|
|
120
|
+
* already been declared" errors when the page is reloaded via
|
|
121
|
+
* document.write() (which reuses the Window's global lexical environment).
|
|
122
|
+
*
|
|
123
|
+
* Skips: external scripts (src=), JSON data blocks, already-wrapped IIFEs,
|
|
124
|
+
* and empty bodies.
|
|
125
|
+
*/
|
|
126
|
+
function wrapInlineScriptsInIIFE(html) {
|
|
127
|
+
return html.replace(/<script([^>]*)>([\s\S]*?)<\/script>/gi, (match, attrs, body) => {
|
|
128
|
+
if (/\bsrc\s*=/i.test(attrs))
|
|
129
|
+
return match;
|
|
130
|
+
if (/\btype\s*=\s*["']application\/json["']/i.test(attrs))
|
|
131
|
+
return match;
|
|
132
|
+
const trimmed = body.trim();
|
|
133
|
+
if (!trimmed)
|
|
134
|
+
return match;
|
|
135
|
+
// Already wrapped — don't double-wrap
|
|
136
|
+
if (trimmed.startsWith('(function(){') || trimmed.startsWith('(function ()'))
|
|
137
|
+
return match;
|
|
138
|
+
return `<script${attrs}>(function(){${body}})();</script>`;
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Move any external <script src="..."> tags found in <body> up to the end
|
|
143
|
+
* of <head>, preserving their relative order. Library scripts (d3, Chart.js,
|
|
144
|
+
* marked, etc.) only define globals and don't touch the DOM, so executing
|
|
145
|
+
* them in <head> is safe and guarantees they are available before any inline
|
|
146
|
+
* <body> scripts run. This also eliminates browser "parser-blocking cross
|
|
147
|
+
* site script invoked via document.write" warnings.
|
|
148
|
+
*/
|
|
149
|
+
function hoistExternalScriptsToHead(html) {
|
|
150
|
+
const $ = cheerio.load(html, { decodeEntities: false });
|
|
151
|
+
const hoisted = [];
|
|
152
|
+
$('body script[src]').each((_, el) => {
|
|
153
|
+
const script = $(el);
|
|
154
|
+
// Don't move data-locked system scripts (page-script, page-helpers, etc.)
|
|
155
|
+
if (script.attr('data-locked') !== undefined)
|
|
156
|
+
return;
|
|
157
|
+
hoisted.push($.html(script));
|
|
158
|
+
script.remove();
|
|
159
|
+
});
|
|
160
|
+
if (hoisted.length > 0) {
|
|
161
|
+
$('head').append(hoisted.join('\n') + '\n');
|
|
162
|
+
}
|
|
163
|
+
return $.html();
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Inline error-capture script injected as the first child of <head> so it
|
|
167
|
+
* registers window.onerror / unhandledrejection *before* any page scripts run.
|
|
168
|
+
* Stripped before page transformation so the LLM never sees it.
|
|
169
|
+
*/
|
|
170
|
+
const ERROR_CAPTURE_ID = 'synthos-error-capture';
|
|
171
|
+
const ERROR_CAPTURE_SCRIPT = `<script id="${ERROR_CAPTURE_ID}">
|
|
172
|
+
(function(){
|
|
173
|
+
var E=window.__synthOSErrors=[];
|
|
174
|
+
window.onerror=function(m,s,l,c,e){
|
|
175
|
+
var entry=m+' at '+(s||'?')+':'+(l||'?')+':'+(c||'?');
|
|
176
|
+
if(e&&e.stack)entry+='\\n'+e.stack;
|
|
177
|
+
E.push(entry);showErr();return false;
|
|
178
|
+
};
|
|
179
|
+
window.addEventListener('unhandledrejection',function(ev){
|
|
180
|
+
var r=ev.reason;
|
|
181
|
+
E.push('Unhandled rejection: '+(r&&r.stack?r.stack:String(r)));showErr();
|
|
182
|
+
});
|
|
183
|
+
function showErr(){
|
|
184
|
+
var cm=document.getElementById('chatMessages');if(!cm)return;
|
|
185
|
+
if(showErr._p)return;showErr._p=true;
|
|
186
|
+
setTimeout(function(){
|
|
187
|
+
showErr._p=false;
|
|
188
|
+
var d=document.createElement('div');d.className='chat-message';
|
|
189
|
+
var p=document.createElement('p');
|
|
190
|
+
p.innerHTML='<strong>SynthOS:</strong> I noticed a JavaScript error on this page. '+
|
|
191
|
+
'<a href="#" style="color:var(--accent-primary,#a78bfa);text-decoration:underline;cursor:pointer" '+
|
|
192
|
+
'onclick="(function(e){e.preventDefault();var ci=document.getElementById(\\'chatInput\\');'+
|
|
193
|
+
'var f=document.getElementById(\\'chatForm\\');if(!ci||!f)return;'+
|
|
194
|
+
'ci.value=\\'Fix the following JavaScript errors on this page:\\\\n\\\\nCONSOLE_ERRORS:\\\\n\\'+window.__synthOSErrors.join(\\'\\\\n---\\\\n\\');'+
|
|
195
|
+
'window.__synthOSErrors=[];f.requestSubmit?f.requestSubmit():f.submit();})(event)">'+
|
|
196
|
+
'Let me try to fix it</a>';
|
|
197
|
+
d.appendChild(p);cm.appendChild(d);
|
|
198
|
+
cm.scrollTo({top:cm.scrollHeight,behavior:'smooth'});
|
|
199
|
+
},500);
|
|
200
|
+
}
|
|
201
|
+
})();
|
|
202
|
+
</script>`;
|
|
203
|
+
function injectErrorCapture(html, pageVersion) {
|
|
204
|
+
if (pageVersion < 2)
|
|
205
|
+
return html;
|
|
206
|
+
if (html.includes(`id="${ERROR_CAPTURE_ID}"`))
|
|
207
|
+
return html;
|
|
208
|
+
const $ = cheerio.load(html, { decodeEntities: false });
|
|
209
|
+
$('head').prepend(ERROR_CAPTURE_SCRIPT + '\n');
|
|
210
|
+
return $.html();
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Inject shell.css (always) and FluentLM base CSS/JS (v3 themes only).
|
|
214
|
+
* For v3 themes also adds the theme name class to <html> so scoped rules apply.
|
|
215
|
+
*/
|
|
216
|
+
function injectShellAssets(html, themeName, themeVersion, toolbarPosition) {
|
|
217
|
+
const $ = cheerio.load(html, { decodeEntities: false });
|
|
218
|
+
const themeLink = $('link#theme-css');
|
|
219
|
+
// Favicon
|
|
220
|
+
if ($('link#synthos-favicon').length === 0) {
|
|
221
|
+
$('head').prepend('<link id="synthos-favicon" rel="icon" type="image/svg+xml" href="/static/favicon.svg">\n');
|
|
222
|
+
}
|
|
223
|
+
// shell.css — always injected (provides toolbar + layout chrome)
|
|
224
|
+
if ($('link#shell-css').length === 0) {
|
|
225
|
+
const shellLink = '<link id="shell-css" rel="stylesheet" href="/static/shell.css">';
|
|
226
|
+
if (themeLink.length > 0) {
|
|
227
|
+
themeLink.before(shellLink + '\n');
|
|
228
|
+
}
|
|
229
|
+
else {
|
|
230
|
+
$('head').append(shellLink + '\n');
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
// FluentLM assets — only for v3 themes
|
|
234
|
+
if (themeVersion >= 3) {
|
|
235
|
+
// Add theme name class to <html> (e.g. "nebula-dusk")
|
|
236
|
+
$('html').addClass(themeName);
|
|
237
|
+
// Inject CSS: fluentlm.min.css before shell.css (load order matters)
|
|
238
|
+
if ($('link#fluentlm-css').length === 0) {
|
|
239
|
+
const fluentLink = '<link id="fluentlm-css" rel="stylesheet" href="/static/fluentlm.min.css">';
|
|
240
|
+
const shellCss = $('link#shell-css');
|
|
241
|
+
if (shellCss.length > 0) {
|
|
242
|
+
shellCss.before(fluentLink + '\n');
|
|
243
|
+
}
|
|
244
|
+
else if (themeLink.length > 0) {
|
|
245
|
+
themeLink.before(fluentLink + '\n');
|
|
246
|
+
}
|
|
247
|
+
else {
|
|
248
|
+
$('head').append(fluentLink + '\n');
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
// Inject FluentLM JS before </body>
|
|
252
|
+
if ($('script#fluentlm-js').length === 0) {
|
|
253
|
+
const fluentScript = '<script id="fluentlm-js" src="/static/fluentlm.min.js"></script>';
|
|
254
|
+
$('body').append(fluentScript + '\n');
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
$('html').attr('data-toolbar', toolbarPosition || 'left');
|
|
258
|
+
return $.html();
|
|
259
|
+
}
|
|
260
|
+
// ---------------------------------------------------------------------------
|
|
261
|
+
// Context section builders — assemble ContextSections from enabled features
|
|
262
|
+
// ---------------------------------------------------------------------------
|
|
263
|
+
function buildContextSection() {
|
|
264
|
+
const now = new Date();
|
|
265
|
+
const dateTime = now.toLocaleString('en-US', {
|
|
266
|
+
weekday: 'long', year: 'numeric', month: 'long', day: 'numeric',
|
|
267
|
+
hour: 'numeric', minute: '2-digit', hour12: true,
|
|
268
|
+
});
|
|
269
|
+
return {
|
|
270
|
+
title: '<CONTEXT>',
|
|
271
|
+
content: `Current date and time: ${dateTime}`,
|
|
272
|
+
instructions: '',
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
function buildServerApisSection(customizer) {
|
|
276
|
+
const content = customizer ? (0, transformPage_1.buildRouteHints)(customizer) : transformPage_1.serverAPIs;
|
|
277
|
+
return {
|
|
278
|
+
title: '<SERVER_APIS>',
|
|
279
|
+
content: content.replace(/^<SERVER_APIS>\n?/, ''),
|
|
280
|
+
instructions: 'provides a list of available server APIs and helper functions you can call from injected scripts. Use synthos.* helpers instead of raw fetch().',
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
async function buildServerScriptsSection(pagesFolder) {
|
|
284
|
+
const scripts = await (0, scripts_1.listScripts)(pagesFolder);
|
|
285
|
+
return {
|
|
286
|
+
title: '<SERVER_SCRIPTS>',
|
|
287
|
+
content: scripts || '',
|
|
288
|
+
instructions: 'provides a list of available scripts callable via synthos.scripts.run(id, variables).',
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
function buildConnectorsSection(configuredConnectors) {
|
|
292
|
+
if (!configuredConnectors)
|
|
293
|
+
return undefined;
|
|
294
|
+
const entries = Object.entries(configuredConnectors)
|
|
295
|
+
.filter(([, cfg]) => cfg.enabled && cfg.apiKey);
|
|
296
|
+
if (entries.length === 0)
|
|
297
|
+
return undefined;
|
|
298
|
+
const blocks = entries.map(([id, cfg]) => {
|
|
299
|
+
const def = (0, connectors_1.getConnectorRegistry)().find(d => d.id === id);
|
|
300
|
+
if (!def)
|
|
301
|
+
return `- ${id}`;
|
|
302
|
+
let block = `- ${def.name} (id: "${id}", category: ${def.category})\n Base URL: ${def.baseUrl}`;
|
|
303
|
+
if (def.hints) {
|
|
304
|
+
block += `\n Usage:\n${def.hints.split('\n').map(l => ' ' + l).join('\n')}`;
|
|
305
|
+
}
|
|
306
|
+
// Append dynamic OAuth context
|
|
307
|
+
if (def.authStrategy === 'oauth2') {
|
|
308
|
+
const oauthCfg = cfg;
|
|
309
|
+
block += '\n Auth: The proxy attaches the access token automatically. Do NOT pass access_token in body or query params.';
|
|
310
|
+
if (oauthCfg.userId) {
|
|
311
|
+
block += `\n User ID: ${oauthCfg.userId} — use this directly in API paths (e.g. /${oauthCfg.userId}/media).`;
|
|
312
|
+
}
|
|
313
|
+
else {
|
|
314
|
+
block += '\n User ID: Not yet resolved. Call GET /me/accounts to discover it, then GET /{page-id}?fields=instagram_business_account to get the IG user ID.';
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
return block;
|
|
318
|
+
});
|
|
319
|
+
const content = `The user has configured and enabled these connectors:\n${blocks.join('\n\n')}\n\nYou may use synthos.connectors.call(connector, method, path, opts) to call them.\nIMPORTANT: Before making any connector call, ALWAYS check that the connector is configured first using synthos.connectors.list(). If the connector is not configured, show the user a friendly message with a link to the Settings > Connectors page (/settings?tab=connectors) so they can set it up.\nDo NOT hardcode API keys. The connector proxy attaches authentication automatically.`;
|
|
320
|
+
return {
|
|
321
|
+
title: '<CONFIGURED_CONNECTORS>',
|
|
322
|
+
content,
|
|
323
|
+
instructions: '',
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
function buildAgentsSection(configuredAgents) {
|
|
327
|
+
const enabledAgents = (configuredAgents ?? []).filter(a => a.enabled);
|
|
328
|
+
if (enabledAgents.length === 0)
|
|
329
|
+
return undefined;
|
|
330
|
+
const agentBlocks = enabledAgents.map(a => {
|
|
331
|
+
let block = `- ${a.name} (id: "${a.id}", provider: ${a.provider})`;
|
|
332
|
+
block += `\n Description: ${a.description}`;
|
|
333
|
+
if (a.capabilities?.streaming) {
|
|
334
|
+
block += `\n Supports streaming: yes`;
|
|
335
|
+
}
|
|
336
|
+
if (a.skills && a.skills.length > 0) {
|
|
337
|
+
const skillList = a.skills.map(s => ` - ${s.name}: ${s.description}`).join('\n');
|
|
338
|
+
block += `\n Skills:\n${skillList}`;
|
|
339
|
+
}
|
|
340
|
+
return block;
|
|
341
|
+
});
|
|
342
|
+
return {
|
|
343
|
+
title: '<CONFIGURED_AGENTS>',
|
|
344
|
+
content: `The user has configured these agents:\n\n${agentBlocks.join('\n\n')}\n\n${transformPage_1.AGENT_API_REFERENCE}`,
|
|
345
|
+
instructions: '',
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
function buildThemeSection(themeInfo) {
|
|
349
|
+
let content = '';
|
|
350
|
+
if (themeInfo) {
|
|
351
|
+
const { mode, colors } = themeInfo;
|
|
352
|
+
const colorList = Object.entries(colors)
|
|
353
|
+
.map(([name, value]) => ` --${name}: ${value}`)
|
|
354
|
+
.join('\n');
|
|
355
|
+
content = `Mode: ${mode}\nCSS custom properties (use instead of hardcoded values):\n${colorList}\n\nShared shell classes (pre-styled by theme, do not redefine):\n .chat-panel — Left sidebar container (30% width)\n .chat-header — Chat panel title bar\n .chat-messages — Scrollable message container\n .chat-message — Individual message wrapper\n .chat-input — Message text input\n .chat-submit — Send button\n .viewer-panel — Right content area (70% width)\n .loading-overlay — Full-screen loading overlay\n .spinner — Animated loading spinner\n .modal-overlay — Full-screen modal backdrop (position:fixed, z-index:2000, backdrop-filter:blur). Add class "show" to display.\n .modal-content — Centered modal container\n .modal-header — Gradient header bar\n .modal-body — Modal content area\n .modal-footer — Bottom action bar (flex, space-between)\n .modal-footer-right — Right-aligned button group\n\nModals and popups: ALWAYS use the theme\'s .modal-overlay class for any modal or popup overlay. Do NOT create custom overlay classes with position:fixed and z-index. Structure:\n <div class="modal-overlay" id="myModal">\n <div class="modal-content">\n <div class="modal-header">Title</div>\n <div class="modal-body">Content</div>\n <div class="modal-footer"><div class="modal-footer-right"><button>OK</button></div></div>\n </div>\n </div>\nShow/hide by toggling the "show" class: el.classList.add(\'show\') / el.classList.remove(\'show\'). This ensures correct z-index layering above the chat toggle and other UI elements.\n\nPage title bars: To align with the chat header, apply these styles:\n min-height: var(--header-min-height);\n padding: var(--header-padding-vertical) var(--header-padding-horizontal);\n line-height: var(--header-line-height);\n display: flex; align-items: center; justify-content: center; box-sizing: border-box;\n\nFull-viewer mode: For games, animations, or full-screen content, add class "full-viewer" to the viewer-panel element to remove its padding.\n\nChat panel behaviours (auto-injected via page script — do NOT recreate in page code):\n The server injects page-v2.js after transformation. It provides:\n - Form submit handler: sets action to window.location.pathname, shows #loadingOverlay, disables inputs\n - Chat scroll to bottom (#chatMessages)\n - Chat toggle button (.chat-toggle) — created dynamically if not in markup\n - .chat-input-wrapper — wraps #chatInput with a brainstorm icon button\n - Brainstorm modal (#brainstormModal) — LLM-powered brainstorm UI, created dynamically\n - Focus management — keeps keyboard input directed to #chatInput\n\n Do NOT:\n - Create your own form submit handler, toggle button, or input wrapper\n - Modify or replace .chat-panel, .chat-header, #chatForm, or .chat-toggle\n - INSERT new <script> blocks that duplicate existing ones — when fixing JavaScript, UPDATE or REPLACE the existing script's nodeId instead. Always give inline scripts a unique id attribute.\n - Set the form action attribute (page-v2.js sets it dynamically)\n - Include these CSS rules (in the theme): #loadingOverlay position, .chat-submit:disabled, .chat-input:disabled\n\n To add chat messages: use insert with parentId of #chatMessages and position "append".\n #chatMessages is the only unlocked element inside .chat-panel.\n\nThe <html> element has class "${mode}-mode". Always add .light-mode CSS overrides for any page-specific styles so the page works in both light and dark themes, unless the user has explicitly requested a very specific color scheme.`;
|
|
356
|
+
}
|
|
357
|
+
return {
|
|
358
|
+
title: '<THEME>',
|
|
359
|
+
content,
|
|
360
|
+
instructions: 'provides details on the current theme\'s color scheme and shared shell classes to help you generate theme-aware pages that fit seamlessly into the user experience.',
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
const LLMD_READING_GUIDE = `Content below is LLMD v0.2 — a compressed, token-optimized format. Read it as follows:
|
|
364
|
+
|
|
365
|
+
Line types (each non-empty line starts with exactly one prefix, or none for prose):
|
|
366
|
+
|
|
367
|
+
- @name — scope. Sets the current topic. All following lines belong to this scope
|
|
368
|
+
until the next @. Hierarchy is flattened: @Auth after @API means separate scopes,
|
|
369
|
+
not nested. Reconstruct context from scope names.
|
|
370
|
+
- :k=v k2=v2 — attributes. Key-value facts about the current scope. ¦ (broken bar,
|
|
371
|
+
U+00A6) separates multiple values (e.g., methods=oauth2¦apikey). Multiple pairs
|
|
372
|
+
may appear on one line, space-separated. Parse each pair by splitting on the
|
|
373
|
+
first = (keys never contain =).
|
|
374
|
+
- plain text (no prefix) — prose about the current scope.
|
|
375
|
+
- -item — list item. Nested depth uses dots: -. child, -.. grandchild.
|
|
376
|
+
- →Node — relation. Current scope depends on Node. ←Node is reverse. =Node is
|
|
377
|
+
equivalence. Trailing ? means optional (e.g., →Cache?).
|
|
378
|
+
- ::lang followed by <<<...>>> — literal block. Code or data preserved exactly,
|
|
379
|
+
not compressed.
|
|
380
|
+
- ~k=v — file metadata. Optional, appears at top of file.
|
|
381
|
+
|
|
382
|
+
Reserved meta-attributes (compiler-generated, prefixed with _):
|
|
383
|
+
|
|
384
|
+
- :_col=<header> — column header for a 2-column property table.
|
|
385
|
+
- :_cols=c1¦c2¦c3 — column headers for a multi-column table.
|
|
386
|
+
- :_pfx=<prefix> — common prefix extracted from subsequent keys. Prepend it to
|
|
387
|
+
restore full key names (e.g., :_pfx=flm-text-- then :secondary=... means the
|
|
388
|
+
full key is flm-text--secondary).
|
|
389
|
+
|
|
390
|
+
Compression artifacts (content may be shortened — infer original phrasing):
|
|
391
|
+
|
|
392
|
+
- Common words (the, a, is, are, of, etc.) may be removed from prose and list items.
|
|
393
|
+
- Long phrases replaced with short forms (e.g., "in order to" → "to",
|
|
394
|
+
"application programming interface" → "API", "specification" → "spec").
|
|
395
|
+
- Units shortened (e.g., "1000 requests per minute" → "1000/m",
|
|
396
|
+
"seconds" → "s", "megabytes" → "MB").
|
|
397
|
+
- Boolean values compressed (Yes/No → Y/N, true/false → T/F,
|
|
398
|
+
enabled/disabled → Y/N).
|
|
399
|
+
- Trailing periods stripped from prose and list items.
|
|
400
|
+
- Negation (no, not, never) and modals (must, should, may, always) are always
|
|
401
|
+
preserved.`;
|
|
402
|
+
function buildLlmdReadingGuideSection() {
|
|
403
|
+
return {
|
|
404
|
+
title: '<LLMD_READING_GUIDE>',
|
|
405
|
+
content: LLMD_READING_GUIDE,
|
|
406
|
+
instructions: '',
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
async function buildFluentLMSection(config) {
|
|
410
|
+
const filePath = await (0, files_1.findFileInFolders)(config.staticFilesFolders, 'fluentlm-instructions.md');
|
|
411
|
+
if (!filePath)
|
|
412
|
+
return undefined;
|
|
413
|
+
try {
|
|
414
|
+
const content = await (0, files_1.loadFile)(filePath);
|
|
415
|
+
return {
|
|
416
|
+
title: '<FLUENTLM_COMPONENTS>',
|
|
417
|
+
content,
|
|
418
|
+
instructions: `<FLUENTLM_COMPONENTS> is the component library available on every page. You MUST use FluentLM components instead of writing custom HTML/CSS for standard UI elements.
|
|
419
|
+
REQUIRED: Use flm-button for buttons, flm-textfield for inputs, flm-dropdown for selects, flm-dialog/flm-panel/flm-modal for overlays, flm-pivot for tabs, flm-nav for navigation, flm-toggle for switches, flm-card for cards, flm-callout for tooltips, flm-messagebar for alerts, and all other components listed in <FLUENTLM_COMPONENTS>.
|
|
420
|
+
FORBIDDEN: Do NOT create custom CSS classes for buttons (e.g. .my-btn, .okr-btn), inputs, modals, cards, tabs, dropdowns, or any UI element that has a FluentLM equivalent. Do NOT use raw <button>, <input>, or <select> elements without FluentLM classes.
|
|
421
|
+
Apply FluentLM utility classes (flm-text--secondary, flm-stack, etc.) for layout and typography instead of custom CSS where possible.`,
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
catch {
|
|
425
|
+
return undefined;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
async function buildRecommendedFrameworksSection(config) {
|
|
429
|
+
const filePath = await (0, files_1.findFileInFolders)(config.staticFilesFolders, 'recommended-frameworks.llmd');
|
|
430
|
+
if (!filePath)
|
|
431
|
+
return undefined;
|
|
432
|
+
try {
|
|
433
|
+
const content = await (0, files_1.loadFile)(filePath);
|
|
434
|
+
return {
|
|
435
|
+
title: '<RECOMMENDED_FRAMEWORKS>',
|
|
436
|
+
content,
|
|
437
|
+
instructions: 'lists recommended third-party frameworks with CDN URLs. When a page needs a framework from this list, load it via <script> (or <link> for CSS) tags at the end of the <head> block. Always use the version shown in the CDN URL (it is the latest approved version).',
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
catch {
|
|
441
|
+
return undefined;
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
function buildMessageFormatSection(productName) {
|
|
445
|
+
return {
|
|
446
|
+
title: '<MESSAGE_FORMAT>',
|
|
447
|
+
content: `<div class="chat-message"><p><strong>{${productName}: | User:}</strong> {message contents}</p></div>`,
|
|
448
|
+
instructions: 'provides the HTML structure for chat messages in the chat panel.',
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
function usePageRoutes(config, app, customizer) {
|
|
109
452
|
// Redirect / to /home page
|
|
110
453
|
app.get('/', (req, res) => res.redirect(HOME_PAGE_ROUTE));
|
|
111
454
|
// Page retrieval
|
|
@@ -117,42 +460,40 @@ function usePageRoutes(config, app) {
|
|
|
117
460
|
res.redirect('/settings?firstRun=1');
|
|
118
461
|
return;
|
|
119
462
|
}
|
|
120
|
-
// Ensure page exists
|
|
121
|
-
const
|
|
463
|
+
// Ensure page exists — force fresh disk read for required pages
|
|
464
|
+
const isRequiredPage = config.requiredPages.includes(page);
|
|
465
|
+
const pageState = await loadPageWithFallback(page, config, isRequiredPage);
|
|
122
466
|
if (!pageState) {
|
|
123
467
|
res.status(404).send(PAGE_NOT_FOUND);
|
|
124
468
|
return;
|
|
125
469
|
}
|
|
126
470
|
// Load page metadata for version-based script injection
|
|
127
|
-
const metadata = await (0, pages_1.loadPageMetadata)(config.pagesFolder, page, config.
|
|
471
|
+
const metadata = await (0, pages_1.loadPageMetadata)(config.pagesFolder, page, config.requiredPagesFolders);
|
|
128
472
|
const pageVersion = metadata?.pageVersion ?? 0;
|
|
129
|
-
// Block outdated pages (redirect to
|
|
130
|
-
if (pageVersion < pages_1.PAGE_VERSION && !
|
|
131
|
-
res.redirect('/pages');
|
|
473
|
+
// Block outdated pages (redirect to tabs list so user sees upgrade UI)
|
|
474
|
+
if (pageVersion < pages_1.PAGE_VERSION && !config.requiredPages.includes(page)) {
|
|
475
|
+
res.redirect(customizer?.tabsListRoute ?? '/pages');
|
|
132
476
|
return;
|
|
133
477
|
}
|
|
478
|
+
// Load settings to determine theme version for FluentLM base injection
|
|
479
|
+
const settings = await (0, settings_1.loadSettings)(config.pagesFolder);
|
|
480
|
+
const themeName = settings.theme ?? 'nebula-dusk';
|
|
481
|
+
const themeVersion = await (0, themes_1.loadThemeVersion)(themeName, config);
|
|
134
482
|
let html = ensureRequiredImports(pageState, pageVersion);
|
|
483
|
+
html = injectErrorCapture(html, pageVersion);
|
|
484
|
+
html = injectShellAssets(html, themeName, themeVersion, settings.toolbarPosition);
|
|
135
485
|
html = injectPageInfoScript(html, page);
|
|
136
486
|
html = injectPageHelpers(html, pageVersion);
|
|
137
487
|
html = injectPageScript(html, pageVersion);
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
const isConfigured = await (0, settings_1.hasConfiguredSettings)(config.pagesFolder);
|
|
145
|
-
if (!isConfigured) {
|
|
146
|
-
res.redirect('/settings?firstRun=1');
|
|
147
|
-
return;
|
|
148
|
-
}
|
|
149
|
-
// Ensure page exists
|
|
150
|
-
const pageState = await loadPageWithFallback(page, config, true);
|
|
151
|
-
if (!pageState) {
|
|
152
|
-
res.status(404).send(PAGE_NOT_FOUND);
|
|
153
|
-
return;
|
|
488
|
+
// Inject version meta tag so undo/try-again links appear on page load
|
|
489
|
+
{
|
|
490
|
+
const latestVersion = await (0, pages_1.getLatestVersion)(config.pagesFolder, page);
|
|
491
|
+
if (latestVersion > 0) {
|
|
492
|
+
html = html.replace('</head>', `<meta name="synthos-version" content="${latestVersion}">\n</head>`);
|
|
493
|
+
}
|
|
154
494
|
}
|
|
155
|
-
|
|
495
|
+
html = hoistExternalScriptsToHead(html);
|
|
496
|
+
res.send(html);
|
|
156
497
|
});
|
|
157
498
|
// Page save
|
|
158
499
|
app.post('/:page/save', async (req, res) => {
|
|
@@ -191,22 +532,59 @@ function usePageRoutes(config, app) {
|
|
|
191
532
|
res.status(404).json({ error: PAGE_NOT_FOUND });
|
|
192
533
|
return;
|
|
193
534
|
}
|
|
194
|
-
//
|
|
195
|
-
|
|
535
|
+
// Always trim chat to the first message on save and remove undo links
|
|
536
|
+
{
|
|
196
537
|
const $ = cheerio.load(pageState);
|
|
197
538
|
const messages = $('#chatMessages .chat-message');
|
|
198
|
-
// Keep only the first message, remove the rest
|
|
199
539
|
messages.slice(1).remove();
|
|
200
|
-
//
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
if (
|
|
204
|
-
firstP
|
|
540
|
+
// Remove any undo links
|
|
541
|
+
$('#chatMessages .synthos-undo-link').remove();
|
|
542
|
+
// Update greeting text if provided
|
|
543
|
+
if (greeting && typeof greeting === 'string' && greeting.trim().length > 0) {
|
|
544
|
+
const firstP = messages.first().find('p');
|
|
545
|
+
const strong = firstP.find('strong');
|
|
546
|
+
if (strong.length) {
|
|
547
|
+
firstP.html('<strong>Synthos:</strong> ' + greeting.trim());
|
|
548
|
+
}
|
|
205
549
|
}
|
|
206
550
|
pageState = $.html();
|
|
207
551
|
}
|
|
552
|
+
// Inject save-line marker at the end of chat messages (skip for locked pages)
|
|
553
|
+
const sourceMetadata = await (0, pages_1.loadPageMetadata)(config.pagesFolder, page, config.requiredPagesFolders);
|
|
554
|
+
if (sourceMetadata?.mode !== 'locked') {
|
|
555
|
+
const $ = cheerio.load(pageState);
|
|
556
|
+
// Remove any existing save-line first
|
|
557
|
+
$('#chatMessages .save-line').remove();
|
|
558
|
+
// Append new save-line
|
|
559
|
+
$('#chatMessages').append('<div class="save-line" data-locked="true"><span class="save-line-label">Saved</span></div>');
|
|
560
|
+
pageState = $.html();
|
|
561
|
+
}
|
|
208
562
|
// Save as new page
|
|
209
563
|
await (0, pages_1.savePageState)(config.pagesFolder, saveAs, pageState, title, categories);
|
|
564
|
+
// Copy files (sound effects, etc.) from source page when saving as a different name
|
|
565
|
+
if (page !== saveAs) {
|
|
566
|
+
// Check source page's files/ dir in user pages, then fallback folders
|
|
567
|
+
let sourceFilesDir;
|
|
568
|
+
const userFilesDir = path_1.default.join(config.pagesFolder, 'pages', page, 'files');
|
|
569
|
+
if (await (0, files_1.checkIfExists)(userFilesDir)) {
|
|
570
|
+
sourceFilesDir = userFilesDir;
|
|
571
|
+
}
|
|
572
|
+
else {
|
|
573
|
+
for (const folder of config.requiredPagesFolders) {
|
|
574
|
+
const candidate = path_1.default.join(folder, page, 'files');
|
|
575
|
+
if (await (0, files_1.checkIfExists)(candidate)) {
|
|
576
|
+
sourceFilesDir = candidate;
|
|
577
|
+
break;
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
if (sourceFilesDir) {
|
|
582
|
+
const targetFilesDir = path_1.default.join(config.pagesFolder, 'pages', saveAs, 'files');
|
|
583
|
+
await (0, files_1.copyFolderRecursive)(sourceFilesDir, targetFilesDir);
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
// Clear version files after saving (fresh baseline)
|
|
587
|
+
await (0, pages_1.clearVersions)(config.pagesFolder, saveAs);
|
|
210
588
|
// Also update metadata with categories (in case page.json already existed)
|
|
211
589
|
await (0, pages_1.savePageMetadata)(config.pagesFolder, saveAs, {
|
|
212
590
|
title,
|
|
@@ -225,6 +603,62 @@ function usePageRoutes(config, app) {
|
|
|
225
603
|
res.status(500).json({ error: err.message });
|
|
226
604
|
}
|
|
227
605
|
});
|
|
606
|
+
// Page undo — roll back to the previous version
|
|
607
|
+
app.post('/:page/undo', async (req, res) => {
|
|
608
|
+
try {
|
|
609
|
+
const { page } = req.params;
|
|
610
|
+
const pagesFolder = config.pagesFolder;
|
|
611
|
+
const cv = await (0, pages_1.getLatestVersion)(pagesFolder, page);
|
|
612
|
+
if (cv <= 0) {
|
|
613
|
+
res.status(400).send('Nothing to undo');
|
|
614
|
+
return;
|
|
615
|
+
}
|
|
616
|
+
// Delete the current version file
|
|
617
|
+
const pageFolder = path_1.default.join(pagesFolder, 'pages', page);
|
|
618
|
+
const versionFile = path_1.default.join(pageFolder, `page.v${cv}.html`);
|
|
619
|
+
if (await (0, files_1.checkIfExists)(versionFile)) {
|
|
620
|
+
await (0, files_1.deleteFile)(versionFile);
|
|
621
|
+
}
|
|
622
|
+
// Load previous version (v{cv-1}.html, or page.html if rolling back to v0)
|
|
623
|
+
const prevVersion = cv - 1;
|
|
624
|
+
let previousHtml;
|
|
625
|
+
if (prevVersion > 0) {
|
|
626
|
+
previousHtml = await (0, pages_1.loadPageVersion)(pagesFolder, page, prevVersion);
|
|
627
|
+
}
|
|
628
|
+
else {
|
|
629
|
+
// v0 = the saved page.html baseline (user folder → required folders fallback)
|
|
630
|
+
previousHtml = await loadPageWithFallback(page, config, true);
|
|
631
|
+
}
|
|
632
|
+
if (!previousHtml) {
|
|
633
|
+
res.status(500).send('Could not load previous version');
|
|
634
|
+
return;
|
|
635
|
+
}
|
|
636
|
+
// Inject shell assets (same as GET handler)
|
|
637
|
+
const settings = await (0, settings_1.loadSettings)(config.pagesFolder);
|
|
638
|
+
const metadata = await (0, pages_1.loadPageMetadata)(pagesFolder, page, config.requiredPagesFolders);
|
|
639
|
+
const pv = metadata?.pageVersion ?? 0;
|
|
640
|
+
const themeName = settings.theme ?? 'nebula-dusk';
|
|
641
|
+
const themeVersion = await (0, themes_1.loadThemeVersion)(themeName, config);
|
|
642
|
+
let out = ensureRequiredImports(previousHtml, pv);
|
|
643
|
+
out = injectErrorCapture(out, pv);
|
|
644
|
+
out = injectShellAssets(out, themeName, themeVersion, settings.toolbarPosition);
|
|
645
|
+
out = injectPageInfoScript(out, page);
|
|
646
|
+
out = injectPageHelpers(out, pv);
|
|
647
|
+
out = injectPageScript(out, pv);
|
|
648
|
+
// Inject version meta tag if still have versions
|
|
649
|
+
if (prevVersion > 0) {
|
|
650
|
+
out = out.replace('</head>', `<meta name="synthos-version" content="${prevVersion}">\n</head>`);
|
|
651
|
+
}
|
|
652
|
+
// Same hardening as POST handler (undo also loads via document.write)
|
|
653
|
+
out = hoistExternalScriptsToHead(out);
|
|
654
|
+
out = wrapInlineScriptsInIIFE(out);
|
|
655
|
+
res.send(out);
|
|
656
|
+
}
|
|
657
|
+
catch (err) {
|
|
658
|
+
console.error(err);
|
|
659
|
+
res.status(500).send(err.message);
|
|
660
|
+
}
|
|
661
|
+
});
|
|
228
662
|
// Page transformation
|
|
229
663
|
app.post('/:page', async (req, res) => {
|
|
230
664
|
try {
|
|
@@ -241,71 +675,221 @@ function usePageRoutes(config, app) {
|
|
|
241
675
|
res.status(404).send(PAGE_NOT_FOUND);
|
|
242
676
|
return;
|
|
243
677
|
}
|
|
678
|
+
// Reject modifications to locked pages
|
|
679
|
+
const lockMetadata = await (0, pages_1.loadPageMetadata)(config.pagesFolder, page, config.requiredPagesFolders);
|
|
680
|
+
if (lockMetadata?.mode === 'locked') {
|
|
681
|
+
res.status(403).send('This page is locked and cannot be modified');
|
|
682
|
+
return;
|
|
683
|
+
}
|
|
244
684
|
// Get required and optional parameters
|
|
245
685
|
const { message } = req.body; // Extract the message from the request body
|
|
246
686
|
if (typeof message !== 'string') {
|
|
247
687
|
res.status(400).send('Invalid or missing message parameter');
|
|
248
688
|
return;
|
|
249
689
|
}
|
|
690
|
+
// Extract and validate optional attachments
|
|
691
|
+
let attachments;
|
|
692
|
+
if (Array.isArray(req.body.attachments)) {
|
|
693
|
+
attachments = [];
|
|
694
|
+
for (const att of req.body.attachments) {
|
|
695
|
+
if (att && typeof att.mediaType === 'string' && att.mediaType.startsWith('image/') && typeof att.data === 'string') {
|
|
696
|
+
attachments.push({ mediaType: att.mediaType, data: att.data, name: typeof att.name === 'string' ? att.name : undefined });
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
if (attachments.length === 0)
|
|
700
|
+
attachments = undefined;
|
|
701
|
+
}
|
|
250
702
|
// Create model instance
|
|
251
703
|
const innerCompletePrompt = await (0, createCompletePrompt_1.createCompletePrompt)(config.pagesFolder, 'builder', req.body.model);
|
|
252
704
|
const debugVerbose = config.debugPageUpdates;
|
|
253
705
|
let inputChars = 0;
|
|
254
706
|
let outputChars = 0;
|
|
255
|
-
const
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
outputChars += result.value?.length ?? 0;
|
|
265
|
-
}
|
|
266
|
-
if (debugVerbose) {
|
|
267
|
-
console.log((0, debugLog_1.green)((0, debugLog_1.dim)('\n ----- PAGE UPDATE RESPONSE -----')));
|
|
707
|
+
const wrapModel = (inner) => {
|
|
708
|
+
return async (args) => {
|
|
709
|
+
if (debugVerbose) {
|
|
710
|
+
console.log((0, debugLog_1.green)((0, debugLog_1.dim)('\n ===== PAGE UPDATE REQUEST =====')));
|
|
711
|
+
console.log((0, debugLog_1.green)(` SYSTEM:\n${args.system?.content}`));
|
|
712
|
+
console.log((0, debugLog_1.green)(`\n PROMPT:\n${args.prompt.content}`));
|
|
713
|
+
}
|
|
714
|
+
inputChars += (args.system?.content?.length ?? 0) + (args.prompt.content?.length ?? 0);
|
|
715
|
+
const result = await inner(args);
|
|
268
716
|
if (result.completed) {
|
|
269
|
-
|
|
717
|
+
outputChars += result.value?.length ?? 0;
|
|
270
718
|
}
|
|
271
|
-
|
|
272
|
-
console.log((0, debugLog_1.
|
|
719
|
+
if (debugVerbose) {
|
|
720
|
+
console.log((0, debugLog_1.green)((0, debugLog_1.dim)('\n ----- PAGE UPDATE RESPONSE -----')));
|
|
721
|
+
if (result.completed) {
|
|
722
|
+
console.log((0, debugLog_1.green)(` RESPONSE:\n${result.value}`));
|
|
723
|
+
}
|
|
724
|
+
else {
|
|
725
|
+
console.log((0, debugLog_1.red)(` ERROR: ${result.error?.message}`));
|
|
726
|
+
}
|
|
727
|
+
console.log((0, debugLog_1.green)((0, debugLog_1.dim)(' ================================\n')));
|
|
273
728
|
}
|
|
274
|
-
|
|
275
|
-
}
|
|
276
|
-
return result;
|
|
729
|
+
return result;
|
|
730
|
+
};
|
|
277
731
|
};
|
|
278
|
-
|
|
732
|
+
const wrappedCompletePrompt = wrapModel(innerCompletePrompt);
|
|
733
|
+
// Load settings and build context
|
|
279
734
|
const pagesFolder = config.pagesFolder;
|
|
280
735
|
const settings = await (0, settings_1.loadSettings)(config.pagesFolder);
|
|
281
|
-
const
|
|
282
|
-
const {
|
|
283
|
-
const
|
|
736
|
+
const entry = (0, settings_1.getModelEntry)(settings, 'builder');
|
|
737
|
+
const { instructions } = entry;
|
|
738
|
+
const productName = customizer?.productName ?? 'SynthOS';
|
|
739
|
+
// Build context sections from enabled features
|
|
740
|
+
const featureSections = [];
|
|
741
|
+
// CONTEXT section — always first so the model knows the current date/time
|
|
742
|
+
featureSections.push(buildContextSection());
|
|
743
|
+
// LLMD_READING_GUIDE section (first — tells model how to read compressed content)
|
|
744
|
+
featureSections.push(buildLlmdReadingGuideSection());
|
|
745
|
+
// SERVER_APIS section
|
|
746
|
+
featureSections.push(buildServerApisSection(customizer));
|
|
747
|
+
// SERVER_SCRIPTS section
|
|
748
|
+
featureSections.push(await buildServerScriptsSection(pagesFolder));
|
|
749
|
+
// CONFIGURED_CONNECTORS section
|
|
750
|
+
const connectorsSection = buildConnectorsSection(settings.connectors);
|
|
751
|
+
if (connectorsSection)
|
|
752
|
+
featureSections.push(connectorsSection);
|
|
753
|
+
// CONFIGURED_AGENTS section
|
|
754
|
+
const agentsSection = buildAgentsSection(settings.agents);
|
|
755
|
+
if (agentsSection)
|
|
756
|
+
featureSections.push(agentsSection);
|
|
757
|
+
// THEME section
|
|
284
758
|
const theme = settings.theme;
|
|
285
759
|
const themeInfo = await (0, themes_1.loadThemeInfo)(theme ?? 'nebula-dusk', config);
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
const
|
|
760
|
+
featureSections.push(buildThemeSection(themeInfo));
|
|
761
|
+
// FLUENTLM_COMPONENTS section
|
|
762
|
+
const fluentLMSection = await buildFluentLMSection(config);
|
|
763
|
+
if (fluentLMSection)
|
|
764
|
+
featureSections.push(fluentLMSection);
|
|
765
|
+
// RECOMMENDED_FRAMEWORKS section
|
|
766
|
+
const frameworksSection = await buildRecommendedFrameworksSection(config);
|
|
767
|
+
if (frameworksSection)
|
|
768
|
+
featureSections.push(frameworksSection);
|
|
769
|
+
// MESSAGE_FORMAT section
|
|
770
|
+
featureSections.push(buildMessageFormatSection(productName));
|
|
771
|
+
// Custom transform instructions as a section (backward compat)
|
|
772
|
+
const customTransformInstructions = customizer ? customizer.getTransformInstructions() : undefined;
|
|
773
|
+
if (customTransformInstructions && customTransformInstructions.length > 0) {
|
|
774
|
+
featureSections.push({
|
|
775
|
+
title: '<CUSTOM_INSTRUCTIONS>',
|
|
776
|
+
content: customTransformInstructions.join('\n'),
|
|
777
|
+
instructions: '',
|
|
778
|
+
});
|
|
779
|
+
}
|
|
780
|
+
// Custom context sections from Customizer (appended last)
|
|
781
|
+
if (customizer) {
|
|
782
|
+
featureSections.push(...customizer.getContextSections());
|
|
783
|
+
}
|
|
784
|
+
// Detect first edit (v0→v1) for saved pages
|
|
785
|
+
const isRequiredPage = config.requiredPages.includes(page);
|
|
786
|
+
const pageFolder = path_1.default.join(pagesFolder, 'pages', page);
|
|
787
|
+
const pageFileExists = await (0, files_1.checkIfExists)(path_1.default.join(pageFolder, 'page.html'));
|
|
788
|
+
let currentVersion = await (0, pages_1.getLatestVersion)(pagesFolder, page);
|
|
789
|
+
const isFirstEdit = !isRequiredPage && pageFileExists && currentVersion === 0;
|
|
790
|
+
// Try again — roll back to previous version before re-running the transform
|
|
791
|
+
const tryAgain = req.body.tryAgain === true;
|
|
792
|
+
let transformInput = pageState;
|
|
793
|
+
if (tryAgain && currentVersion > 0) {
|
|
794
|
+
// Delete current version file
|
|
795
|
+
const versionFile = path_1.default.join(pageFolder, `page.v${currentVersion}.html`);
|
|
796
|
+
if (await (0, files_1.checkIfExists)(versionFile)) {
|
|
797
|
+
await (0, files_1.deleteFile)(versionFile);
|
|
798
|
+
}
|
|
799
|
+
// Load previous version
|
|
800
|
+
const prevVersion = currentVersion - 1;
|
|
801
|
+
if (prevVersion > 0) {
|
|
802
|
+
transformInput = await (0, pages_1.loadPageVersion)(pagesFolder, page, prevVersion) ?? pageState;
|
|
803
|
+
}
|
|
804
|
+
else {
|
|
805
|
+
transformInput = await loadPageWithFallback(page, config, true) ?? pageState;
|
|
806
|
+
}
|
|
807
|
+
currentVersion = prevVersion;
|
|
808
|
+
}
|
|
809
|
+
// Create builder
|
|
810
|
+
const builder = (0, builders_1.createBuilder)(entry.provider, wrappedCompletePrompt, instructions, productName, {
|
|
811
|
+
apiKey: entry.configuration.apiKey,
|
|
812
|
+
model: entry.configuration.model,
|
|
813
|
+
wrapModel,
|
|
814
|
+
isFirstEdit,
|
|
815
|
+
tryAgain,
|
|
816
|
+
});
|
|
817
|
+
// Inject save-line before transform if not already present, so new
|
|
818
|
+
// messages appended by the LLM land after the marker.
|
|
819
|
+
{
|
|
820
|
+
const $pre = cheerio.load(transformInput, { decodeEntities: false });
|
|
821
|
+
if ($pre('#chatMessages').length > 0 && $pre('#chatMessages .save-line').length === 0) {
|
|
822
|
+
$pre('#chatMessages').append('<div class="save-line" data-locked="true"><span class="save-line-label">Saved</span></div>');
|
|
823
|
+
transformInput = $pre.html();
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
// Transform page
|
|
827
|
+
const result = await (0, transformPage_1.transformPage)({
|
|
828
|
+
pageState: transformInput,
|
|
829
|
+
message,
|
|
830
|
+
instructions,
|
|
831
|
+
builder,
|
|
832
|
+
additionalSections: featureSections,
|
|
833
|
+
isBuilder: page === 'builder',
|
|
834
|
+
productName,
|
|
835
|
+
attachments,
|
|
836
|
+
});
|
|
289
837
|
if (result.completed) {
|
|
290
|
-
|
|
838
|
+
let { html, changeCount } = result.value;
|
|
291
839
|
if (config.debug) {
|
|
292
840
|
const inTokens = (0, debugLog_1.estimateTokens)(inputChars).toLocaleString();
|
|
293
841
|
const outTokens = (0, debugLog_1.estimateTokens)(outputChars).toLocaleString();
|
|
294
842
|
console.log(` page: ${page} | message: ${message.length} chars | changes: ${changeCount} ops | ~${inTokens} in / ~${outTokens} out tokens`);
|
|
295
843
|
}
|
|
296
|
-
|
|
844
|
+
// Handle 0-ops from transforms: model returned no page changes.
|
|
845
|
+
// Append the user's message + a "try again" prompt with undo link.
|
|
846
|
+
// Still save as a version so undo logic stays simple.
|
|
847
|
+
// changeCount -1 means error/reply path already handled messaging.
|
|
848
|
+
if (changeCount === 0) {
|
|
849
|
+
const $ = cheerio.load(pageState, { decodeEntities: false });
|
|
850
|
+
const chatMessages = $('#chatMessages');
|
|
851
|
+
if (chatMessages.length > 0) {
|
|
852
|
+
const escapedMsg = message.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
853
|
+
chatMessages.append(`<div class="chat-message"><p><strong>User:</strong> ${escapedMsg}</p></div>`);
|
|
854
|
+
const tryAgainLink = `<a href="#" style="color:var(--themePrimary);text-decoration:underline;cursor:pointer" `
|
|
855
|
+
+ `onclick="(function(e){e.preventDefault();var ci=document.getElementById('chatInput');if(ci){ci.focus();ci.value='';}})(event)">try again</a>`;
|
|
856
|
+
const undoLink = `<a href="#" style="color:var(--themePrimary);text-decoration:underline;cursor:pointer" `
|
|
857
|
+
+ `onclick="(function(e){e.preventDefault();var o=document.getElementById('loadingOverlay');if(o)o.style.display='flex';`
|
|
858
|
+
+ `fetch(window.location.pathname+'/undo',{method:'POST',headers:{'Content-Type':'application/json'},body:'{}'})`
|
|
859
|
+
+ `.then(function(r){return r.text()}).then(function(h){document.open();document.write(h);document.close()})`
|
|
860
|
+
+ `.catch(function(){if(o)o.style.display='none'});})(event)">undo</a>`;
|
|
861
|
+
chatMessages.append(`<div class="chat-message"><p><strong>${productName}:</strong> Sorry, I wasn\u2019t able to make changes for that request. Please ${tryAgainLink} or ${undoLink}.</p></div>`);
|
|
862
|
+
}
|
|
863
|
+
html = $.html();
|
|
864
|
+
}
|
|
865
|
+
// Save version snapshot (working state for all pages, undo support for saved pages)
|
|
866
|
+
const nextVersion = currentVersion + 1;
|
|
867
|
+
await (0, pages_1.savePageVersion)(pagesFolder, page, nextVersion, html);
|
|
297
868
|
// Update lastModified timestamp in page metadata
|
|
298
|
-
const metadata = await (0, pages_1.loadPageMetadata)(pagesFolder, page, config.
|
|
869
|
+
const metadata = await (0, pages_1.loadPageMetadata)(pagesFolder, page, config.requiredPagesFolders);
|
|
299
870
|
if (metadata) {
|
|
300
871
|
metadata.lastModified = new Date().toISOString();
|
|
301
872
|
await (0, pages_1.savePageMetadata)(pagesFolder, page, metadata);
|
|
302
873
|
}
|
|
303
874
|
// Inject required imports and page scripts (same as GET)
|
|
304
875
|
const pv = metadata?.pageVersion ?? 0;
|
|
876
|
+
const themeName = settings.theme ?? 'nebula-dusk';
|
|
877
|
+
const themeVersion = await (0, themes_1.loadThemeVersion)(themeName, config);
|
|
305
878
|
let out = ensureRequiredImports(html, pv);
|
|
879
|
+
out = injectErrorCapture(out, pv);
|
|
880
|
+
out = injectShellAssets(out, themeName, themeVersion, settings.toolbarPosition);
|
|
306
881
|
out = injectPageInfoScript(out, page);
|
|
307
882
|
out = injectPageHelpers(out, pv);
|
|
308
883
|
out = injectPageScript(out, pv);
|
|
884
|
+
// Inject version meta tag for client-side undo support
|
|
885
|
+
if (nextVersion > 0) {
|
|
886
|
+
out = out.replace('</head>', `<meta name="synthos-version" content="${nextVersion}">\n</head>`);
|
|
887
|
+
}
|
|
888
|
+
// Hoist external scripts to <head> so libs load before
|
|
889
|
+
// inline body scripts, then wrap inlines in IIFEs to
|
|
890
|
+
// avoid const/let redeclaration via document.write().
|
|
891
|
+
out = hoistExternalScriptsToHead(out);
|
|
892
|
+
out = wrapInlineScriptsInIIFE(out);
|
|
309
893
|
res.send(out);
|
|
310
894
|
}
|
|
311
895
|
else {
|
|
@@ -325,13 +909,21 @@ function usePageRoutes(config, app) {
|
|
|
325
909
|
}
|
|
326
910
|
exports.usePageRoutes = usePageRoutes;
|
|
327
911
|
async function loadPageWithFallback(page, config, reset) {
|
|
912
|
+
if (reset) {
|
|
913
|
+
// Clear working-state versions so we get the fresh template
|
|
914
|
+
await (0, pages_1.clearVersions)(config.pagesFolder, page);
|
|
915
|
+
}
|
|
328
916
|
// Try primary pages folder first
|
|
329
|
-
const pageState = await (0, pages_1.loadPageState)(config.pagesFolder, page
|
|
330
|
-
if (pageState)
|
|
917
|
+
const pageState = await (0, pages_1.loadPageState)(config.pagesFolder, page);
|
|
918
|
+
if (pageState)
|
|
331
919
|
return pageState;
|
|
920
|
+
// Try fallback pages folders
|
|
921
|
+
for (const folder of config.requiredPagesFolders) {
|
|
922
|
+
const state = await (0, pages_1.loadPageState)(folder, page);
|
|
923
|
+
if (state)
|
|
924
|
+
return state;
|
|
332
925
|
}
|
|
333
|
-
|
|
334
|
-
return (0, pages_1.loadPageState)(config.requiredPagesFolder, page, reset);
|
|
926
|
+
return undefined;
|
|
335
927
|
}
|
|
336
928
|
exports.loadPageWithFallback = loadPageWithFallback;
|
|
337
929
|
//# sourceMappingURL=usePageRoutes.js.map
|