@livepreso/cdk 0.0.1

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.
Files changed (117) hide show
  1. package/dist/668.js +2 -0
  2. package/dist/assets/031b9314092954f3.woff2 +0 -0
  3. package/dist/assets/031cf8d6851ae28b.woff2 +0 -0
  4. package/dist/assets/04e13675b1493ad2.woff2 +0 -0
  5. package/dist/assets/0519ad6f9869d898.woff2 +0 -0
  6. package/dist/assets/07c6d6ea9c229edb.woff +0 -0
  7. package/dist/assets/0a9edc5b190f2190.woff +0 -0
  8. package/dist/assets/0ccfdf89065a00b3.woff2 +0 -0
  9. package/dist/assets/0ce1ebd07c368f63.woff +0 -0
  10. package/dist/assets/1192b38e490fc7d1.woff2 +0 -0
  11. package/dist/assets/17e097f3b9f2d542.woff2 +0 -0
  12. package/dist/assets/19f91f1ad9824715.woff +0 -0
  13. package/dist/assets/1cc7496cc9b77e08.woff +0 -0
  14. package/dist/assets/1e592275a4fc2c99.woff2 +0 -0
  15. package/dist/assets/1e8de1180277cf53.woff +0 -0
  16. package/dist/assets/21b7c92d576179bb.woff2 +0 -0
  17. package/dist/assets/259c166b717079d8.woff +0 -0
  18. package/dist/assets/30ec7aec36351a14.woff +0 -0
  19. package/dist/assets/318ac720200f56ad.svg +1 -0
  20. package/dist/assets/3372ffe2ab723644.woff +0 -0
  21. package/dist/assets/36927296f7219149.woff2 +0 -0
  22. package/dist/assets/3806f0522558b224.woff2 +0 -0
  23. package/dist/assets/3c6c2126b6583695.woff2 +0 -0
  24. package/dist/assets/3d62b6f4c938e2e0.woff +0 -0
  25. package/dist/assets/3f48d5c9b4d1724f.woff +0 -0
  26. package/dist/assets/4021a38ee294b169.png +0 -0
  27. package/dist/assets/434c501c034ff4d7.woff2 +0 -0
  28. package/dist/assets/43cee8b32aebce11.woff +0 -0
  29. package/dist/assets/456562a2e1e13e20.woff +0 -0
  30. package/dist/assets/48d247e34d3aa635.woff +0 -0
  31. package/dist/assets/495dffa7dcac87c7.woff +0 -0
  32. package/dist/assets/4a386aca9584dbb9.woff2 +0 -0
  33. package/dist/assets/4b70338a5df3d413.woff2 +0 -0
  34. package/dist/assets/4cc1ace7e0d08476.woff +0 -0
  35. package/dist/assets/5858323bed0fe4bc.woff +0 -0
  36. package/dist/assets/59a71b9c0e14a00c.woff2 +0 -0
  37. package/dist/assets/619287de139b93ac.woff +0 -0
  38. package/dist/assets/62df8e180451dc9c.woff2 +0 -0
  39. package/dist/assets/630c5ad5139b5844.woff2 +0 -0
  40. package/dist/assets/6690f2dc3ac60371.woff2 +0 -0
  41. package/dist/assets/69426761a47f790e.woff2 +0 -0
  42. package/dist/assets/69c066cbc1e388a8.svg +1 -0
  43. package/dist/assets/6bc65973da12e0db.woff2 +0 -0
  44. package/dist/assets/6c5480c146b7fec6.woff +0 -0
  45. package/dist/assets/6efba251d9ff16f0.woff +0 -0
  46. package/dist/assets/6f2be5c4e077a95f.woff +0 -0
  47. package/dist/assets/736e673b62aec3a1.woff +0 -0
  48. package/dist/assets/786c2167e5fb0419.woff2 +0 -0
  49. package/dist/assets/78dd43210d89bfa0.woff +0 -0
  50. package/dist/assets/790c228262b3cc43.woff +0 -0
  51. package/dist/assets/793b729fcc55fb15.woff2 +0 -0
  52. package/dist/assets/7a5dc43a36101231.woff2 +0 -0
  53. package/dist/assets/7a893d1eb7679380.woff +0 -0
  54. package/dist/assets/7a99187126461071.woff +0 -0
  55. package/dist/assets/7d6d8a6f02c4c1aa.woff +0 -0
  56. package/dist/assets/7f7357dc812eefda.woff +0 -0
  57. package/dist/assets/871c3ceece4e3cd9.woff +0 -0
  58. package/dist/assets/87f3dff3547b0909.woff2 +0 -0
  59. package/dist/assets/87f95ed67632b03b.woff2 +0 -0
  60. package/dist/assets/89d075654f06f10c.woff2 +0 -0
  61. package/dist/assets/8c4d36f4ee8e7c52.woff +0 -0
  62. package/dist/assets/8cfbfbd3d549aa8f.woff2 +0 -0
  63. package/dist/assets/901509487406193c.woff +0 -0
  64. package/dist/assets/937a484c67327d90.woff +0 -0
  65. package/dist/assets/9999b0f2b2092b76.woff +0 -0
  66. package/dist/assets/99acac18e078b66e.woff +0 -0
  67. package/dist/assets/99ad1c88b9cdd54d.woff2 +0 -0
  68. package/dist/assets/99df3ad791ebae4d.woff +0 -0
  69. package/dist/assets/9bcd290ba4712876.woff2 +0 -0
  70. package/dist/assets/9f7ce8788b3a2feb.woff +0 -0
  71. package/dist/assets/a09ffd2fa9db2b77.woff2 +0 -0
  72. package/dist/assets/a11e030888b0c74d.woff2 +0 -0
  73. package/dist/assets/a221c5c63b0b007f.woff2 +0 -0
  74. package/dist/assets/a2b67360075a3845.woff2 +0 -0
  75. package/dist/assets/a995d3bd798f6af6.woff +0 -0
  76. package/dist/assets/a9a8664294faf616.woff2 +0 -0
  77. package/dist/assets/ac778417aa085869.png +0 -0
  78. package/dist/assets/af1dafcfb9d93cb7.ttf +0 -0
  79. package/dist/assets/b6f749506db82948.woff2 +0 -0
  80. package/dist/assets/b83e01be56fee57a.woff2 +0 -0
  81. package/dist/assets/bb96a486b115a27e.woff2 +0 -0
  82. package/dist/assets/bd6455e315f82d54.woff +0 -0
  83. package/dist/assets/c0cd43646bf5bc8e.woff2 +0 -0
  84. package/dist/assets/c8c031dea2283941.woff2 +0 -0
  85. package/dist/assets/c8de52c3f3327f69.woff +0 -0
  86. package/dist/assets/cb4e4e5d92737be1.woff2 +0 -0
  87. package/dist/assets/cc800fd19d5badfe.woff2 +0 -0
  88. package/dist/assets/d3306554cd238326.woff2 +0 -0
  89. package/dist/assets/d697bdae42ff838a.woff2 +0 -0
  90. package/dist/assets/d89041b1647c76f8.woff2 +0 -0
  91. package/dist/assets/dade5e8991a4748b.woff +0 -0
  92. package/dist/assets/db49dd71ad0fd177.woff2 +0 -0
  93. package/dist/assets/deaeec314b032fd9.woff +0 -0
  94. package/dist/assets/df18386e29f35837.ttf +0 -0
  95. package/dist/assets/e14b7a3b443b8c88.woff +0 -0
  96. package/dist/assets/e4cd99ec6cee4d80.woff +0 -0
  97. package/dist/assets/e6648178fa173da7.woff +0 -0
  98. package/dist/assets/e81332fec9311063.woff2 +0 -0
  99. package/dist/assets/ef28e132822430d7.woff +0 -0
  100. package/dist/assets/f2d64f400f75f079.woff +0 -0
  101. package/dist/assets/f6e1854c7f798a3a.woff +0 -0
  102. package/dist/assets/f7589cf6b9bf4073.woff +0 -0
  103. package/dist/assets/f87c7e0970223449.woff2 +0 -0
  104. package/dist/backend/cli.mjs +3586 -0
  105. package/dist/favicon.png +0 -0
  106. package/dist/index.html +12 -0
  107. package/dist/main.css +2 -0
  108. package/dist/main.js +152 -0
  109. package/dist/mcp-page-client.js +13 -0
  110. package/dist/mcp-page-console.js +2 -0
  111. package/dist/runtime.405c167245800bcf.hot-update.js +9 -0
  112. package/dist/runtime.js +1285 -0
  113. package/package.json +98 -0
  114. package/src/shared/modes.mjs +319 -0
  115. package/src/shared/modes.spec.js +87 -0
  116. package/src/shared/modes.spec.mjs +95 -0
  117. package/src/shared/tabs.mjs +7 -0
@@ -0,0 +1,3586 @@
1
+ #!/usr/bin/env node
2
+ import * as __rspack_external_commander from "commander";
3
+ import * as __rspack_external_consola from "consola";
4
+ import * as __rspack_external_dedent_js_f320a911 from "dedent-js";
5
+ import * as __rspack_external_fs_extra_esm_b7f62bda from "fs-extra/esm";
6
+ import * as __rspack_external_handle_cli_error_4370b838 from "handle-cli-error";
7
+ import * as __rspack_external_zod from "zod";
8
+ import { createRequire as __rspack_createRequire } from "node:module";
9
+ const __rspack_createRequire_require = __rspack_createRequire(import.meta.url);
10
+ import * as __rspack_external_fastify from "fastify";
11
+ import * as __rspack_external__fastify_cors_424bc224 from "@fastify/cors";
12
+ import * as __rspack_external_portscanner from "portscanner";
13
+ import * as __rspack_external_fast_glob_bdd2f626 from "fast-glob";
14
+ import * as __rspack_external__fastify_static_a76d2a9e from "@fastify/static";
15
+ import * as __rspack_external_yamljs from "yamljs";
16
+ import * as __rspack_external__fastify_websocket_ea21246a from "@fastify/websocket";
17
+ import * as __rspack_external__modelcontextprotocol_sdk_server_mcp_js_f5d3ff69 from "@modelcontextprotocol/sdk/server/mcp.js";
18
+ import * as __rspack_external__modelcontextprotocol_sdk_server_streamableHttp_js_7ca5b80f from "@modelcontextprotocol/sdk/server/streamableHttp.js";
19
+ var __webpack_modules__ = ({
20
+ 444(module) {
21
+
22
+ module.exports = __rspack_external_commander;
23
+
24
+
25
+ },
26
+ 691(module) {
27
+
28
+ module.exports = __rspack_external_consola;
29
+
30
+
31
+ },
32
+ 868(module) {
33
+
34
+ module.exports = __rspack_external_dedent_js_f320a911;
35
+
36
+
37
+ },
38
+ 674(module) {
39
+
40
+ module.exports = __rspack_external_fs_extra_esm_b7f62bda;
41
+
42
+
43
+ },
44
+ 648(module) {
45
+
46
+ module.exports = __rspack_external_handle_cli_error_4370b838;
47
+
48
+
49
+ },
50
+ 971(module) {
51
+
52
+ module.exports = __rspack_external_zod;
53
+
54
+
55
+ },
56
+ 943(module) {
57
+ module.exports = __rspack_createRequire_require("fs/promises");
58
+
59
+ },
60
+ 24(module) {
61
+ module.exports = __rspack_createRequire_require("node:fs");
62
+
63
+ },
64
+ 455(module) {
65
+ module.exports = __rspack_createRequire_require("node:fs/promises");
66
+
67
+ },
68
+ 760(module) {
69
+ module.exports = __rspack_createRequire_require("node:path");
70
+
71
+ },
72
+ 136(module) {
73
+ module.exports = __rspack_createRequire_require("node:url");
74
+
75
+ },
76
+ 928(module) {
77
+ module.exports = __rspack_createRequire_require("path");
78
+
79
+ },
80
+ 331(__webpack_module__, __unused_rspack___webpack_exports__, __webpack_require__) {
81
+ __webpack_require__.a(__webpack_module__, async function (__rspack_load_async_deps, __rspack_async_done) { try {
82
+ /* import */ var consola__rspack_import_0 = __webpack_require__(691);
83
+ /* import */ var commander__rspack_import_1 = __webpack_require__(444);
84
+ /* import */ var fs_extra_esm__rspack_import_2 = __webpack_require__(674);
85
+ /* import */ var path__rspack_import_3 = __webpack_require__(928);
86
+ /* import */ var _server_mjs__rspack_import_4 = __webpack_require__(360);
87
+ /* import */ var _mcp_stdio_proxy_mjs__rspack_import_5 = __webpack_require__(690);
88
+ /* import */ var handle_cli_error__rspack_import_6 = __webpack_require__(648);
89
+ /* import */ var _cli_feeds_index_mjs__rspack_import_7 = __webpack_require__(377);
90
+ /* import */ var _utils_get_port_by_name_mjs__rspack_import_10 = __webpack_require__(351);
91
+ /* import */ var _utils_stale_bundle_mjs__rspack_import_8 = __webpack_require__(721);
92
+ /* import */ var _utils_package_root_mjs__rspack_import_9 = __webpack_require__(560);
93
+ //#!/usr/bin/env node
94
+
95
+
96
+
97
+
98
+
99
+
100
+
101
+
102
+
103
+
104
+
105
+
106
+ commander__rspack_import_1.program.name("livepreso-cdk");
107
+
108
+ const PACKAGE_ROOT = (0,_utils_package_root_mjs__rspack_import_9/* .findPackageRoot */.C)(import.meta.url);
109
+
110
+ /** Says so when the UI being served was built before the last change to it. */
111
+ async function reportStaleBundle() {
112
+ const stale = await (0,_utils_stale_bundle_mjs__rspack_import_8/* .findStaleBundle */.H)(
113
+ path__rspack_import_3.join(PACKAGE_ROOT, "dist"),
114
+ path__rspack_import_3.join(PACKAGE_ROOT, "src/frontend"),
115
+ );
116
+
117
+ if (!stale) {
118
+ return;
119
+ }
120
+
121
+ consola__rspack_import_0["default"].warn(
122
+ `The CDK interface was built ${describeAge(stale.builtAt)}, and its source has changed since.
123
+ This command serves what was built and does not rebuild it, so those changes are not on screen.
124
+ Run \`rushx serve\` in apps/cdk2 to rebuild it.`,
125
+ );
126
+ }
127
+
128
+ function describeAge(builtAt) {
129
+ const minutes = Math.round((Date.now() - builtAt) / 60000);
130
+
131
+ if (minutes < 60) {
132
+ return `${minutes} minutes ago`;
133
+ }
134
+
135
+ const hours = Math.round(minutes / 60);
136
+
137
+ return hours < 24
138
+ ? `${hours} hours ago`
139
+ : `${Math.round(hours / 24)} days ago`;
140
+ }
141
+
142
+ commander__rspack_import_1.program.command("dev")
143
+ .summary("start the development server")
144
+ .option("-p --port <number>", "Set a port", 0)
145
+ // Get rid of this... use the current directory cli is run in I reckon
146
+ .argument("dir", "project directory")
147
+ .action(async (projectDir, options) => {
148
+ const resolvedProjectDir = path__rspack_import_3.resolve(projectDir);
149
+ const distPath = path__rspack_import_3.join(resolvedProjectDir, "dist");
150
+ const pkg = await (0,fs_extra_esm__rspack_import_2.readJson)(path__rspack_import_3.join(resolvedProjectDir, "package.json"));
151
+ const port = options.port || (0,_utils_get_port_by_name_mjs__rspack_import_10/* .getPortByName */.u)(pkg.name);
152
+
153
+ await reportStaleBundle();
154
+
155
+ (0,_server_mjs__rspack_import_4/* ["default"] */.A)({ projectDir: resolvedProjectDir, distDir: distPath, port });
156
+ });
157
+
158
+ commander__rspack_import_1.program.command("mcp")
159
+ .summary("Start an MCP server an AI tool can connect to")
160
+ .option("-d --project-dir <path>", "deck to connect to, defaults to cwd")
161
+ .action((options) => (0,_mcp_stdio_proxy_mjs__rspack_import_5/* .runStdioMcpProxy */.R)({ projectDir: options.projectDir }));
162
+
163
+ const feed = commander__rspack_import_1.program.command("feed")
164
+ .summary("Subcommand for dealing with feeds");
165
+
166
+ feed
167
+ .command("add")
168
+ .summary("create separate fixtures from one feed")
169
+ .argument("[file]", "Inject from a filepath")
170
+ .requiredOption(
171
+ "--name <string>",
172
+ "name of the file to create (without the .json extension)",
173
+ )
174
+ .option("--force", "If a file already exists, overwrite it.")
175
+ .option("--dry-run", "Don't alter the filesystem, useful for debugging")
176
+ .action((fromFile, { name, ...options }) => {
177
+ return _cli_feeds_index_mjs__rspack_import_7/* .createFromFile */.t(fromFile, name, options);
178
+ });
179
+
180
+ try {
181
+ await commander__rspack_import_1.program.parseAsync();
182
+ } catch (e) {
183
+ // Pretty prints error exceptions
184
+ (0,handle_cli_error__rspack_import_6["default"])(e, {
185
+ stack: false,
186
+ classes: {
187
+ SyntaxError: { stack: true },
188
+ TypeError: { stack: true },
189
+ },
190
+ });
191
+ }
192
+
193
+ __rspack_async_done();
194
+ } catch(e) { __rspack_async_done(e); } }, 1);
195
+
196
+ },
197
+ 377(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) {
198
+
199
+ // EXPORTS
200
+ __webpack_require__.d(__webpack_exports__, {
201
+ t: () => (/* reexport */ createFromFile)
202
+ });
203
+
204
+ // EXTERNAL MODULE: external "path"
205
+ var external_path_ = __webpack_require__(928);
206
+ // EXTERNAL MODULE: external "fs/promises"
207
+ var promises_ = __webpack_require__(943);
208
+ // EXTERNAL MODULE: external "consola"
209
+ var external_consola_ = __webpack_require__(691);
210
+ // EXTERNAL MODULE: external "fs-extra/esm"
211
+ var esm_ = __webpack_require__(674);
212
+ // EXTERNAL MODULE: ./src/backend/utils/fs.mjs
213
+ var fs = __webpack_require__(488);
214
+ ;// CONCATENATED MODULE: ./src/backend/utils/is-project-directory.mjs
215
+
216
+
217
+
218
+ function isProjectDirectory(dir) {
219
+ // If we find any of these files in the root, we can assume it's a
220
+ // project.
221
+ const projectFiles = ["project.json", "project.yaml", "project.js"];
222
+
223
+ for (const projectFile of projectFiles) {
224
+ const fullPath = external_path_.join(dir, projectFile)
225
+ if ((0,fs/* .pathExists */.s)(fullPath)) {
226
+ return true;
227
+ }
228
+ }
229
+
230
+ return false;
231
+ }
232
+
233
+ ;// CONCATENATED MODULE: ./src/backend/errors.mjs
234
+ /**
235
+ * Tried to look up a file but it wasn't there
236
+ */
237
+ class FileNotFoundError extends Error {}
238
+
239
+ /**
240
+ * We're in a directory that isn't a project
241
+ */
242
+ class ProjectNotFoundError extends Error {}
243
+
244
+ /**
245
+ * We tried to create a file here but it already exists
246
+ */
247
+ class FileAlreadyExistsError extends Error {}
248
+
249
+ ;// CONCATENATED MODULE: ./src/backend/cli/feeds/add.mjs
250
+
251
+
252
+
253
+
254
+
255
+
256
+
257
+
258
+ function logInfo(message, isDryRun) {
259
+ external_consola_["default"].info(isDryRun ? `DRYRUN: ${message}` : message);
260
+ }
261
+
262
+ async function createFromFile(filePath, name, options = {}) {
263
+ const { force = false, dryRun = false } = options;
264
+
265
+ if (!isProjectDirectory(process.cwd())) {
266
+ throw new ProjectNotFoundError("Not a project");
267
+ }
268
+
269
+ if (!(0,fs/* .pathExists */.s)(filePath)) {
270
+ throw new FileNotFoundError(`File ${filePath} not found`);
271
+ }
272
+
273
+ const file = await promises_.readFile(filePath, "utf8");
274
+
275
+ const parsedJson = JSON.parse(file);
276
+
277
+ const cdkFeedsDirPath = external_path_.join(process.cwd(), ".cdk/feeds");
278
+
279
+ const entries = [];
280
+
281
+ for (const [key, obj] of Object.entries(parsedJson)) {
282
+ const newFilePath = external_path_.join(cdkFeedsDirPath, key, `${name}.json`);
283
+
284
+ if ((0,fs/* .pathExists */.s)(newFilePath) && !force) {
285
+ throw new FileAlreadyExistsError(
286
+ `Was going to create file ${newFilePath}, but it already exists. Use --force to do it anyway.`,
287
+ );
288
+ }
289
+
290
+ entries.push([newFilePath, obj]);
291
+ }
292
+
293
+ for (const [filePath, obj] of entries) {
294
+ const dir = external_path_.dirname(filePath);
295
+ if (!(0,fs/* .pathExists */.s)(dir)) {
296
+ logInfo(
297
+ `Creating directory ${external_path_.relative(process.cwd(), dir)}`,
298
+ dryRun,
299
+ );
300
+ if (!dryRun) {
301
+ await (0,esm_.mkdirp)(dir);
302
+ }
303
+ }
304
+
305
+ logInfo(`Creating file ${external_path_.relative(process.cwd(), filePath)}`, dryRun);
306
+ if (!dryRun) {
307
+ await promises_.writeFile(filePath, JSON.stringify(obj, null, 2) + "\n");
308
+ }
309
+ }
310
+
311
+ external_consola_["default"].success("Done!");
312
+ }
313
+
314
+ ;// CONCATENATED MODULE: ./src/backend/cli/feeds/index.mjs
315
+
316
+
317
+
318
+ },
319
+ 614(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) {
320
+
321
+ // EXPORTS
322
+ __webpack_require__.d(__webpack_exports__, {
323
+ O: () => (/* binding */ MCP_SERVER_INFO),
324
+ createMcpServer: () => (/* binding */ createMcpServer)
325
+ });
326
+
327
+ ;// CONCATENATED MODULE: external "@modelcontextprotocol/sdk/server/mcp.js"
328
+
329
+ // EXTERNAL MODULE: ./src/backend/mcp/tools/helpers.mjs
330
+ var helpers = __webpack_require__(903);
331
+ // EXTERNAL MODULE: ./src/backend/mcp/tools/index.mjs + 14 modules
332
+ var tools = __webpack_require__(532);
333
+ // EXTERNAL MODULE: external "node:fs"
334
+ var external_node_fs_ = __webpack_require__(24);
335
+ // EXTERNAL MODULE: external "node:path"
336
+ var external_node_path_ = __webpack_require__(760);
337
+ // EXTERNAL MODULE: external "node:url"
338
+ var external_node_url_ = __webpack_require__(136);
339
+ // EXTERNAL MODULE: ./src/backend/utils/package-root.mjs
340
+ var package_root = __webpack_require__(560);
341
+ ;// CONCATENATED MODULE: ./src/backend/mcp/read-modes.mjs
342
+
343
+
344
+
345
+
346
+
347
+
348
+ const MODES_PATH = external_node_path_.join(
349
+ (0,package_root/* .findPackageRoot */.C)(import.meta.url),
350
+ "src/shared/modes.mjs",
351
+ );
352
+
353
+ /**
354
+ * The mode tree as it is on disk now.
355
+ *
356
+ * Node holds the copy this process imported at startup, and a mode added since
357
+ * then would be refused as unknown. The stamp is the file's mtime, so an
358
+ * unchanged file costs one import.
359
+ */
360
+ async function readModes() {
361
+ const stamp = (0,external_node_fs_.statSync)(MODES_PATH).mtimeMs;
362
+
363
+ // Left to Node: the bundler would otherwise fold the file into the bundle,
364
+ // and the point is to read the copy on disk.
365
+ return import(
366
+ /* webpackIgnore: true */ `${(0,external_node_url_.pathToFileURL)(MODES_PATH).href}?stamp=${stamp}`
367
+ );
368
+ }
369
+
370
+ ;// CONCATENATED MODULE: ./src/backend/mcp/mcp-server.mjs
371
+
372
+
373
+
374
+
375
+
376
+ const SERVER_NAME = "cdk";
377
+ const SERVER_VERSION = "0.1.0";
378
+
379
+ async function createMcpServer({
380
+ pages,
381
+ projectDir,
382
+ distDir,
383
+ log,
384
+ } = {}) {
385
+ const server = new __rspack_external__modelcontextprotocol_sdk_server_mcp_js_f5d3ff69.McpServer(
386
+ { name: SERVER_NAME, version: SERVER_VERSION },
387
+ { capabilities: { tools: {} } },
388
+ );
389
+
390
+ // `set_mode` carries the mode paths in its schema, so a mode added while the
391
+ // dev server runs is refused by the client unless this request reads it.
392
+ const modes = await readModes();
393
+
394
+ (0,helpers/* .registerTools */.Fd)(server, (0,tools/* .allTools */.X)({ pages, projectDir, distDir, modes }), {
395
+ log,
396
+ announce: (kind, payload) => pages.announce(kind, payload),
397
+ });
398
+
399
+ return server;
400
+ }
401
+
402
+ const MCP_SERVER_INFO = Object.freeze({
403
+ name: SERVER_NAME,
404
+ version: SERVER_VERSION,
405
+ });
406
+
407
+
408
+ },
409
+ 690(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) {
410
+
411
+ // EXPORTS
412
+ __webpack_require__.d(__webpack_exports__, {
413
+ R: () => (/* binding */ runStdioMcpProxy)
414
+ });
415
+
416
+ // EXTERNAL MODULE: external "node:path"
417
+ var external_node_path_ = __webpack_require__(760);
418
+ // EXTERNAL MODULE: external "node:fs/promises"
419
+ var promises_ = __webpack_require__(455);
420
+ ;// CONCATENATED MODULE: external "node:readline"
421
+ const external_node_readline_namespaceObject = __rspack_createRequire_require("node:readline");
422
+ // EXTERNAL MODULE: external "dedent-js"
423
+ var external_dedent_js_ = __webpack_require__(868);
424
+ // EXTERNAL MODULE: external "zod"
425
+ var external_zod_ = __webpack_require__(971);
426
+ // EXTERNAL MODULE: ./src/backend/utils/get-port-by-name.mjs
427
+ var get_port_by_name = __webpack_require__(351);
428
+ // EXTERNAL MODULE: ./src/backend/mcp/tools/helpers.mjs
429
+ var helpers = __webpack_require__(903);
430
+ // EXTERNAL MODULE: ./src/backend/mcp/tools/index.mjs + 14 modules
431
+ var tools = __webpack_require__(532);
432
+ // EXTERNAL MODULE: ./src/backend/mcp/mcp-server.mjs + 2 modules
433
+ var mcp_server = __webpack_require__(614);
434
+ ;// CONCATENATED MODULE: ./src/backend/mcp/stdio-proxy.mjs
435
+
436
+
437
+
438
+
439
+
440
+
441
+
442
+
443
+
444
+
445
+
446
+ const MCP_PATH = "/server/api/mcp";
447
+ const PROTOCOL_VERSION = "2025-06-18";
448
+ const NO_PROJECT_MESSAGE =
449
+ "No project connected; call `connect_to_project` first.";
450
+
451
+ const CONNECT_TOOL = {
452
+ name: "connect_to_project",
453
+ description: (0,external_dedent_js_["default"])`
454
+ Connect to a deck's running cdk dev server so the other tools can read and
455
+ control it. Call this first.
456
+ `,
457
+ schema: external_zod_.z.object({
458
+ project_dir: external_zod_.z.string()
459
+ .describe("Absolute path to the deck (a directory with a package.json)."),
460
+ }),
461
+ };
462
+
463
+ // Advertised whether or not a project is connected, so the model can see what
464
+ // it will be able to do; each one answers with NO_PROJECT_MESSAGE until
465
+ // connect_to_project succeeds.
466
+ const TOOLS = (0,helpers/* .toolDescriptors */.jE)([CONNECT_TOOL, ...(0,tools/* .allTools */.X)()]);
467
+
468
+ const session = { projectDir: null, devUrl: null };
469
+
470
+ function getErrorMessage(error) {
471
+ return error instanceof Error ? error.message : String(error);
472
+ }
473
+
474
+ function write(message) {
475
+ process.stdout.write(`${JSON.stringify(message)}\n`);
476
+ }
477
+
478
+ function writeError(id, code, message) {
479
+ write({ jsonrpc: "2.0", id, error: { code, message } });
480
+ }
481
+
482
+ /**
483
+ * Points the session at the deck in `projectDir`. The dev server's port is
484
+ * derived from the package name with the same function the dev server itself
485
+ * uses, so the two always agree without anything being written down.
486
+ */
487
+ async function connectToProject(projectDir) {
488
+ const resolved = external_node_path_.resolve(projectDir);
489
+ const stats = await (0,promises_.stat)(resolved).catch((error) => {
490
+ throw new Error(`Cannot read ${resolved}: ${getErrorMessage(error)}`);
491
+ });
492
+
493
+ if (!stats.isDirectory()) {
494
+ throw new Error(`Not a directory: ${resolved}`);
495
+ }
496
+
497
+ const manifest = await (0,promises_.readFile)(external_node_path_.join(resolved, "package.json"), "utf8")
498
+ .then(JSON.parse)
499
+ .catch((error) => {
500
+ throw new Error(
501
+ `Cannot read package.json in ${resolved}: ${getErrorMessage(error)}`,
502
+ );
503
+ });
504
+
505
+ if (!manifest.name) {
506
+ throw new Error(`package.json in ${resolved} has no "name"`);
507
+ }
508
+
509
+ const devUrl = `http://localhost:${(0,get_port_by_name/* .getPortByName */.u)(manifest.name)}`;
510
+
511
+ // Checked before the session is pointed anywhere, so a failed connect leaves
512
+ // the previous one intact.
513
+ await requireDevServer(devUrl, resolved);
514
+
515
+ session.projectDir = resolved;
516
+ session.devUrl = devUrl;
517
+
518
+ return { projectDir: session.projectDir, devUrl: session.devUrl };
519
+ }
520
+
521
+ const REACHABLE_TIMEOUT_MS = 2000;
522
+
523
+ /**
524
+ * Throws where nothing is listening on the deck's port.
525
+ *
526
+ * Any HTTP status counts, a 404 included: all this establishes is that there is
527
+ * something there to forward to.
528
+ */
529
+ async function requireDevServer(devUrl, projectDir) {
530
+ try {
531
+ await fetch(devUrl, { signal: AbortSignal.timeout(REACHABLE_TIMEOUT_MS) });
532
+ } catch (error) {
533
+ throw new Error((0,external_dedent_js_["default"])`
534
+ No cdk dev server at ${devUrl}: ${getErrorMessage(error)}.
535
+ Start one with: livepreso-cdk dev ${projectDir}
536
+ `);
537
+ }
538
+ }
539
+
540
+ /**
541
+ * Pulls the JSON-RPC payloads out of a streamable-HTTP response, which the SDK
542
+ * frames as server-sent events even for a single reply.
543
+ */
544
+ function readEvents(body) {
545
+ const events = [];
546
+ let dataLines = [];
547
+
548
+ for (const rawLine of body.split("\n")) {
549
+ const line = rawLine.replace(/\r$/, "");
550
+
551
+ if (line.startsWith("data:")) {
552
+ dataLines.push(line.slice(5).trimStart());
553
+ } else if (line === "" && dataLines.length > 0) {
554
+ events.push(dataLines.join("\n"));
555
+ dataLines = [];
556
+ }
557
+ }
558
+
559
+ if (dataLines.length > 0) {
560
+ events.push(dataLines.join("\n"));
561
+ }
562
+
563
+ if (events.length === 0 && body.trim().startsWith("{")) {
564
+ events.push(body.trim());
565
+ }
566
+
567
+ return events;
568
+ }
569
+
570
+ function post(devUrl, body) {
571
+ return fetch(new URL(MCP_PATH, devUrl).href, {
572
+ method: "POST",
573
+ headers: {
574
+ "Content-Type": "application/json",
575
+ Accept: "application/json, text/event-stream",
576
+ },
577
+ body,
578
+ });
579
+ }
580
+
581
+ /**
582
+ * Answers with the dev server's own tool list where it can, so a tool added to
583
+ * a running dev server shows up without restarting this process, and falls
584
+ * back to the built-in descriptors for anything it did not report.
585
+ */
586
+ async function listTools(devUrl, requestBody) {
587
+ if (!devUrl) {
588
+ return TOOLS;
589
+ }
590
+
591
+ let live = [];
592
+
593
+ try {
594
+ const response = await post(devUrl, requestBody);
595
+
596
+ for (const event of readEvents(await response.text())) {
597
+ const message = JSON.parse(event);
598
+ if (Array.isArray(message.result?.tools)) {
599
+ live = message.result.tools;
600
+ break;
601
+ }
602
+ }
603
+ } catch {
604
+ // Dev server unreachable - the built-in list still tells the model what
605
+ // exists, and each call will explain that nothing is connected.
606
+ }
607
+
608
+ const names = new Set(live.map((tool) => tool.name));
609
+
610
+ return [...live, ...TOOLS.filter((tool) => !names.has(tool.name))];
611
+ }
612
+
613
+ async function handleConnect(id, args) {
614
+ if (!args?.project_dir?.trim()) {
615
+ writeError(id, -32602, "connect_to_project: project_dir (string) required");
616
+ return;
617
+ }
618
+
619
+ try {
620
+ const connection = await connectToProject(args.project_dir);
621
+
622
+ write({
623
+ jsonrpc: "2.0",
624
+ id,
625
+ result: {
626
+ content: [{ type: "text", text: JSON.stringify(connection) }],
627
+ },
628
+ });
629
+ write({ jsonrpc: "2.0", method: "notifications/tools/list_changed" });
630
+ } catch (error) {
631
+ writeError(id, -32000, getErrorMessage(error));
632
+ }
633
+ }
634
+
635
+ async function forward({ id, line, isRequest }) {
636
+ let response;
637
+
638
+ try {
639
+ response = await post(session.devUrl, line);
640
+ } catch (error) {
641
+ if (isRequest) {
642
+ writeError(
643
+ id,
644
+ -32000,
645
+ `cdk dev not reachable at ${session.devUrl}: ${getErrorMessage(error)}`,
646
+ );
647
+ }
648
+ return;
649
+ }
650
+
651
+ const events = readEvents(await response.text());
652
+
653
+ // A notification is answered with 202 and an empty body, which is not
654
+ // something to report back - and a notification must never be replied to.
655
+ if (events.length === 0) {
656
+ if (isRequest) {
657
+ writeError(
658
+ id,
659
+ -32000,
660
+ `cdk dev returned HTTP ${response.status} with no JSON-RPC payload`,
661
+ );
662
+ }
663
+ return;
664
+ }
665
+
666
+ for (const event of events) {
667
+ process.stdout.write(`${event}\n`);
668
+ }
669
+ }
670
+
671
+ /**
672
+ * A deck directory is one with a package.json and a src directory, which is
673
+ * what makes `cdk mcp` started from a deck connect to it without being asked.
674
+ */
675
+ async function isProjectDirectory(dir) {
676
+ return (0,promises_.stat)(external_node_path_.join(dir, "src"))
677
+ .then((stats) => stats.isDirectory())
678
+ .catch(() => false);
679
+ }
680
+
681
+ /**
682
+ * Speaks MCP over stdin/stdout, handling the session-management tool itself
683
+ * and forwarding everything else to the connected deck's dev server. It stays
684
+ * running across dev server restarts, so the editor keeps one connection while
685
+ * the deck it is pointed at comes and goes.
686
+ */
687
+ async function runStdioMcpProxy({ projectDir } = {}) {
688
+ const initial = projectDir ?? process.cwd();
689
+
690
+ if (projectDir || (await isProjectDirectory(initial))) {
691
+ await connectToProject(initial).catch((error) => {
692
+ process.stderr.write(`cdk mcp: ${getErrorMessage(error)}\n`);
693
+ });
694
+ }
695
+
696
+ const lines = (0,external_node_readline_namespaceObject.createInterface)({ input: process.stdin, crlfDelay: Infinity });
697
+ const close = () => lines.close();
698
+
699
+ process.once("SIGINT", close);
700
+ process.once("SIGTERM", close);
701
+
702
+ try {
703
+ for await (const line of lines) {
704
+ const trimmed = line.trim();
705
+ if (!trimmed) {
706
+ continue;
707
+ }
708
+
709
+ let message;
710
+ try {
711
+ message = JSON.parse(trimmed);
712
+ } catch {
713
+ continue;
714
+ }
715
+
716
+ const id = message.id ?? null;
717
+ // A notification has no id, and must never be answered.
718
+ const isRequest = Object.hasOwn(message, "id");
719
+
720
+ if (message.method === "initialize") {
721
+ write({
722
+ jsonrpc: "2.0",
723
+ id,
724
+ result: {
725
+ protocolVersion:
726
+ message.params?.protocolVersion ?? PROTOCOL_VERSION,
727
+ capabilities: { tools: { listChanged: true } },
728
+ serverInfo: mcp_server/* .MCP_SERVER_INFO */.O,
729
+ },
730
+ });
731
+ continue;
732
+ }
733
+
734
+ if (message.params?.name === CONNECT_TOOL.name) {
735
+ if (isRequest) {
736
+ await handleConnect(id, message.params?.arguments);
737
+ }
738
+ continue;
739
+ }
740
+
741
+ if (message.method === "tools/list" && isRequest) {
742
+ write({
743
+ jsonrpc: "2.0",
744
+ id,
745
+ result: { tools: await listTools(session.devUrl, trimmed) },
746
+ });
747
+ continue;
748
+ }
749
+
750
+ if (!session.devUrl) {
751
+ if (isRequest) {
752
+ writeError(id, -32000, NO_PROJECT_MESSAGE);
753
+ }
754
+ continue;
755
+ }
756
+
757
+ await forward({ id, line: trimmed, isRequest });
758
+ }
759
+ } finally {
760
+ process.removeListener("SIGINT", close);
761
+ process.removeListener("SIGTERM", close);
762
+ }
763
+ }
764
+
765
+
766
+ },
767
+ 903(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) {
768
+ /* import */ var dedent_js__rspack_import_0 = __webpack_require__(868);
769
+ /* import */ var zod__rspack_import_1 = __webpack_require__(971);
770
+
771
+
772
+
773
+ const browserIdSchema = zod__rspack_import_1.z.string()
774
+ .describe(
775
+ (0,dedent_js__rspack_import_0["default"])`
776
+ Which connected browser to talk to. Optional when only one is open; use
777
+ list_browsers to see the ids.
778
+ `,
779
+ )
780
+ .optional();
781
+
782
+ /**
783
+ * Renders a tool call's input as the parens payload of `<name> called(...)`.
784
+ * Objects and arrays go through JSON.stringify so a deep value cannot blow up
785
+ * the log line.
786
+ */
787
+ function formatToolArgs(input) {
788
+ if (!input || typeof input !== "object") {
789
+ return "";
790
+ }
791
+
792
+ return Object.entries(input)
793
+ .filter(([, value]) => value !== undefined)
794
+ .map(([key, value]) => {
795
+ if (typeof value === "string") {
796
+ return `${key}="${value}"`;
797
+ }
798
+ if (value === null || typeof value !== "object") {
799
+ return `${key}=${value}`;
800
+ }
801
+ return `${key}=${JSON.stringify(value)}`;
802
+ })
803
+ .join(", ");
804
+ }
805
+
806
+ /**
807
+ * Registers each tool with the MCP server. Handlers return a plain value and
808
+ * throw a plain Error; this turns the value into a tool result, turns the
809
+ * error into a message the model can read rather than a transport failure,
810
+ * and announces every call to the dev server's log, the MCP client and the
811
+ * console of every open deck.
812
+ *
813
+ * Handles both SDK dispatch shapes - `(args, extra)` for tools with an input
814
+ * schema and `(extra)` for tools without one - by sniffing `arguments.length`.
815
+ */
816
+ function registerTools(server, tools, { log, announce }) {
817
+ for (const { name, description, schema, handler } of tools) {
818
+ server.registerTool(
819
+ name,
820
+ { description, inputSchema: schema },
821
+ async (...args) => {
822
+ const extra = args.length >= 2 ? args[1] : args[0];
823
+ const input = (args.length >= 2 ? args[0] : {}) ?? {};
824
+ const called = `${name}(${formatToolArgs(input)})`;
825
+
826
+ log?.info(called);
827
+ announce?.("call", { text: called });
828
+
829
+ // Fire and forget: a slow or dropped notification must not hold
830
+ // up the tool result.
831
+ extra
832
+ ?.sendNotification?.({
833
+ method: "notifications/message",
834
+ params: { level: "info", logger: "mcp", data: called },
835
+ })
836
+ .catch(() => {});
837
+
838
+ try {
839
+ const value = await handler(input, extra);
840
+
841
+ announce?.("result", { value });
842
+
843
+ return {
844
+ content: [{ type: "text", text: JSON.stringify(value) }],
845
+ };
846
+ } catch (error) {
847
+ const message =
848
+ error instanceof Error ? error.message : String(error);
849
+
850
+ announce?.("error", { text: message });
851
+
852
+ return {
853
+ content: [{ type: "text", text: message }],
854
+ isError: true,
855
+ };
856
+ }
857
+ },
858
+ );
859
+ }
860
+ }
861
+
862
+ /**
863
+ * Projects the tool definitions to the `tools/list` shape, so the stdio proxy
864
+ * advertises exactly what the dev server validates.
865
+ */
866
+ function toolDescriptors(tools) {
867
+ return tools.map(({ name, description, schema }) => {
868
+ const inputSchema = zod__rspack_import_1.z.toJSONSchema(schema, { io: "input" });
869
+
870
+ // The MCP SDK ships a real inputSchema only for object schemas.
871
+ // Anything else - a union, an optional-wrapped object - is replaced
872
+ // with an empty schema in tools/list, and the model then sees a tool it
873
+ // has no way to call. Use `z.object({...}).refine(...)` for a payload
874
+ // with variants.
875
+ if (inputSchema.type !== "object") {
876
+ throw new Error(
877
+ `Tool "${name}" inputSchema must be a z.object, got ` +
878
+ `${inputSchema.type ?? Object.keys(inputSchema).join("/")}.`,
879
+ );
880
+ }
881
+
882
+ return {
883
+ name,
884
+ description,
885
+ inputSchema: { properties: {}, ...inputSchema },
886
+ };
887
+ });
888
+ }
889
+
890
+ __webpack_require__.d(__webpack_exports__, {
891
+ Fd: () => (registerTools),
892
+ jE: () => (toolDescriptors)
893
+ }, {
894
+ NW: browserIdSchema
895
+ });
896
+
897
+
898
+ },
899
+ 532(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) {
900
+
901
+ // EXPORTS
902
+ __webpack_require__.d(__webpack_exports__, {
903
+ X: () => (/* binding */ allTools)
904
+ });
905
+ // NAMESPACE OBJECT: ./src/shared/modes.mjs
906
+ var modes_namespaceObject = {};
907
+ __webpack_require__.r(modes_namespaceObject);
908
+ __webpack_require__.d(modes_namespaceObject, {
909
+ CMS_VALS: () => (CMS_VALS),
910
+ CONTEXT_OVERRIDES: () => (CONTEXT_OVERRIDES),
911
+ MODES: () => (modes_MODES),
912
+ PRESENT_STATES: () => (PRESENT_STATES),
913
+ TEMPLATE_CONTEXT: () => (TEMPLATE_CONTEXT),
914
+ findModeByIndices: () => (findModeByIndices),
915
+ findModeByPath: () => (modes_findModeByPath),
916
+ findModesForTab: () => (findModesForTab),
917
+ isStateOnTab: () => (isStateOnTab) });
918
+
919
+
920
+ // EXTERNAL MODULE: external "dedent-js"
921
+ var external_dedent_js_ = __webpack_require__(868);
922
+ // EXTERNAL MODULE: external "zod"
923
+ var external_zod_ = __webpack_require__(971);
924
+ // EXTERNAL MODULE: ./src/backend/mcp/tools/helpers.mjs
925
+ var helpers = __webpack_require__(903);
926
+ ;// CONCATENATED MODULE: ./src/backend/mcp/tools/browsers.mjs
927
+
928
+
929
+
930
+
931
+ function browserTools({ pages }) {
932
+ return [
933
+ {
934
+ name: "list_browsers",
935
+ description: (0,external_dedent_js_["default"])`
936
+ List the browser tabs connected to this cdk dev server, with the id
937
+ other tools can be aimed at and the page each one is showing.
938
+ `,
939
+ schema: external_zod_.z.object({}),
940
+ handler: () => ({ browsers: pages.listClients() }),
941
+ },
942
+ {
943
+ name: "get_page_url",
944
+ description: "Return the URL a connected browser is showing.",
945
+ schema: external_zod_.z.object({ browser_id: helpers/* .browserIdSchema */.NW }),
946
+ handler: ({ browser_id: browserId }) => ({
947
+ url: pages.getClient(browserId).url,
948
+ }),
949
+ },
950
+ {
951
+ name: "evaluate",
952
+ description: (0,external_dedent_js_["default"])`
953
+ Run JavaScript in a connected browser and return the result. The code
954
+ is evaluated as an async expression, so \`await\` works and the value
955
+ of the expression is what comes back.
956
+ `,
957
+ schema: external_zod_.z.object({
958
+ js: external_zod_.z.string().describe("A JavaScript expression to evaluate."),
959
+ browser_id: helpers/* .browserIdSchema */.NW,
960
+ }),
961
+ handler: async ({ js, browser_id: browserId }) => ({
962
+ result: await pages.evaluate(browserId, js),
963
+ }),
964
+ },
965
+ {
966
+ name: "read_console",
967
+ description: (0,external_dedent_js_["default"])`
968
+ Return the buffered console output of a connected browser. Each entry
969
+ is \`{ts, level, args}\`, where \`ts\` is a millisecond timestamp and
970
+ \`level\` is one of log|info|warn|error|debug.
971
+ `,
972
+ schema: external_zod_.z.object({
973
+ since: external_zod_.z.number()
974
+ .describe(
975
+ (0,external_dedent_js_["default"])`
976
+ Only return entries newer than this millisecond timestamp. Pass the
977
+ \`ts\` of the last entry you saw to poll for new output.
978
+ `,
979
+ )
980
+ .optional(),
981
+ level: external_zod_.z["enum"](["log", "info", "warn", "error", "debug"])
982
+ .describe("Only return entries at this level.")
983
+ .optional(),
984
+ pattern: external_zod_.z.string()
985
+ .describe(
986
+ "Only return entries whose text matches this regular expression.",
987
+ )
988
+ .optional(),
989
+ limit: external_zod_.z.number()
990
+ .int()
991
+ .min(1)
992
+ .max(500)
993
+ .describe(
994
+ "How many of the newest matches to return. Defaults to 100.",
995
+ )
996
+ .optional(),
997
+ browser_id: helpers/* .browserIdSchema */.NW,
998
+ }),
999
+ handler: async ({
1000
+ since,
1001
+ level,
1002
+ pattern,
1003
+ limit = 100,
1004
+ browser_id: browserId,
1005
+ }) => {
1006
+ const entries = await pages.readConsole(browserId, { since });
1007
+ const matching = filterConsole(entries, { level, pattern });
1008
+
1009
+ return {
1010
+ entries: matching.slice(-limit),
1011
+ // A caller that asked for 100 and got 100 cannot otherwise tell
1012
+ // whether it is looking at all of them.
1013
+ matched: matching.length,
1014
+ };
1015
+ },
1016
+ },
1017
+ ];
1018
+ }
1019
+
1020
+ /**
1021
+ * Narrows console output to what a caller asked for.
1022
+ *
1023
+ * A deck logs enough that returning the buffer whole can cost more tokens than
1024
+ * the entries worth reading.
1025
+ */
1026
+ function filterConsole(entries, { level, pattern } = {}) {
1027
+ const matcher = pattern ? new RegExp(pattern) : null;
1028
+
1029
+ return entries.filter((entry) => {
1030
+ if (level && entry.level !== level) {
1031
+ return false;
1032
+ }
1033
+
1034
+ return !matcher || matcher.test(describeArgs(entry.args));
1035
+ });
1036
+ }
1037
+
1038
+ function describeArgs(args = []) {
1039
+ return args
1040
+ .map((arg) => (typeof arg === "string" ? arg : JSON.stringify(arg)))
1041
+ .join(" ");
1042
+ }
1043
+
1044
+ ;// CONCATENATED MODULE: ./src/backend/mcp/tools/content.mjs
1045
+
1046
+
1047
+
1048
+
1049
+ function contentTools({ pages }) {
1050
+ return [
1051
+ {
1052
+ name: "get_cms_val",
1053
+ description: (0,external_dedent_js_["default"])`
1054
+ Return the CMS value behind one of a deck's editables, looked up by
1055
+ its key. The key belongs to any editable in the deck, not just the
1056
+ current slide; list_slides enumerates the editables per slide.
1057
+ `,
1058
+ schema: external_zod_.z.object({
1059
+ key: external_zod_.z.string().describe("A single editable's key."),
1060
+ browser_id: helpers/* .browserIdSchema */.NW,
1061
+ }),
1062
+ handler: ({ key, browser_id: browserId }) =>
1063
+ pages.deck(browserId, "get_cms_val", { key }),
1064
+ },
1065
+ {
1066
+ name: "set_cms_val",
1067
+ description: (0,external_dedent_js_["default"])`
1068
+ Set the CMS value behind one of a deck's editables, as though it had
1069
+ been typed in. Takes effect wherever that editable appears, whichever
1070
+ slide is on screen.
1071
+ `,
1072
+ schema: external_zod_.z.object({
1073
+ key: external_zod_.z.string().describe("The editable's key."),
1074
+ value: external_zod_.z.string().describe("The value to store."),
1075
+ mime: external_zod_.z.string()
1076
+ .describe(
1077
+ "How the deck should read the value. Defaults to text/plain.",
1078
+ )
1079
+ .optional(),
1080
+ browser_id: helpers/* .browserIdSchema */.NW,
1081
+ }),
1082
+ handler: ({ key, value, mime, browser_id: browserId }) =>
1083
+ pages.deck(browserId, "set_cms_val", { key, value, mime }),
1084
+ },
1085
+ {
1086
+ name: "get_context",
1087
+ description: (0,external_dedent_js_["default"])`
1088
+ Return the context a deck is being rendered against - the data its
1089
+ slides read. Pass \`path\` for one value; without it the whole
1090
+ context comes back, which can be large.
1091
+ `,
1092
+ schema: external_zod_.z.object({
1093
+ path: external_zod_.z.string().describe("Dot path into the context.").optional(),
1094
+ browser_id: helpers/* .browserIdSchema */.NW,
1095
+ }),
1096
+ handler: ({ path, browser_id: browserId }) =>
1097
+ pages.deck(browserId, "get_context", { path }),
1098
+ },
1099
+ {
1100
+ name: "set_context",
1101
+ description: (0,external_dedent_js_["default"])`
1102
+ Set a value in the context a deck is rendered against. The edit sits
1103
+ on top of the selected context, the same as one made in the CDK's
1104
+ data panel. Levels that do not exist yet are created.
1105
+ `,
1106
+ schema: external_zod_.z.object({
1107
+ path: external_zod_.z.string().describe("Dot path into the context."),
1108
+ value: external_zod_.z.any()
1109
+ .describe("The value to store: text, a number, or a whole object."),
1110
+ browser_id: helpers/* .browserIdSchema */.NW,
1111
+ }),
1112
+ handler: ({ path, value, browser_id: browserId }) =>
1113
+ pages.deck(browserId, "set_context", { path, value }),
1114
+ },
1115
+ {
1116
+ name: "clear_cms_vals",
1117
+ description: (0,external_dedent_js_["default"])`
1118
+ Discard every CMS value stored in the CDK, so each editable shows
1119
+ its default again. The same as the toolbar's Reset > Clear CMS
1120
+ Vals. Reloads the deck afterwards and returns what it is showing.
1121
+ `,
1122
+ schema: external_zod_.z.object({ browser_id: helpers/* .browserIdSchema */.NW }),
1123
+ handler: ({ browser_id: browserId }) =>
1124
+ clearThenReload(pages, browserId, "clear_cms_vals"),
1125
+ },
1126
+ {
1127
+ name: "clear_context",
1128
+ description: (0,external_dedent_js_["default"])`
1129
+ Discard every context edit made in the CDK, so the deck renders
1130
+ against the selected context as it was loaded. The same as the
1131
+ toolbar's Reset > Clear Context Vals. Reloads the deck afterwards
1132
+ and returns what it is showing.
1133
+ `,
1134
+ schema: external_zod_.z.object({ browser_id: helpers/* .browserIdSchema */.NW }),
1135
+ handler: ({ browser_id: browserId }) =>
1136
+ clearThenReload(pages, browserId, "clear_context"),
1137
+ },
1138
+ ];
1139
+ }
1140
+
1141
+ // A clear is a storage write the slide on screen does not always follow, which
1142
+ // is why the toolbar's Reset menu reloads after one.
1143
+ async function clearThenReload(pages, browserId, command) {
1144
+ const { cleared } = await pages.deck(browserId, command);
1145
+ const state = await pages.deck(browserId, "reload");
1146
+
1147
+ return { cleared, ...state };
1148
+ }
1149
+
1150
+ ;// CONCATENATED MODULE: ./src/backend/mcp/tools/dock.mjs
1151
+
1152
+
1153
+
1154
+
1155
+ const limitSchema = external_zod_.z.number()
1156
+ .int()
1157
+ .min(1)
1158
+ .max(300)
1159
+ .describe("How many of the most recent entries to return. Defaults to 50.")
1160
+ .optional();
1161
+
1162
+ function dockTools({ pages }) {
1163
+ return [
1164
+ {
1165
+ name: "read_action_log",
1166
+ description: (0,external_dedent_js_["default"])`
1167
+ Return the queries and mutations that have run against the deck's
1168
+ fields, newest last.
1169
+
1170
+ Each entry says which target and operation ran, what it was given,
1171
+ what came back, and how long it took. \`source\` is "mcp" where a tool
1172
+ call drove it and "user" where a person edited on the slide, so this
1173
+ is how to tell an edit you made from an edit someone typed.
1174
+
1175
+ Consecutive calls to one operation on one target from one source share
1176
+ an entry. Its fields repeat the latest call, and \`calls\` lists every
1177
+ one in order - a person typing a word is one entry with a call per
1178
+ keystroke.
1179
+
1180
+ Lives in memory, so a reload empties it.
1181
+ `,
1182
+ schema: external_zod_.z.object({ limit: limitSchema, browser_id: helpers/* .browserIdSchema */.NW }),
1183
+ handler: ({ limit, browser_id: browserId }) =>
1184
+ pages.deck(browserId, "read_action_log", { limit }),
1185
+ },
1186
+ {
1187
+ name: "read_changes",
1188
+ description: (0,external_dedent_js_["default"])`
1189
+ Return the stored values the deck has written, newest last - the
1190
+ cmsvals and context paths that carry an edit, with what each one held
1191
+ before.
1192
+
1193
+ read_action_log says what was asked for; this says what landed.
1194
+
1195
+ Lives in memory, so a reload empties it.
1196
+ `,
1197
+ schema: external_zod_.z.object({ limit: limitSchema, browser_id: helpers/* .browserIdSchema */.NW }),
1198
+ handler: ({ limit, browser_id: browserId }) =>
1199
+ pages.deck(browserId, "read_changes", { limit }),
1200
+ },
1201
+ ];
1202
+ }
1203
+
1204
+ ;// CONCATENATED MODULE: ../../modules/deck-interface/llm/definitions.js
1205
+ /**
1206
+ * What the five tools are called and what a caller reads before using one.
1207
+ *
1208
+ * The schemas here are inert JSON Schema. A host turns them into whatever its
1209
+ * own transport needs - the CDK builds zod from them - so nothing here depends
1210
+ * on a validator and deck-interface keeps no dependencies.
1211
+ *
1212
+ * `createDeckInterface` in `../interface.js` builds the functions these describe,
1213
+ * under the same names.
1214
+ */
1215
+
1216
+ const TARGET_KEY = {
1217
+ type: "string",
1218
+ description: 'A target key from list_targets, e.g. "insurance/fees".',
1219
+ };
1220
+
1221
+ const STEPS = {
1222
+ type: "array",
1223
+ description: "The steps to run, in order. One step is a list of one.",
1224
+ items: {
1225
+ type: "object",
1226
+ properties: {
1227
+ target: TARGET_KEY,
1228
+ operation: {
1229
+ type: "string",
1230
+ description: "An operation name from describe_targets.",
1231
+ },
1232
+ on: {
1233
+ type: "string",
1234
+ description: stripIndent(`
1235
+ Which part inside the target, for an operation that addresses
1236
+ one. An operation on the target itself needs none.
1237
+ `),
1238
+ },
1239
+ input: {
1240
+ description: stripIndent(`
1241
+ What the operation takes, matching its inputSchema. An
1242
+ operation that asks for nothing takes none.
1243
+ `),
1244
+ },
1245
+ },
1246
+ required: ["target", "operation"],
1247
+ },
1248
+ };
1249
+
1250
+ const TOOL_DEFINITIONS = [
1251
+ {
1252
+ name: "list_targets",
1253
+ description: stripIndent(`
1254
+ Every slide, section and template in the deck, with what each one is
1255
+ and how many editable fields it has.
1256
+
1257
+ Reads one file and opens no target, however large the deck is. Start
1258
+ here: everything else takes a target key from it.
1259
+ `),
1260
+ inputSchema: { type: "object", properties: {} },
1261
+ },
1262
+ {
1263
+ name: "describe_targets",
1264
+ description: stripIndent(`
1265
+ Everything the targets you name can be asked or told, as operations.
1266
+ Each one says whether it reads or changes something, what it is for,
1267
+ and the schema of what it takes.
1268
+
1269
+ Slides share components, so one operation usually covers several
1270
+ places. Its "on" maps each target to the names to call it by there.
1271
+ Every call names an operation from "on", so read that to find the
1272
+ name you want.
1273
+
1274
+ Ask for every target you mean to work on in one call. It costs one
1275
+ import each, a target named twice costs one, and a name the deck does
1276
+ not have is refused before any of them are opened.
1277
+
1278
+ It reads no stored value, so it says what is possible rather than
1279
+ what is there. Read a field before replacing it: a field still
1280
+ showing the copy the deck was built with looks the same here as one
1281
+ somebody has written over, and read_content tells them apart.
1282
+
1283
+ "requiresRender" on an operation means the slide it belongs to has to be
1284
+ the one on screen. Show that slide with set_slide, then call it.
1285
+ `),
1286
+ inputSchema: {
1287
+ type: "object",
1288
+ properties: {
1289
+ targets: {
1290
+ type: "array",
1291
+ description: "Target keys from list_targets.",
1292
+ items: TARGET_KEY,
1293
+ },
1294
+ },
1295
+ required: ["targets"],
1296
+ },
1297
+ },
1298
+ {
1299
+ name: "read_content",
1300
+ description: stripIndent(`
1301
+ Ask any number of targets what they currently hold, in one request.
1302
+ A step is { target, operation, on?, input }, naming an operation
1303
+ describe_targets listed. Answers come back in the order asked.
1304
+
1305
+ Costs one import per target named, and nothing for a target named
1306
+ twice. An operation that changes something is refused here - that is
1307
+ call_actions - so a failed write can never abort a read.
1308
+
1309
+ A query result carries "from", saying where the value came out of:
1310
+ "default" is the copy the deck was built with, "everyone" is the value
1311
+ every presentation shares, "personal" is this presentation's own
1312
+ override of it, and null means the query read no stored value at all.
1313
+ Check it before replacing anything.
1314
+ `),
1315
+ inputSchema: {
1316
+ type: "object",
1317
+ properties: { steps: STEPS },
1318
+ required: ["steps"],
1319
+ },
1320
+ },
1321
+ {
1322
+ name: "call_actions",
1323
+ description: stripIndent(`
1324
+ Change content across any number of targets in one request. A step is
1325
+ { target, operation, on?, input }, and queries are allowed among
1326
+ them.
1327
+
1328
+ The whole list succeeds or none of it does: a refusal names the step
1329
+ it came from and nothing at all is written. A later step sees what an
1330
+ earlier one did, so a batch can add something and then fill it in.
1331
+
1332
+ Never send a storage key. The deck decides where each value lands.
1333
+ `),
1334
+ inputSchema: {
1335
+ type: "object",
1336
+ properties: { steps: STEPS },
1337
+ required: ["steps"],
1338
+ },
1339
+ },
1340
+ {
1341
+ name: "find_values",
1342
+ description: stripIndent(`
1343
+ Find every key in the deck holding some text, and which targets
1344
+ carry it.
1345
+
1346
+ Search for the words as the slide reads them. Every word has to
1347
+ appear, in the key or in the value, but order, case, markup and
1348
+ punctuation are all ignored - so "annual report" finds a heading
1349
+ stored as "<h2>Annual<br><em>report</em></h2>", and "first quarter"
1350
+ finds the key first_quarter-heading.
1351
+
1352
+ A field matches on what it shows: the stored value, or the deck's
1353
+ own copy where nothing is stored over it.
1354
+
1355
+ Costs nothing beyond what is already in memory: no target is opened
1356
+ and nothing is fetched. Use it to find the slides worth describing
1357
+ before describing any of them.
1358
+ `),
1359
+ inputSchema: {
1360
+ type: "object",
1361
+ properties: {
1362
+ query: { type: "string", description: "The text to look for." },
1363
+ },
1364
+ required: ["query"],
1365
+ },
1366
+ },
1367
+ ];
1368
+
1369
+ // deck-interface takes no dependencies, so a template literal is dedented here
1370
+ // rather than by dedent-js.
1371
+ function stripIndent(text) {
1372
+ return text.replace(/\n\t*/g, "\n").trim();
1373
+ }
1374
+
1375
+ ;// CONCATENATED MODULE: ./src/backend/mcp/tools/interface.mjs
1376
+
1377
+
1378
+
1379
+
1380
+
1381
+ /**
1382
+ * Advertises the five tools a deck's own interface answers, over MCP.
1383
+ *
1384
+ * Nothing here says what a tool does or what it takes. The names, the prose a
1385
+ * model reads and the schemas all come from `deck-interface`, so the CDK and
1386
+ * the app advertise one description rather than two. All the CDK adds is which
1387
+ * browser to talk to.
1388
+ */
1389
+ function interfaceTools({ pages }) {
1390
+ return TOOL_DEFINITIONS.map(({ name, description, inputSchema }) => ({
1391
+ name,
1392
+ description,
1393
+ schema: external_zod_.z.object({
1394
+ ...external_zod_.z.fromJSONSchema(inputSchema).shape,
1395
+ browser_id: helpers/* .browserIdSchema */.NW,
1396
+ }),
1397
+ handler: async ({ browser_id: browserId, ...args }) => {
1398
+ // A caller names a field and the deck decides the rest, so the list of
1399
+ // where each value landed carries nothing it can act on. Each step
1400
+ // reports what it left in the slot, in the caller's own terms.
1401
+ const { writes, ...answered } = await pages.deck(browserId, name, args);
1402
+
1403
+ return answered;
1404
+ },
1405
+ }));
1406
+ }
1407
+
1408
+ ;// CONCATENATED MODULE: ./src/shared/tabs.mjs
1409
+ // Which half of a deck the stage is showing. Shared by the app and the dev
1410
+ // server, so this file is .mjs alongside `modes.mjs`.
1411
+ const SLIDES = "slides";
1412
+
1413
+ const TEMPLATES = "templates";
1414
+
1415
+ const TABS = [SLIDES, TEMPLATES];
1416
+
1417
+ ;// CONCATENATED MODULE: ./src/shared/modes.mjs
1418
+ // Shared by the app and the dev server (the MCP mode tools), so this file is
1419
+ // .mjs: the backend imports it directly with Node's ESM loader.
1420
+
1421
+
1422
+ /** Where a mode keeps what is typed into it. */
1423
+ const CMS_VALS = "cmsVals";
1424
+
1425
+ const CONTEXT_OVERRIDES = "contextOverrides";
1426
+
1427
+ /** Where a template copy keeps both its companywide and its personal values. */
1428
+ const TEMPLATE_CONTEXT = "templateContext";
1429
+
1430
+ // The instance `placement` reports, which is what a caller with no template in
1431
+ // hand sees. Each template drawn on the tab is given a number of its own.
1432
+ const REPORTED_INSTANCE = 1;
1433
+
1434
+ const PRESENT_STATES = [
1435
+ {
1436
+ title: "App",
1437
+ key: "app",
1438
+ description: "Replicate various areas in the app",
1439
+ childrenDescription: "Which app screen",
1440
+ children: [
1441
+ {
1442
+ title: "Preso",
1443
+ key: "preso",
1444
+ description: "Screens for a preso",
1445
+ childrenDescription: "Preso present types",
1446
+ editStore: CONTEXT_OVERRIDES,
1447
+ children: [
1448
+ {
1449
+ title: "Prep",
1450
+ key: "prep",
1451
+ description:
1452
+ "Test preparing a preso - contains editables and the like usually",
1453
+ bodyClasses: ["master", "omnipreso", "livepreso"],
1454
+ tabs: [(/* inlined export .SLIDES */"slides")],
1455
+ childrenDescription: "Prepping or previewing",
1456
+ children: [
1457
+ {
1458
+ title: "Prepping",
1459
+ key: "prepping",
1460
+ bodyClasses: ["preview"],
1461
+ showEditables: true,
1462
+ },
1463
+ {
1464
+ title: "Previewing",
1465
+ key: "previewing",
1466
+ bodyClasses: ["present"],
1467
+ },
1468
+ ],
1469
+ },
1470
+ {
1471
+ title: "Add slides",
1472
+ key: "add-slides",
1473
+ description: "Test a template in various stages",
1474
+ bodyClasses: ["master", "omnipreso", "livepreso"],
1475
+ tabs: [TEMPLATES],
1476
+ children: [
1477
+ {
1478
+ title: "Template preview",
1479
+ key: "template-preview",
1480
+ description: "A read-only view of a template",
1481
+ bodyClasses: ["edit-mode"],
1482
+ editStore: null,
1483
+ providesCmsVals: false,
1484
+ },
1485
+ {
1486
+ title: "User template",
1487
+ key: "user-template",
1488
+ description: "A template override owned by a salesperson",
1489
+ bodyClasses: ["edit-mode"],
1490
+ showEditables: true,
1491
+ editStore: TEMPLATE_CONTEXT,
1492
+ buildPlacement: (instance) => ({
1493
+ createdByTemplate: true,
1494
+ templateID: instance,
1495
+ }),
1496
+ },
1497
+ {
1498
+ title: "Unsaved custom slide",
1499
+ key: "custom-slide",
1500
+ description: "A custom slide dropped in, before it is uploaded",
1501
+ bodyClasses: ["edit-mode"],
1502
+ showEditables: true,
1503
+ editStore: TEMPLATE_CONTEXT,
1504
+ buildPlacement: (instance) => ({
1505
+ createdByTemplate: true,
1506
+ custom: true,
1507
+ willUpload: true,
1508
+ id: instance,
1509
+ }),
1510
+ },
1511
+ {
1512
+ title: "Saved custom slide",
1513
+ key: "custom-slide-saved",
1514
+ description: "A custom slide dropped in, once it is uploaded",
1515
+ bodyClasses: ["edit-mode"],
1516
+ showEditables: true,
1517
+ editStore: TEMPLATE_CONTEXT,
1518
+ buildPlacement: (instance) => ({
1519
+ createdByTemplate: true,
1520
+ custom: true,
1521
+ adjunct: { id: instance },
1522
+ }),
1523
+ },
1524
+ ],
1525
+ },
1526
+ {
1527
+ title: "Present",
1528
+ key: "present",
1529
+ description: "Test how it will be presented to customers",
1530
+ bodyClasses: ["master", "omnipreso", "present", "livepreso"],
1531
+ tabs: [(/* inlined export .SLIDES */"slides")],
1532
+ },
1533
+ {
1534
+ title: "Review",
1535
+ key: "review",
1536
+ description: "Test how it looks after the preso has concluded",
1537
+ bodyClasses: ["master", "omnipreso", "review", "livepreso"],
1538
+ editStore: null,
1539
+ tabs: [(/* inlined export .SLIDES */"slides")],
1540
+ },
1541
+ ],
1542
+ },
1543
+ {
1544
+ title: "PresoManager",
1545
+ key: "presomanager",
1546
+ description: "For testing deck-wide editable values and templates",
1547
+ childrenDescription: "Which type of preview",
1548
+ bodyClasses: ["master", "review", "livepreso", "presomanager"],
1549
+ editStore: CMS_VALS,
1550
+ children: [
1551
+ {
1552
+ title: "Edit mode",
1553
+ key: "edit",
1554
+ bodyClasses: ["edit-mode"],
1555
+ showEditables: true,
1556
+ tabs: [(/* inlined export .SLIDES */"slides")],
1557
+ },
1558
+ {
1559
+ title: "Empty preview",
1560
+ key: "preview",
1561
+ bodyClasses: ["empty-preview"],
1562
+ tabs: [(/* inlined export .SLIDES */"slides")],
1563
+ },
1564
+ {
1565
+ title: "Template preview",
1566
+ key: "template-preview",
1567
+ description: "A read-only view of a template",
1568
+ bodyClasses: ["edit-mode"],
1569
+ editStore: null,
1570
+ providesCmsVals: false,
1571
+ tabs: [TEMPLATES],
1572
+ },
1573
+ {
1574
+ title: "Unsaved placed template",
1575
+ key: "placed-template",
1576
+ description: "A template placed as a slide, before it is published",
1577
+ bodyClasses: ["edit-mode"],
1578
+ showEditables: true,
1579
+ // PresoManager uses an "<n>-temp" id until the server assigns a
1580
+ // real one on publish.
1581
+ buildPlacement: (instance) => ({
1582
+ createdByTemplate: true,
1583
+ autoAdjunctID: `${instance}-temp`,
1584
+ }),
1585
+ tabs: [TEMPLATES],
1586
+ },
1587
+ {
1588
+ title: "Saved placed template",
1589
+ key: "placed-template-saved",
1590
+ description: "A template placed as a slide, once it is published",
1591
+ bodyClasses: ["edit-mode"],
1592
+ showEditables: true,
1593
+ buildPlacement: (instance) => ({
1594
+ createdByTemplate: true,
1595
+ autoAdjunctID: instance,
1596
+ }),
1597
+ tabs: [TEMPLATES],
1598
+ },
1599
+ ],
1600
+ },
1601
+ {
1602
+ title: "Preset",
1603
+ key: "preset",
1604
+ description: "For testing a preset preview",
1605
+ bodyClasses: ["review", "master", "livepreso", "empty-preview"],
1606
+ editStore: CMS_VALS,
1607
+ isReadOnly: true,
1608
+ tabs: [(/* inlined export .SLIDES */"slides")],
1609
+ },
1610
+ ],
1611
+ },
1612
+ {
1613
+ title: "Link",
1614
+ key: "link",
1615
+ description:
1616
+ "Links of various sorts for accessing LivePreso outside of the main app",
1617
+ childrenDescription: "What type of link",
1618
+ editStore: CONTEXT_OVERRIDES,
1619
+ tabs: [(/* inlined export .SLIDES */"slides")],
1620
+ children: [
1621
+ { title: "Share", key: "share", bodyClasses: ["share_online"] },
1622
+ { title: "Remote", key: "remote", bodyClasses: ["client"] },
1623
+ ],
1624
+ },
1625
+ {
1626
+ title: "Screenshot",
1627
+ key: "screenshot",
1628
+ description: "Test how the preso looks for various screenshot types",
1629
+ bodyClasses: ["screenshot", "share_online"],
1630
+ childrenDescription: "What type of screenshot",
1631
+ isScreenshot: true,
1632
+ editStore: CONTEXT_OVERRIDES,
1633
+ isReadOnly: true,
1634
+ children: [
1635
+ {
1636
+ title: "Thumbnail",
1637
+ key: "thumbnail",
1638
+ bodyClasses: ["screenshot-thumbnail"],
1639
+ },
1640
+ { title: "PDF", key: "pdf", bodyClasses: ["screenshot-full"] },
1641
+ ],
1642
+ },
1643
+ ];
1644
+
1645
+ /**
1646
+ * The value the deepest state on the trail carries for this field.
1647
+ */
1648
+ function readNearest(states, field, fallback) {
1649
+ const named = [...states].reverse().find((state) => field in state);
1650
+
1651
+ return named ? named[field] : fallback;
1652
+ }
1653
+
1654
+ function collectModes(nodes, ancestors) {
1655
+ const modes = [];
1656
+
1657
+ nodes.forEach((node, index) => {
1658
+ const trail = [...ancestors, { node, index }];
1659
+
1660
+ if (node.children?.length) {
1661
+ modes.push(...collectModes(node.children, trail));
1662
+ return;
1663
+ }
1664
+
1665
+ const nodes = trail.map((entry) => entry.node);
1666
+ const described = [...nodes].reverse().find((state) => state.description);
1667
+ const editStore = readNearest(nodes, "editStore", CMS_VALS);
1668
+ const buildPlacement = readNearest(nodes, "buildPlacement", null);
1669
+
1670
+ // Flags are inherited: a state deep in the tree is in PresoManager, or
1671
+ // showing editables, because one of the states it sits under says so.
1672
+ modes.push({
1673
+ path: nodes.map((state) => state.key).join("/"),
1674
+ indices: trail.map((entry) => entry.index),
1675
+ title: nodes.map((state) => state.title).join(" > "),
1676
+ description: described ? described.description : node.title,
1677
+ bodyClasses: nodes.flatMap((state) => state.bodyClasses ?? []),
1678
+ showEditables: nodes.some((state) => state.showEditables),
1679
+ isPresomanager: nodes.some((state) => state.key === "presomanager"),
1680
+ isScreenshot: nodes.some((state) => state.key === "screenshot"),
1681
+ isEmptyPreview: nodes.some((state) =>
1682
+ state.bodyClasses?.includes("empty-preview"),
1683
+ ),
1684
+ tabs: readNearest(nodes, "tabs", TABS),
1685
+ editStore,
1686
+ isReadOnly: editStore === null || readNearest(nodes, "isReadOnly", false),
1687
+ providesCmsVals: readNearest(nodes, "providesCmsVals", true),
1688
+ buildPlacement,
1689
+ // A plain object, because a mode is serialised over the MCP and read
1690
+ // for its shape - which channel it stores on, whether it is a copy.
1691
+ placement: buildPlacement ? buildPlacement(REPORTED_INSTANCE) : null,
1692
+ });
1693
+ });
1694
+
1695
+ return modes;
1696
+ }
1697
+
1698
+ /**
1699
+ * Every mode that can actually be selected: the leaves of PRESENT_STATES.
1700
+ * Picking a parent in the CDK's state selector walks down to its first
1701
+ * descendant until it reaches a leaf, so a leaf is the only thing ever stored.
1702
+ *
1703
+ * `path` is the slash-separated key trail, which is how modes are named
1704
+ * outside the app. `indices` is the position of each step in its level, which
1705
+ * is how the app stores the selection.
1706
+ */
1707
+ const modes_MODES = collectModes(PRESENT_STATES, []);
1708
+
1709
+ function modes_findModeByPath(path) {
1710
+ return modes_MODES.find((mode) => mode.path === path) ?? null;
1711
+ }
1712
+
1713
+ function findModeByIndices(indices) {
1714
+ if (!Array.isArray(indices)) {
1715
+ return null;
1716
+ }
1717
+
1718
+ const wanted = indices.join(",");
1719
+
1720
+ return modes_MODES.find((mode) => mode.indices.join(",") === wanted) ?? null;
1721
+ }
1722
+
1723
+ /** The modes one tab offers, in the order the picker walks them. */
1724
+ function findModesForTab(tab) {
1725
+ return modes_MODES.filter((mode) => mode.tabs.includes(tab));
1726
+ }
1727
+
1728
+ function isStateOnTab(state, tab, inherited = TABS) {
1729
+ const tabs = state.tabs ?? inherited;
1730
+
1731
+ if (state.children?.length) {
1732
+ return state.children.some((child) => isStateOnTab(child, tab, tabs));
1733
+ }
1734
+
1735
+ return tabs.includes(tab);
1736
+ }
1737
+
1738
+ ;// CONCATENATED MODULE: ./src/backend/mcp/tools/modes.mjs
1739
+
1740
+
1741
+
1742
+
1743
+
1744
+ function modeTools({ pages, modes = modes_namespaceObject }) {
1745
+ const { MODES, findModeByPath } = modes;
1746
+
1747
+ const modeList = MODES.map(
1748
+ (mode) => `- ${mode.path} (${mode.title}): ${mode.description}`,
1749
+ ).join("\n");
1750
+
1751
+ return [
1752
+ {
1753
+ name: "get_state",
1754
+ description: (0,external_dedent_js_["default"])`
1755
+ Everything about how a connected browser is showing the deck, in one
1756
+ call. Start a session here.
1757
+
1758
+ - \`slide\` is the slide asked for, \`rendered\` the target the presenter
1759
+ actually has on screen. They differ while a rebuild settles, and
1760
+ that gap is worth checking before trusting a screenshot.
1761
+ - \`build\` says whether the deck's dev server is watching, when it
1762
+ last finished, and what it last said. A change to a build plugin
1763
+ needs that server restarted; a rebuild alone keeps the old one.
1764
+ `,
1765
+ schema: external_zod_.z.object({ browser_id: helpers/* .browserIdSchema */.NW }),
1766
+ handler: async ({ browser_id: browserId }) => {
1767
+ const state = await pages.deck(browserId, "get_state");
1768
+
1769
+ return { ...state, mode: findModeByPath(state.mode) };
1770
+ },
1771
+ },
1772
+ {
1773
+ name: "get_current_mode",
1774
+ description: (0,external_dedent_js_["default"])`
1775
+ Return the mode a connected browser is displaying the deck in - which
1776
+ of the app's screens it is imitating, and whether editables are shown.
1777
+ `,
1778
+ schema: external_zod_.z.object({ browser_id: helpers/* .browserIdSchema */.NW }),
1779
+ handler: async ({ browser_id: browserId }) => {
1780
+ const { mode } = await pages.deck(browserId, "get_state");
1781
+
1782
+ return { mode: findModeByPath(mode) };
1783
+ },
1784
+ },
1785
+ {
1786
+ name: "set_mode",
1787
+ description: (0,external_dedent_js_["default"])`
1788
+ Display the deck the way one of the app's screens would, in a
1789
+ connected browser. Waits for the deck to finish re-rendering before
1790
+ returning, so a screenshot taken next sees the new mode.
1791
+
1792
+ Modes:
1793
+ ${modeList}
1794
+ `,
1795
+ schema: external_zod_.z.object({
1796
+ mode: external_zod_.z["enum"](MODES.map((mode) => mode.path)),
1797
+ browser_id: helpers/* .browserIdSchema */.NW,
1798
+ }),
1799
+ handler: async ({ mode, browser_id: browserId }) => {
1800
+ const state = await pages.deck(browserId, "set_mode", { mode });
1801
+
1802
+ return {
1803
+ mode: findModeByPath(state.mode),
1804
+ settled: state.settled,
1805
+ };
1806
+ },
1807
+ },
1808
+ ];
1809
+ }
1810
+
1811
+ // EXTERNAL MODULE: external "node:fs/promises"
1812
+ var promises_ = __webpack_require__(455);
1813
+ ;// CONCATENATED MODULE: external "node:os"
1814
+ const external_node_os_namespaceObject = __rspack_createRequire_require("node:os");
1815
+ // EXTERNAL MODULE: external "node:path"
1816
+ var external_node_path_ = __webpack_require__(760);
1817
+ ;// CONCATENATED MODULE: external "node:crypto"
1818
+ const external_node_crypto_namespaceObject = __rspack_createRequire_require("node:crypto");
1819
+ ;// CONCATENATED MODULE: ./src/backend/page-scripts/computed-styles.mjs
1820
+ // Enough of the box model, layout and typography to reason about how a slide
1821
+ // is rendering, without returning every property of every element.
1822
+ const REPORTED_PROPERTIES = [
1823
+ "display",
1824
+ "position",
1825
+ "top",
1826
+ "right",
1827
+ "bottom",
1828
+ "left",
1829
+ "z-index",
1830
+ "width",
1831
+ "height",
1832
+ "min-width",
1833
+ "min-height",
1834
+ "max-width",
1835
+ "max-height",
1836
+ "color",
1837
+ "background",
1838
+ "font",
1839
+ "font-family",
1840
+ "font-size",
1841
+ "font-weight",
1842
+ "line-height",
1843
+ "text-align",
1844
+ "margin",
1845
+ "padding",
1846
+ "border",
1847
+ "border-radius",
1848
+ "box-shadow",
1849
+ "visibility",
1850
+ "opacity",
1851
+ "transform",
1852
+ "overflow",
1853
+ "object-fit",
1854
+ "flex-direction",
1855
+ "align-items",
1856
+ "justify-content",
1857
+ "gap",
1858
+ "grid-template-columns",
1859
+ "grid-template-rows",
1860
+ ];
1861
+
1862
+ // A slide can have thousands of descendants; past a couple of hundred the
1863
+ // report is too big to be useful anyway, so it is truncated and says so.
1864
+ const MAX_ELEMENTS = 200;
1865
+
1866
+ /**
1867
+ * Builds the JavaScript that, evaluated in the page, reports the computed
1868
+ * styles of the element matching `selector` and everything under it. Each one
1869
+ * is identified by an `nth-child` path relative to that root, so a caller can
1870
+ * feed the path back into another selector-based tool; the root reports itself
1871
+ * as `:scope`.
1872
+ */
1873
+ function computedStylesScript(selector) {
1874
+ return `(() => {
1875
+ const root = document.querySelector(${JSON.stringify(selector)});
1876
+ if (!root) {
1877
+ return { elements: [] };
1878
+ }
1879
+
1880
+ const properties = ${JSON.stringify(REPORTED_PROPERTIES)};
1881
+
1882
+ const selectorFor = (element) => {
1883
+ if (element === root) {
1884
+ return ":scope";
1885
+ }
1886
+
1887
+ const parts = [];
1888
+ let current = element;
1889
+
1890
+ while (current && current !== root) {
1891
+ const parent = current.parentElement;
1892
+ if (!parent) {
1893
+ break;
1894
+ }
1895
+
1896
+ const index = Array.from(parent.children).indexOf(current) + 1;
1897
+ parts.unshift(current.tagName.toLowerCase() + ":nth-child(" + index + ")");
1898
+ current = parent;
1899
+ }
1900
+
1901
+ return parts.join(" > ");
1902
+ };
1903
+
1904
+ const all = [root, ...root.querySelectorAll("*")];
1905
+ const reported = all.slice(0, ${MAX_ELEMENTS});
1906
+ const response = {
1907
+ rootSelector: ${JSON.stringify(selector)},
1908
+ elements: reported.map((element) => {
1909
+ const computed = getComputedStyle(element);
1910
+ return {
1911
+ selector: selectorFor(element),
1912
+ tag: element.tagName.toLowerCase(),
1913
+ classes: Array.from(element.classList),
1914
+ styles: Object.fromEntries(
1915
+ properties.map((property) => [property, computed.getPropertyValue(property)]),
1916
+ ),
1917
+ };
1918
+ }),
1919
+ };
1920
+
1921
+ if (all.length > reported.length) {
1922
+ response.truncated = true;
1923
+ }
1924
+
1925
+ return response;
1926
+ })()`;
1927
+ }
1928
+
1929
+ ;// CONCATENATED MODULE: ./src/backend/mcp/tools/page.mjs
1930
+
1931
+
1932
+
1933
+
1934
+
1935
+
1936
+
1937
+
1938
+
1939
+
1940
+ const CURRENT_SLIDE_SELECTOR = "#slideshow .presoSlide.current";
1941
+
1942
+ const selectorSchema = external_zod_.z.string()
1943
+ .describe(
1944
+ (0,external_dedent_js_["default"])`
1945
+ CSS selector to scope the result. Defaults to the slide on screen. Use a
1946
+ more specific selector to keep the payload small.
1947
+ `,
1948
+ )
1949
+ .optional();
1950
+
1951
+ function pageTools({ pages }) {
1952
+ return [
1953
+ {
1954
+ name: "get_slide_snapshot",
1955
+ description: (0,external_dedent_js_["default"])`
1956
+ Return the rendered HTML of the slide a connected browser is showing,
1957
+ or of a smaller part of it.
1958
+ `,
1959
+ schema: external_zod_.z.object({
1960
+ selector: selectorSchema,
1961
+ browser_id: helpers/* .browserIdSchema */.NW,
1962
+ }),
1963
+ handler: async ({ selector, browser_id: browserId }) => {
1964
+ const scope = selector || CURRENT_SLIDE_SELECTOR;
1965
+ const html = await pages.evaluate(
1966
+ browserId,
1967
+ `document.querySelector(${JSON.stringify(scope)})?.innerHTML ?? null`,
1968
+ );
1969
+
1970
+ return { selector: scope, html };
1971
+ },
1972
+ },
1973
+ {
1974
+ name: "get_styles",
1975
+ description: (0,external_dedent_js_["default"])`
1976
+ Return the computed styles of the elements making up the slide a
1977
+ connected browser is showing. Answers questions a screenshot cannot,
1978
+ like why something is positioned or coloured the way it is.
1979
+ `,
1980
+ schema: external_zod_.z.object({
1981
+ selector: selectorSchema,
1982
+ browser_id: helpers/* .browserIdSchema */.NW,
1983
+ }),
1984
+ handler: ({ selector, browser_id: browserId }) =>
1985
+ pages.evaluate(
1986
+ browserId,
1987
+ computedStylesScript(selector || CURRENT_SLIDE_SELECTOR),
1988
+ ),
1989
+ },
1990
+ {
1991
+ name: "get_slide_screenshot",
1992
+ description: (0,external_dedent_js_["default"])`
1993
+ Capture the slide a connected browser is showing as a PNG and return
1994
+ the path it was written to. Read that path to look at the slide.
1995
+ `,
1996
+ schema: external_zod_.z.object({ browser_id: helpers/* .browserIdSchema */.NW }),
1997
+ handler: async ({ browser_id: browserId }) => {
1998
+ const { data, mimeType } = await pages.screenshot(browserId, {
1999
+ selector: CURRENT_SLIDE_SELECTOR,
2000
+ });
2001
+ const path = (0,external_node_path_.join)((0,external_node_os_namespaceObject.tmpdir)(), `cdk-slide-${(0,external_node_crypto_namespaceObject.randomUUID)()}.png`);
2002
+
2003
+ await (0,promises_.writeFile)(path, Buffer.from(data, "base64"));
2004
+
2005
+ return { path, mimeType };
2006
+ },
2007
+ },
2008
+ ];
2009
+ }
2010
+
2011
+ // EXTERNAL MODULE: ./src/backend/utils/get-project.mjs + 1 modules
2012
+ var get_project = __webpack_require__(577);
2013
+ ;// CONCATENATED MODULE: ./src/backend/utils/get-slide-structure.mjs
2014
+
2015
+
2016
+ function toEntry(entry, kind) {
2017
+ const next = { kind, key: entry.key, title: entry.title };
2018
+
2019
+ if (Array.isArray(entry.editables) && entry.editables.length > 0) {
2020
+ next.editables = entry.editables;
2021
+ }
2022
+
2023
+ return next;
2024
+ }
2025
+
2026
+ function projectSections(sections) {
2027
+ return sections.map((section) => ({
2028
+ // A section renders a slide of its own, so it carries what any other
2029
+ // entry does as well as the slides under it.
2030
+ ...toEntry(section, "section"),
2031
+ slides: (section.slides ?? []).map((slide) => toEntry(slide, "slide")),
2032
+ }));
2033
+ }
2034
+
2035
+ function projectTemplates(templates) {
2036
+ return (templates ?? []).map((template) => toEntry(template, "template"));
2037
+ }
2038
+
2039
+ /**
2040
+ * A handful of older, legacy decks declare `welcome` as a list rather than a
2041
+ * single object — not how it should be declared, but take the first entry
2042
+ * either way. Decks that don't define a welcome screen at all get `null`.
2043
+ */
2044
+ function projectWelcome(welcome) {
2045
+ const entry = Array.isArray(welcome) ? welcome[0] : welcome;
2046
+
2047
+ if (!entry) {
2048
+ return null;
2049
+ }
2050
+
2051
+ return toEntry(
2052
+ { key: "welcome", title: entry.title, editables: entry.editables },
2053
+ "welcome",
2054
+ );
2055
+ }
2056
+
2057
+ /**
2058
+ * The deck's navigable structure, read from the project manifest: the keys
2059
+ * `set_slide` navigates by, with the editables each entry defines.
2060
+ */
2061
+ async function getSlideStructure({ projectDir, distDir }) {
2062
+ const project = await (0,get_project/* .getProject */.U)({ projectDir, distDir });
2063
+
2064
+ return {
2065
+ welcome: projectWelcome(project.welcome),
2066
+ sections: projectSections(project.sections ?? []),
2067
+ templates: projectTemplates(project.templates),
2068
+ };
2069
+ }
2070
+
2071
+ ;// CONCATENATED MODULE: ./src/backend/mcp/tools/slides.mjs
2072
+
2073
+
2074
+
2075
+
2076
+
2077
+ /**
2078
+ * Modelled as one object with a `.refine` rather than a discriminated union:
2079
+ * the MCP SDK only accepts object schemas, and a union collapses to an empty
2080
+ * schema the model cannot call.
2081
+ */
2082
+ const setSlideSchema = external_zod_.z.object({
2083
+ type: external_zod_.z["enum"](["slide", "template", "welcome"]),
2084
+ section: external_zod_.z.string()
2085
+ .describe("Section key, required when type is `slide`.")
2086
+ .optional(),
2087
+ slide: external_zod_.z.string()
2088
+ .describe(
2089
+ "Slide key within the section. Leave it out for the section's own slide.",
2090
+ )
2091
+ .optional(),
2092
+ key: external_zod_.z.string()
2093
+ .describe("Template key, required when type is `template`.")
2094
+ .optional(),
2095
+ browser_id: helpers/* .browserIdSchema */.NW,
2096
+ })
2097
+ .refine(
2098
+ ({ type, section, key }) =>
2099
+ (type === "slide" && section) ||
2100
+ (type === "template" && key) ||
2101
+ type === "welcome",
2102
+ {
2103
+ message: (0,external_dedent_js_["default"])`
2104
+ Navigation targets are {type: "slide", section, slide},
2105
+ {type: "slide", section} for the section's own slide,
2106
+ {type: "template", key} or {type: "welcome"}.
2107
+ `,
2108
+ },
2109
+ );
2110
+
2111
+ function findByKey(entries, key, label) {
2112
+ const found = entries.find((entry) => entry.key === key);
2113
+
2114
+ if (!found) {
2115
+ const available = entries.map((entry) => entry.key).join(", ") || "none";
2116
+ throw new Error(`Unknown ${label} "${key}". Available: ${available}.`);
2117
+ }
2118
+
2119
+ return found;
2120
+ }
2121
+
2122
+ function slideTools({ pages, projectDir, distDir }) {
2123
+ const readStructure = () => getSlideStructure({ projectDir, distDir });
2124
+
2125
+ async function checkTarget(target) {
2126
+ if (target.type === "welcome") {
2127
+ return { type: "welcome" };
2128
+ }
2129
+
2130
+ const { sections, templates } = await readStructure();
2131
+
2132
+ if (target.type === "template") {
2133
+ return {
2134
+ type: "template",
2135
+ key: findByKey(templates, target.key, "template").key,
2136
+ };
2137
+ }
2138
+
2139
+ const section = findByKey(sections, target.section, "section");
2140
+
2141
+ if (!target.slide) {
2142
+ return { type: "slide", section: section.key };
2143
+ }
2144
+
2145
+ return {
2146
+ type: "slide",
2147
+ section: section.key,
2148
+ slide: findByKey(section.slides, target.slide, "slide").key,
2149
+ };
2150
+ }
2151
+
2152
+ /**
2153
+ * Adds the title and editables the manifest knows about to the bare
2154
+ * `{type, ...keys}` the page reports. A slide the manifest has no record of
2155
+ * (a stale dist, say) is passed through as-is.
2156
+ */
2157
+ async function describe(slide) {
2158
+ const { sections, templates, welcome } = await readStructure();
2159
+ let found = null;
2160
+
2161
+ if (slide?.type === "slide") {
2162
+ const section = sections.find((entry) => entry.key === slide.section);
2163
+
2164
+ // No slide key names the section's own slide, which the section entry
2165
+ // carries the title and editables for.
2166
+ found = slide.slide
2167
+ ? section?.slides.find((entry) => entry.key === slide.slide)
2168
+ : section;
2169
+ }
2170
+
2171
+ if (slide?.type === "template") {
2172
+ found = templates.find((entry) => entry.key === slide.key);
2173
+ }
2174
+
2175
+ if (slide?.type === "welcome") {
2176
+ found = welcome;
2177
+ }
2178
+
2179
+ const described = { ...slide };
2180
+
2181
+ if (found) {
2182
+ described.title = found.title;
2183
+ }
2184
+
2185
+ if (found?.editables) {
2186
+ described.editables = found.editables;
2187
+ }
2188
+
2189
+ return described;
2190
+ }
2191
+
2192
+ /**
2193
+ * What a command reports back: the slide the page ended up on, plus whether
2194
+ * the page confirmed it had finished rendering. `settled: false` means the
2195
+ * change was made but the deck took longer than the page was willing to
2196
+ * wait, so anything read next may still be catching up.
2197
+ */
2198
+ async function report(state) {
2199
+ const described = await describe(state.slide);
2200
+
2201
+ if (state.settled !== undefined) {
2202
+ described.settled = state.settled;
2203
+ }
2204
+
2205
+ return described;
2206
+ }
2207
+
2208
+ return [
2209
+ {
2210
+ name: "list_slides",
2211
+ description: (0,external_dedent_js_["default"])`
2212
+ List the deck's welcome slide, sections, the slides in each section,
2213
+ and its top-level templates. The keys returned here are what
2214
+ set_slide navigates by.
2215
+ `,
2216
+ schema: external_zod_.z.object({}),
2217
+ handler: () => readStructure(),
2218
+ },
2219
+ {
2220
+ name: "set_slide",
2221
+ description: (0,external_dedent_js_["default"])`
2222
+ Navigate a connected browser to a slide, a template or the welcome
2223
+ screen, and return what it ends up showing. Waits for the deck to
2224
+ finish rendering before returning, so a screenshot taken next sees
2225
+ the slide that was asked for.
2226
+ `,
2227
+ schema: setSlideSchema,
2228
+ handler: async ({ browser_id: browserId, ...target }) => {
2229
+ const checked = await checkTarget(target);
2230
+ const state = await pages.deck(browserId, "navigate", checked);
2231
+ return report(state);
2232
+ },
2233
+ },
2234
+ {
2235
+ name: "get_current_slide",
2236
+ description: (0,external_dedent_js_["default"])`
2237
+ Return the slide a connected browser is showing, with its title and
2238
+ the editables the deck defines on it.
2239
+ `,
2240
+ schema: external_zod_.z.object({ browser_id: helpers/* .browserIdSchema */.NW }),
2241
+ handler: async ({ browser_id: browserId }) => {
2242
+ const state = await pages.deck(browserId, "get_state");
2243
+ return report(state);
2244
+ },
2245
+ },
2246
+ {
2247
+ name: "refresh_slide",
2248
+ description: (0,external_dedent_js_["default"])`
2249
+ Render the slide on screen again, so it re-reads the data it draws
2250
+ from. Decks differ in how much they watch for themselves: one may
2251
+ pick up a context change on its own, another only shows it once the
2252
+ slide is rendered again. Reach for this when something set with
2253
+ set_context or set_cms_val has not appeared.
2254
+ `,
2255
+ schema: external_zod_.z.object({ browser_id: helpers/* .browserIdSchema */.NW }),
2256
+ handler: async ({ browser_id: browserId }) => {
2257
+ const state = await pages.deck(browserId, "refresh");
2258
+ return report(state);
2259
+ },
2260
+ },
2261
+ {
2262
+ name: "reload_slide",
2263
+ description: (0,external_dedent_js_["default"])`
2264
+ Rebuild the deck in a connected browser from the content on disk and
2265
+ return what it ends up showing. Use this to pick up an edit to the
2266
+ deck's source; refresh_slide is enough for a change to its data.
2267
+ `,
2268
+ schema: external_zod_.z.object({ browser_id: helpers/* .browserIdSchema */.NW }),
2269
+ handler: async ({ browser_id: browserId }) => {
2270
+ const state = await pages.deck(browserId, "reload");
2271
+ return report(state);
2272
+ },
2273
+ },
2274
+ ];
2275
+ }
2276
+
2277
+ ;// CONCATENATED MODULE: ./src/backend/mcp/tools/index.mjs
2278
+
2279
+
2280
+
2281
+
2282
+
2283
+
2284
+
2285
+
2286
+ /**
2287
+ * Every tool the dev server exposes. The stdio proxy calls this without any
2288
+ * dependencies to describe the tools it forwards, so the handlers must not run
2289
+ * at build time.
2290
+ */
2291
+ function allTools(deps = {}) {
2292
+ return [
2293
+ ...browserTools(deps),
2294
+ ...slideTools(deps),
2295
+ ...pageTools(deps),
2296
+ ...modeTools(deps),
2297
+ ...contentTools(deps),
2298
+ ...interfaceTools(deps),
2299
+ ...dockTools(deps),
2300
+ ];
2301
+ }
2302
+
2303
+
2304
+ },
2305
+ 360(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) {
2306
+
2307
+ // EXPORTS
2308
+ __webpack_require__.d(__webpack_exports__, {
2309
+ A: () => (/* binding */ backend_server)
2310
+ });
2311
+ // NAMESPACE OBJECT: ./src/backend/routes/index.mjs
2312
+ var routes_namespaceObject = {};
2313
+ __webpack_require__.r(routes_namespaceObject);
2314
+ __webpack_require__.d(routes_namespaceObject, {
2315
+ contextsRoutes: () => (contextsRoutes),
2316
+ customerRoutes: () => (customerRoutes),
2317
+ deckAssetsRoutes: () => (deckAssetsRoutes),
2318
+ envsRoutes: () => (envsRoutes),
2319
+ feedsRoutes: () => (feedsRoutes),
2320
+ projectRoutes: () => (projectRoutes),
2321
+ publicRoutes: () => (publicRoutes),
2322
+ rootRoutes: () => (rootRoutes) });
2323
+
2324
+
2325
+ // EXTERNAL MODULE: external "consola"
2326
+ var external_consola_ = __webpack_require__(691);
2327
+ ;// CONCATENATED MODULE: external "fastify"
2328
+
2329
+ ;// CONCATENATED MODULE: external "@fastify/cors"
2330
+
2331
+ ;// CONCATENATED MODULE: external "portscanner"
2332
+
2333
+ // EXTERNAL MODULE: external "path"
2334
+ var external_path_ = __webpack_require__(928);
2335
+ ;// CONCATENATED MODULE: external "fast-glob"
2336
+
2337
+ // EXTERNAL MODULE: external "node:fs/promises"
2338
+ var promises_ = __webpack_require__(455);
2339
+ ;// CONCATENATED MODULE: ./src/backend/utils/get-contexts.mjs
2340
+
2341
+
2342
+
2343
+
2344
+ async function getContexts(config) {
2345
+ const { projectDir } = config;
2346
+
2347
+ const contextsPath = external_path_.join(projectDir, ".cdk/contexts");
2348
+
2349
+ const filepaths = await __rspack_external_fast_glob_bdd2f626["default"].async([contextsPath + `/*.json`]);
2350
+
2351
+ return filepaths.map((filepath) => {
2352
+ const filename = external_path_.basename(filepath);
2353
+ const testKey = filename.replace(".json", "");
2354
+
2355
+ return {
2356
+ key: testKey,
2357
+ filename,
2358
+ title: testKey,
2359
+ };
2360
+ });
2361
+ }
2362
+
2363
+ async function getContext(config, file) {
2364
+ const { projectDir } = config;
2365
+
2366
+ const feedPath = external_path_.join(projectDir, ".cdk/contexts", `${file}.json`);
2367
+
2368
+ try {
2369
+ const file = await promises_.readFile(feedPath, "utf8");
2370
+ return JSON.parse(file);
2371
+ } catch (e) {
2372
+ // TODO: Check if bad content, or missing
2373
+ return null;
2374
+ }
2375
+ }
2376
+
2377
+ ;// CONCATENATED MODULE: ./src/backend/routes/contexts.mjs
2378
+
2379
+
2380
+ function contextsRoutes(config, fastify) {
2381
+ fastify.get(
2382
+ "/server/api/contexts/",
2383
+ { config: { internalName: "context" } },
2384
+ async (_request, reply) => {
2385
+ reply.send({
2386
+ results: await getContexts(config),
2387
+ });
2388
+ },
2389
+ );
2390
+
2391
+ fastify.get(
2392
+ "/server/api/contexts/:file",
2393
+ { config: { internalName: "feed-detail", listed: false } },
2394
+ async (request, reply) => {
2395
+ const { file } = request.params;
2396
+
2397
+ const contents = await getContext(config, file);
2398
+
2399
+ if (!contents) {
2400
+ reply.code(404).send();
2401
+ return;
2402
+ }
2403
+
2404
+ reply.send(contents);
2405
+ },
2406
+ );
2407
+ }
2408
+
2409
+ ;// CONCATENATED MODULE: external "@fastify/static"
2410
+
2411
+ ;// CONCATENATED MODULE: ./src/backend/routes/deck-assets.mjs
2412
+
2413
+
2414
+ function deckAssetsRoutes(config, fastify) {
2415
+ fastify.register(async (scope) => {
2416
+ await scope.register(__rspack_external__fastify_static_a76d2a9e["default"], {
2417
+ root: config.distDir,
2418
+ prefix: "/server/deck/",
2419
+ wildcard: true,
2420
+ });
2421
+ });
2422
+
2423
+ config.listedRoutes.push({ path: "/server/deck/*", internalName: "deck" });
2424
+ }
2425
+
2426
+ ;// CONCATENATED MODULE: ./src/backend/utils/get-envs.mjs
2427
+
2428
+
2429
+
2430
+
2431
+ async function getEnvs(config) {
2432
+ const { projectDir } = config;
2433
+ const envsPath = external_path_.join(projectDir, ".cdk/envs");
2434
+
2435
+ const filepaths = await __rspack_external_fast_glob_bdd2f626["default"].async([
2436
+ envsPath + `/{appointment,tenancy,user}/*.json`,
2437
+ ]);
2438
+
2439
+ const grouped = filepaths.reduce(
2440
+ (acc, file) => {
2441
+ const type = file.split("/").at(-2);
2442
+ const filename = external_path_.basename(file);
2443
+ const testKey = filename.replace(".json", "");
2444
+
2445
+ acc[type].push({
2446
+ key: testKey,
2447
+ filename,
2448
+ title: testKey,
2449
+ });
2450
+
2451
+ return acc;
2452
+ },
2453
+ {
2454
+ appointment: [],
2455
+ tenancy: [],
2456
+ user: [],
2457
+ },
2458
+ );
2459
+
2460
+ return grouped;
2461
+ }
2462
+
2463
+ async function getEnv(config, envType, file) {
2464
+ const { projectDir } = config;
2465
+ const envPath = external_path_.join(projectDir, ".cdk/envs", envType, `${file}.json`);
2466
+
2467
+ try {
2468
+ const file = await promises_.readFile(envPath, "utf8");
2469
+ return JSON.parse(file);
2470
+ } catch (e) {
2471
+ // TODO: Check if bad content, or missing
2472
+ return null;
2473
+ }
2474
+ }
2475
+
2476
+ ;// CONCATENATED MODULE: ./src/backend/routes/envs.mjs
2477
+
2478
+
2479
+ function envsRoutes(config, fastify) {
2480
+ fastify.get(
2481
+ "/server/api/envs/",
2482
+ { config: { internalName: "envs" } },
2483
+ async (_request, reply) => {
2484
+ reply.send({
2485
+ results: await getEnvs(config),
2486
+ });
2487
+ },
2488
+ );
2489
+
2490
+ fastify.get(
2491
+ "/server/api/envs/:envType/:file/",
2492
+ { config: { internalName: "envs-detail", listed: false } },
2493
+ async (request, reply) => {
2494
+ const { envType, file } = request.params;
2495
+
2496
+ const contents = await getEnv(config, envType, file);
2497
+
2498
+ if (!contents) {
2499
+ reply.code(404).send();
2500
+ return;
2501
+ }
2502
+
2503
+ reply.send(contents);
2504
+ },
2505
+ );
2506
+ }
2507
+
2508
+ // EXTERNAL MODULE: ./src/backend/utils/get-project.mjs + 1 modules
2509
+ var get_project = __webpack_require__(577);
2510
+ ;// CONCATENATED MODULE: ./src/backend/utils/get-feeds.mjs
2511
+
2512
+
2513
+
2514
+
2515
+
2516
+ async function getFeeds(config) {
2517
+ const { projectDir } = config;
2518
+ const project = await (0,get_project/* .getProject */.U)(config);
2519
+
2520
+ const feedsPath = external_path_.join(projectDir, ".cdk/feeds");
2521
+
2522
+ const { feeds } = project;
2523
+
2524
+ const results = [];
2525
+
2526
+ for (const feedKey of Object.keys(feeds || {})) {
2527
+ const filepaths = await __rspack_external_fast_glob_bdd2f626["default"].async([feedsPath + `/${feedKey}/*.json`]);
2528
+
2529
+ results.push({
2530
+ key: feedKey,
2531
+ title: feedKey,
2532
+ testFeeds: filepaths.map((filepath) => {
2533
+ const filename = external_path_.basename(filepath);
2534
+ const testKey = filename.replace(".json", "");
2535
+
2536
+ return {
2537
+ key: testKey,
2538
+ filename,
2539
+ title: testKey
2540
+ };
2541
+ }),
2542
+ });
2543
+ }
2544
+
2545
+ return results;
2546
+ }
2547
+
2548
+ async function getFeed(config, feedKey, file) {
2549
+ const { projectDir } = config;
2550
+
2551
+ const feedPath = external_path_.join(projectDir, ".cdk/feeds", feedKey, `${file}.json`);
2552
+
2553
+ try {
2554
+ const file = await promises_.readFile(feedPath, "utf8");
2555
+ return JSON.parse(file);
2556
+ } catch (e) {
2557
+ // TODO: Check if bad content, or missing
2558
+ return null;
2559
+ }
2560
+ }
2561
+
2562
+ ;// CONCATENATED MODULE: ./src/backend/routes/feeds.mjs
2563
+
2564
+
2565
+
2566
+ function feedsRoutes(config, fastify) {
2567
+ fastify.get(
2568
+ "/server/api/feeds/",
2569
+ { config: { internalName: "feeds" } },
2570
+ async (_request, reply) => {
2571
+ reply.send({
2572
+ results: await getFeeds(config),
2573
+ });
2574
+ },
2575
+ );
2576
+
2577
+ fastify.get(
2578
+ "/server/api/feeds/:feedKey/:file",
2579
+ { config: { internalName: "feed-detail", listed: false } },
2580
+ async (request, reply) => {
2581
+ const project = await (0,get_project/* .getProject */.U)(config);
2582
+ const { feedKey, file } = request.params;
2583
+
2584
+ if (!project?.feeds?.[feedKey]) {
2585
+ reply.code(404).send();
2586
+ return;
2587
+ }
2588
+
2589
+ const contents = await getFeed(config, feedKey, file);
2590
+
2591
+ if (!contents) {
2592
+ reply.code(404).send();
2593
+ return;
2594
+ }
2595
+
2596
+ reply.send(contents);
2597
+ },
2598
+ );
2599
+
2600
+ fastify.get(
2601
+ "/server/api/feed-sets/",
2602
+ { config: { internalName: "feed-sets" } },
2603
+ async (_request, reply) => {
2604
+ const feeds = await getFeeds(config);
2605
+
2606
+ const possibleSets = {};
2607
+
2608
+ for (const feed of feeds) {
2609
+ for (const testFeed of feed.testFeeds) {
2610
+ if (!possibleSets[testFeed.key]) {
2611
+ possibleSets[testFeed.key] = [];
2612
+ }
2613
+
2614
+ possibleSets[testFeed.key].push(feed.key);
2615
+ }
2616
+ }
2617
+
2618
+ const actualSets = Object.entries(possibleSets).filter(([, feeds]) => {
2619
+ return feeds.length > 0;
2620
+ });
2621
+
2622
+ reply.send({
2623
+ results: actualSets.map(([setKey, feeds]) => {
2624
+ return {
2625
+ title: setKey,
2626
+ feeds: feeds.reduce((acc, key) => {
2627
+ return { ...acc, [key]: setKey };
2628
+ }, {}),
2629
+ };
2630
+ }),
2631
+ });
2632
+ },
2633
+ );
2634
+ }
2635
+
2636
+ ;// CONCATENATED MODULE: ./src/backend/routes/project.mjs
2637
+
2638
+
2639
+ function projectRoutes(config, fastify) {
2640
+ fastify.get(
2641
+ "/server/api/project/",
2642
+ { config: { internalName: "project" } },
2643
+ async (_request, reply) => {
2644
+ const project = await (0,get_project/* .getProject */.U)(config);
2645
+ reply.send(project);
2646
+ },
2647
+ );
2648
+ }
2649
+
2650
+ // EXTERNAL MODULE: ./src/backend/utils/package-root.mjs
2651
+ var package_root = __webpack_require__(560);
2652
+ ;// CONCATENATED MODULE: ./src/backend/routes/public.mjs
2653
+
2654
+
2655
+
2656
+
2657
+
2658
+
2659
+ function publicRoutes(config, fastify) {
2660
+ const distPath = external_path_.join((0,package_root/* .findPackageRoot */.C)(import.meta.url), "dist");
2661
+
2662
+ fastify.register(async (scope) => {
2663
+ await scope.register(__rspack_external__fastify_static_a76d2a9e["default"], {
2664
+ root: distPath,
2665
+ prefix: "/",
2666
+ wildcard: true,
2667
+ });
2668
+ });
2669
+
2670
+ config.listedRoutes.push({ path: "/*", internalName: "public" });
2671
+ }
2672
+
2673
+ ;// CONCATENATED MODULE: external "url"
2674
+ const external_url_namespaceObject = __rspack_createRequire_require("url");
2675
+ ;// CONCATENATED MODULE: ./src/backend/routes/root.mjs
2676
+
2677
+
2678
+ function rootRoutes(config, fastify) {
2679
+ fastify.get(
2680
+ "/server/",
2681
+ { config: { internalName: "root" } },
2682
+ (_request, reply) => {
2683
+ const paths = config.listedRoutes.map((route) => {
2684
+ const newURL = new external_url_namespaceObject.URL(config.serverURL);
2685
+ newURL.pathname = route.path.replace(/\*.*/g, "");
2686
+ return {
2687
+ path: newURL.toString(),
2688
+ internalName: route.internalName,
2689
+ };
2690
+ });
2691
+
2692
+ const list = paths
2693
+ .map(
2694
+ (route) =>
2695
+ `<li>${route.internalName}: <a href="${route.path}">${route.path}</a></li>`,
2696
+ )
2697
+ .join("");
2698
+
2699
+ reply.header("content-type", "text/html");
2700
+ reply.send(`<html><body><ul>${list}</ul></body></html>`);
2701
+ },
2702
+ );
2703
+ }
2704
+
2705
+ ;// CONCATENATED MODULE: ./src/backend/utils/get-customers.mjs
2706
+
2707
+
2708
+
2709
+
2710
+
2711
+ async function getCustomers(config) {
2712
+ const { projectDir } = config;
2713
+ const customersPath = external_path_.join(projectDir, ".cdk/customers");
2714
+
2715
+ const customers = await __rspack_external_fast_glob_bdd2f626["default"].async(customersPath + "/*", {
2716
+ onlyDirectories: true,
2717
+ });
2718
+
2719
+ const results = [];
2720
+
2721
+ for (const customer of customers) {
2722
+ const customerKey = customer.split("/").at(-1);
2723
+
2724
+ try {
2725
+ const data = JSON.parse(
2726
+ await promises_.readFile(
2727
+ external_path_.join(customersPath, customerKey, "index.json"),
2728
+ "utf8",
2729
+ ),
2730
+ );
2731
+ results.push({
2732
+ key: customerKey,
2733
+ title: data.title,
2734
+ });
2735
+ } catch (e) {
2736
+ // TODO: Show errors somehow
2737
+ external_consola_["default"].error(e);
2738
+ continue;
2739
+ }
2740
+ }
2741
+
2742
+ return results;
2743
+ }
2744
+
2745
+ async function getCustomer(config, customerKey) {
2746
+ const { projectDir } = config;
2747
+ const customersDir = external_path_.join(projectDir, ".cdk/customers", customerKey);
2748
+ let customerIndex;
2749
+ const customerIndexPath = external_path_.join(customersDir, "index.json");
2750
+
2751
+ try {
2752
+ customerIndex = JSON.parse(await promises_.readFile(customerIndexPath, "utf8"));
2753
+ } catch (e) {
2754
+ external_consola_["default"].error(`Issue in file ${customerIndexPath}`);
2755
+ return null;
2756
+ }
2757
+
2758
+ const contactFiles = await __rspack_external_fast_glob_bdd2f626["default"].async(customersDir + "/contacts/*.json");
2759
+ const contacts = [];
2760
+
2761
+ for (const contactFile of contactFiles) {
2762
+ try {
2763
+ const contactData = JSON.parse(await promises_.readFile(contactFile, "utf8"));
2764
+ contacts.push(contactData);
2765
+ } catch (e) {
2766
+ external_consola_["default"].error(`Issue in file ${contactFile}`);
2767
+ external_consola_["default"].error(e);
2768
+ continue;
2769
+ }
2770
+ }
2771
+
2772
+ return {
2773
+ key: customerKey,
2774
+ ...customerIndex,
2775
+ contacts,
2776
+ };
2777
+ }
2778
+
2779
+ ;// CONCATENATED MODULE: ./src/backend/routes/customers.mjs
2780
+
2781
+
2782
+ function customerRoutes(config, fastify) {
2783
+ fastify.get(
2784
+ "/server/api/customers/",
2785
+ { config: { internalName: "customers" } },
2786
+ async (_request, reply) => {
2787
+ reply.send({
2788
+ results: await getCustomers(config),
2789
+ });
2790
+ },
2791
+ );
2792
+
2793
+ fastify.get(
2794
+ "/server/api/customers/:customerKey",
2795
+ { config: { internalName: "customer-detail", listed: false } },
2796
+ async (request, reply) => {
2797
+ const { customerKey } = request.params;
2798
+
2799
+ const contents = await getCustomer(config, customerKey);
2800
+
2801
+ if (!contents) {
2802
+ reply.code(404).send();
2803
+ return;
2804
+ }
2805
+
2806
+ reply.send(contents);
2807
+ },
2808
+ );
2809
+ }
2810
+
2811
+ ;// CONCATENATED MODULE: ./src/backend/routes/index.mjs
2812
+
2813
+
2814
+
2815
+
2816
+
2817
+
2818
+
2819
+
2820
+
2821
+ ;// CONCATENATED MODULE: external "@fastify/websocket"
2822
+
2823
+ ;// CONCATENATED MODULE: ./src/backend/pages/index.mjs
2824
+
2825
+
2826
+ const OPEN_READY_STATE = 1;
2827
+
2828
+ const DEFAULT_TIMEOUT_MS = 5000;
2829
+
2830
+ // Deck commands wait for the page to finish rendering, which after a mode
2831
+ // change means rebuilding the presenter.
2832
+ const DECK_TIMEOUT_MS = 15000;
2833
+
2834
+ function toPagePath(url) {
2835
+ try {
2836
+ const parsedUrl = new URL(url);
2837
+ return `${parsedUrl.pathname}${parsedUrl.search}${parsedUrl.hash}`;
2838
+ } catch {
2839
+ return url;
2840
+ }
2841
+ }
2842
+
2843
+ /**
2844
+ * The dev server's connection to every open deck page.
2845
+ *
2846
+ * Everything that has to happen inside a page - evaluating code, reading the
2847
+ * console, capturing a screenshot, driving the deck - is a request over this
2848
+ * socket, answered by `frontend/page-client.js`. The page is asked whenever a
2849
+ * tool needs to know what it is showing.
2850
+ *
2851
+ * Any number of pages can be connected at once. Each one identifies itself
2852
+ * with an id it keeps in `sessionStorage`, so a reload reconnects as the same
2853
+ * page.
2854
+ */
2855
+ function createPageChannel() {
2856
+ const clients = new Map();
2857
+ const pendingRequests = new Map();
2858
+ let nextRequestId = 0;
2859
+
2860
+ function isOpen(client) {
2861
+ return client?.socket.readyState === OPEN_READY_STATE;
2862
+ }
2863
+
2864
+ function listClients() {
2865
+ return [...clients.values()]
2866
+ .filter(isOpen)
2867
+ .map(({ id, url, connectedAt }) => ({ id, url, connectedAt }));
2868
+ }
2869
+
2870
+ /**
2871
+ * Picks the client a tool call is aimed at. With one tab open the id can be
2872
+ * left out; with several the caller has to say which, and the error names
2873
+ * the choices so the model can retry without a round trip through
2874
+ * `list_browsers`.
2875
+ */
2876
+ function resolveClient(browserId) {
2877
+ const open = [...clients.values()].filter(isOpen);
2878
+
2879
+ if (browserId) {
2880
+ const client = clients.get(browserId);
2881
+ if (!isOpen(client)) {
2882
+ const known = open.map((c) => c.id).join(", ") || "none";
2883
+ throw new Error(
2884
+ `No browser connected with id "${browserId}". Connected: ${known}.`,
2885
+ );
2886
+ }
2887
+ return client;
2888
+ }
2889
+
2890
+ if (open.length === 0) {
2891
+ throw new Error(
2892
+ "No browser connected. Open the cdk frontend at the page URL.",
2893
+ );
2894
+ }
2895
+
2896
+ if (open.length > 1) {
2897
+ const choices = open.map((c) => `${c.id} (${c.url})`).join(", ");
2898
+ throw new Error(
2899
+ `${open.length} browsers are connected; pass browser_id to say which one. Connected: ${choices}.`,
2900
+ );
2901
+ }
2902
+
2903
+ return open[0];
2904
+ }
2905
+
2906
+ function settleRequest(id, settle) {
2907
+ const pendingRequest = pendingRequests.get(id);
2908
+ if (!pendingRequest) {
2909
+ return;
2910
+ }
2911
+
2912
+ clearTimeout(pendingRequest.timeout);
2913
+ pendingRequests.delete(id);
2914
+ settle(pendingRequest);
2915
+ }
2916
+
2917
+ function failClientRequests(client, error) {
2918
+ for (const [id, pendingRequest] of pendingRequests) {
2919
+ if (pendingRequest.client === client) {
2920
+ settleRequest(id, ({ reject }) => reject(error));
2921
+ }
2922
+ }
2923
+ }
2924
+
2925
+ function receiveMessage(client, message) {
2926
+ if (message.type === "url_changed" && typeof message.url === "string") {
2927
+ client.url = toPagePath(message.url);
2928
+ return;
2929
+ }
2930
+
2931
+ if (message.type !== "result") {
2932
+ return;
2933
+ }
2934
+
2935
+ settleRequest(message.id, ({ resolve, reject }) => {
2936
+ if (message.ok) {
2937
+ resolve(message.value);
2938
+ } else {
2939
+ reject(new Error(message.error ?? "The page reported an error."));
2940
+ }
2941
+ });
2942
+ }
2943
+
2944
+ /**
2945
+ * Registers a page under the id it asked for. A tab that reloads reclaims
2946
+ * its own id (its previous socket is already closing); a tab duplicated by
2947
+ * the browser arrives with a copy of another tab's sessionStorage, so it is
2948
+ * handed a fresh id and told to store that instead.
2949
+ */
2950
+ function registerClient(client, requestedId) {
2951
+ let id = requestedId;
2952
+ const existing = clients.get(id);
2953
+
2954
+ if (isOpen(existing) && existing !== client) {
2955
+ let suffix = 2;
2956
+ while (isOpen(clients.get(`${requestedId}-${suffix}`))) {
2957
+ suffix += 1;
2958
+ }
2959
+ id = `${requestedId}-${suffix}`;
2960
+ }
2961
+
2962
+ client.id = id;
2963
+ clients.set(id, client);
2964
+ client.socket.send(JSON.stringify({ type: "welcome", id }));
2965
+ }
2966
+
2967
+ function request(client, message, { timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {
2968
+ const id = String(++nextRequestId);
2969
+
2970
+ return new Promise((resolve, reject) => {
2971
+ const timeout = setTimeout(() => {
2972
+ pendingRequests.delete(id);
2973
+ reject(
2974
+ new Error(
2975
+ `Browser ${client.id} did not answer the ${message.type} request within ${timeoutMs}ms.`,
2976
+ ),
2977
+ );
2978
+ }, timeoutMs);
2979
+
2980
+ pendingRequests.set(id, { client, resolve, reject, timeout });
2981
+
2982
+ try {
2983
+ client.socket.send(JSON.stringify({ ...message, id }));
2984
+ } catch (error) {
2985
+ settleRequest(id, () => reject(error));
2986
+ }
2987
+ });
2988
+ }
2989
+
2990
+ return {
2991
+ async registerRoutes(fastify) {
2992
+ await fastify.register(__rspack_external__fastify_websocket_ea21246a["default"]);
2993
+
2994
+ fastify.get("/server/api/pages/socket", { websocket: true }, (socket) => {
2995
+ const client = { id: null, socket, url: null, connectedAt: Date.now() };
2996
+
2997
+ socket.on("message", (data) => {
2998
+ let message;
2999
+ try {
3000
+ message = JSON.parse(data.toString());
3001
+ } catch {
3002
+ return;
3003
+ }
3004
+
3005
+ // Until a page says hello it has no id, so nothing can be
3006
+ // addressed to it and its other messages are meaningless.
3007
+ if (message.type === "hello") {
3008
+ client.url = toPagePath(message.url ?? "");
3009
+ registerClient(client, message.id);
3010
+ return;
3011
+ }
3012
+
3013
+ if (client.id) {
3014
+ receiveMessage(client, message);
3015
+ }
3016
+ });
3017
+
3018
+ socket.on("close", () => {
3019
+ if (client.id && clients.get(client.id) === client) {
3020
+ clients.delete(client.id);
3021
+ }
3022
+
3023
+ failClientRequests(client, new Error("The browser disconnected."));
3024
+ });
3025
+ });
3026
+ },
3027
+
3028
+ listClients,
3029
+
3030
+ getClient(browserId) {
3031
+ const { id, url, connectedAt } = resolveClient(browserId);
3032
+ return { id, url, connectedAt };
3033
+ },
3034
+
3035
+ /**
3036
+ * Sends a line to every connected page's console, so the developer
3037
+ * watching the deck sees what the model is doing to it. `kind` tells the
3038
+ * page how to present it: the call, what it returned, or how it failed.
3039
+ * A result travels as a value rather than as text, so the console can
3040
+ * render it as something the developer can expand.
3041
+ */
3042
+ announce(kind, { text, value }) {
3043
+ for (const client of clients.values()) {
3044
+ if (!isOpen(client)) {
3045
+ continue;
3046
+ }
3047
+
3048
+ try {
3049
+ client.socket.send(
3050
+ JSON.stringify({ type: "announce", kind, text, value }),
3051
+ );
3052
+ } catch {
3053
+ // A socket mid-close is not worth failing a tool call over.
3054
+ }
3055
+ }
3056
+ },
3057
+
3058
+ evaluate(browserId, code, { timeoutMs } = {}) {
3059
+ return request(
3060
+ resolveClient(browserId),
3061
+ { type: "evaluate", code },
3062
+ {
3063
+ timeoutMs,
3064
+ },
3065
+ );
3066
+ },
3067
+
3068
+ readConsole(browserId, { since, timeoutMs } = {}) {
3069
+ return request(
3070
+ resolveClient(browserId),
3071
+ { type: "read_console", since },
3072
+ {
3073
+ timeoutMs,
3074
+ },
3075
+ );
3076
+ },
3077
+
3078
+ screenshot(browserId, { selector, timeoutMs = 30000 } = {}) {
3079
+ return request(
3080
+ resolveClient(browserId),
3081
+ { type: "screenshot", selector },
3082
+ { timeoutMs },
3083
+ );
3084
+ },
3085
+
3086
+ /**
3087
+ * Runs a command against the deck itself (`get_state`, `navigate`,
3088
+ * `set_mode`, `reload`). These are answered by the React app rather than
3089
+ * the page client, and resolve once the presenter has settled - so a
3090
+ * screenshot taken after one sees the slide it asked for.
3091
+ */
3092
+ deck(browserId, command, args = {}) {
3093
+ return request(
3094
+ resolveClient(browserId),
3095
+ { type: "deck", command, args },
3096
+ { timeoutMs: DECK_TIMEOUT_MS },
3097
+ );
3098
+ },
3099
+ };
3100
+ }
3101
+
3102
+ ;// CONCATENATED MODULE: external "@modelcontextprotocol/sdk/server/streamableHttp.js"
3103
+
3104
+ ;// CONCATENATED MODULE: ./src/backend/mcp/index.mjs
3105
+
3106
+
3107
+ /**
3108
+ * Mounts the MCP endpoint at `/server/api/mcp`, in the SDK's stateless mode: a
3109
+ * fresh server and transport per request, bound to Fastify's raw req/res so
3110
+ * the SDK can write its own SSE framing.
3111
+ */
3112
+ function registerMcpRoutes(config, fastify) {
3113
+ const { log } = config;
3114
+
3115
+ fastify.all(
3116
+ "/server/api/mcp",
3117
+ { config: { internalName: "mcp", listed: false } },
3118
+ async (request, reply) => {
3119
+ // Hands the response lifecycle to the SDK for this request.
3120
+ reply.hijack();
3121
+
3122
+ // Once hijacked, Fastify will not respond for us - not even for a
3123
+ // rejected promise - so an unhandled throw in here would leave the
3124
+ // client waiting forever with nothing in the log.
3125
+ try {
3126
+ // Imported per request so a syntax error or a bad tool definition
3127
+ // is a 500 on this route with the reason logged, rather than a
3128
+ // dev server that will not boot. Node caches the module after the
3129
+ // first success, so this costs one resolve.
3130
+ const { createMcpServer } = await Promise.resolve(/* import() */).then(__webpack_require__.bind(__webpack_require__, 614));
3131
+ const server = await createMcpServer(config);
3132
+ const transport = new __rspack_external__modelcontextprotocol_sdk_server_streamableHttp_js_7ca5b80f.StreamableHTTPServerTransport({
3133
+ sessionIdGenerator: undefined,
3134
+ });
3135
+
3136
+ await server.connect(transport);
3137
+
3138
+ try {
3139
+ await transport.handleRequest(request.raw, reply.raw, request.body);
3140
+ } finally {
3141
+ await transport.close();
3142
+ }
3143
+ } catch (error) {
3144
+ log.error("MCP request failed", error);
3145
+
3146
+ if (reply.raw.headersSent) {
3147
+ reply.raw.destroy();
3148
+ return;
3149
+ }
3150
+
3151
+ reply.raw.writeHead(500, { "content-type": "application/json" }).end(
3152
+ JSON.stringify({
3153
+ jsonrpc: "2.0",
3154
+ id: null,
3155
+ error: { code: -32603, message: "Internal server error" },
3156
+ }),
3157
+ );
3158
+ }
3159
+ },
3160
+ );
3161
+ }
3162
+
3163
+ ;// CONCATENATED MODULE: ./src/backend/server.mjs
3164
+
3165
+
3166
+
3167
+
3168
+
3169
+
3170
+
3171
+
3172
+
3173
+ const SHUTDOWN_TIMEOUT_MS = 2000;
3174
+
3175
+ /* export default */ async function backend_server({ port = 9999, projectDir, distDir }) {
3176
+ const portStatus = await __rspack_external_portscanner["default"].checkPortStatus(port);
3177
+
3178
+ if (portStatus === "open") {
3179
+ external_consola_["default"].info(`Port ${port} is already in use`);
3180
+ return;
3181
+ }
3182
+
3183
+ const fastify = (0,__rspack_external_fastify["default"])();
3184
+
3185
+ await fastify.register(__rspack_external__fastify_cors_424bc224["default"], {
3186
+ origin: "*",
3187
+ allowedHeaders: ["X-Requested-With"],
3188
+ });
3189
+
3190
+ const listedRoutes = [];
3191
+ fastify.addHook("onRoute", (routeOptions) => {
3192
+ if (
3193
+ routeOptions.config?.internalName !== undefined &&
3194
+ routeOptions.config?.listed !== false
3195
+ ) {
3196
+ listedRoutes.push({
3197
+ path: routeOptions.url,
3198
+ internalName: routeOptions.config.internalName,
3199
+ });
3200
+ }
3201
+ });
3202
+
3203
+ const serverURL = `http://localhost:${port}`;
3204
+ const pages = createPageChannel();
3205
+
3206
+ const config = {
3207
+ serverURL,
3208
+ projectDir,
3209
+ distDir,
3210
+ listedRoutes,
3211
+ pages,
3212
+ log: external_consola_["default"].withTag("mcp"),
3213
+ };
3214
+
3215
+ await pages.registerRoutes(fastify);
3216
+ registerMcpRoutes(config, fastify);
3217
+
3218
+ for (const route of Object.values(routes_namespaceObject)) {
3219
+ route(config, fastify);
3220
+ }
3221
+
3222
+ await fastify.listen({ port, host: "localhost" });
3223
+ external_consola_["default"].box("Running CDK. Access server at %s", serverURL);
3224
+
3225
+ process.once("SIGTERM", async () => {
3226
+ external_consola_["default"].info("Shutting down fastify");
3227
+
3228
+ // `fastify.close()` waits for open connections, and a page holds its
3229
+ // socket open until it is closed - so without a deadline the shutdown
3230
+ // never finishes and the port stays bound.
3231
+ await Promise.race([
3232
+ fastify.close(),
3233
+ new Promise((resolve) => {
3234
+ setTimeout(resolve, SHUTDOWN_TIMEOUT_MS);
3235
+ }),
3236
+ ]);
3237
+
3238
+ external_consola_["default"].info("Closed fastify");
3239
+ process.exit();
3240
+ });
3241
+ }
3242
+
3243
+
3244
+ },
3245
+ 488(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) {
3246
+ /* import */ var node_fs__rspack_import_0 = __webpack_require__(24);
3247
+
3248
+
3249
+ function pathExists(file) {
3250
+ try {
3251
+ node_fs__rspack_import_0.accessSync(file, node_fs__rspack_import_0.constants.F_OK);
3252
+ return true;
3253
+ } catch (e) {
3254
+ return false;
3255
+ }
3256
+ }
3257
+
3258
+ __webpack_require__.d(__webpack_exports__, {
3259
+ s: () => (pathExists)
3260
+ });
3261
+
3262
+
3263
+ },
3264
+ 351(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) {
3265
+ function getPortByName(name) {
3266
+ const port = (
3267
+ name
3268
+ .split("")
3269
+ .map((char) => char.charCodeAt())
3270
+ .reduce((num1, num2) => num1 + num2) % 99
3271
+ ).toString();
3272
+
3273
+ const padding = "000".substring(0, 3 - port.length);
3274
+ return parseInt(`9${port}${padding}`, 10);
3275
+ }
3276
+
3277
+ __webpack_require__.d(__webpack_exports__, {
3278
+ u: () => (getPortByName)
3279
+ });
3280
+
3281
+
3282
+ },
3283
+ 577(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) {
3284
+
3285
+ // EXPORTS
3286
+ __webpack_require__.d(__webpack_exports__, {
3287
+ U: () => (/* binding */ getProject)
3288
+ });
3289
+
3290
+ // EXTERNAL MODULE: external "path"
3291
+ var external_path_ = __webpack_require__(928);
3292
+ // EXTERNAL MODULE: external "node:fs/promises"
3293
+ var promises_ = __webpack_require__(455);
3294
+ ;// CONCATENATED MODULE: external "yamljs"
3295
+
3296
+ // EXTERNAL MODULE: ./src/backend/utils/fs.mjs
3297
+ var fs = __webpack_require__(488);
3298
+ ;// CONCATENATED MODULE: ./src/backend/utils/get-project.mjs
3299
+
3300
+
3301
+
3302
+
3303
+
3304
+ async function getProject({ projectDir, distDir }) {
3305
+ const projectFile = external_path_.join(distDir, "project.json");
3306
+
3307
+ if ((0,fs/* .pathExists */.s)(projectFile)) {
3308
+ return JSON.parse(await promises_.readFile(projectFile, "utf8"));
3309
+ } else {
3310
+ const yamlFile = external_path_.join(projectDir, "project.yaml");
3311
+ const file = await promises_.readFile(yamlFile, "utf8");
3312
+ return __rspack_external_yamljs["default"].parse(file);
3313
+ }
3314
+ }
3315
+
3316
+
3317
+ },
3318
+ 560(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) {
3319
+ /* import */ var node_fs__rspack_import_0 = __webpack_require__(24);
3320
+ /* import */ var node_path__rspack_import_1 = __webpack_require__(760);
3321
+ /* import */ var node_url__rspack_import_2 = __webpack_require__(136);
3322
+
3323
+
3324
+
3325
+
3326
+ /**
3327
+ * Finds the folder with the nearest package.json above a module.
3328
+ *
3329
+ * Source runs from src/backend and the published bundle from dist/backend, so
3330
+ * a path relative to the module breaks in one of them.
3331
+ */
3332
+ function findPackageRoot(moduleURL) {
3333
+ let directory = node_path__rspack_import_1.dirname((0,node_url__rspack_import_2.fileURLToPath)(moduleURL));
3334
+
3335
+ while (!(0,node_fs__rspack_import_0.existsSync)(node_path__rspack_import_1.join(directory, "package.json"))) {
3336
+ const parent = node_path__rspack_import_1.dirname(directory);
3337
+
3338
+ if (parent === directory) {
3339
+ throw new Error(`No package.json above ${(0,node_url__rspack_import_2.fileURLToPath)(moduleURL)}`);
3340
+ }
3341
+
3342
+ directory = parent;
3343
+ }
3344
+
3345
+ return directory;
3346
+ }
3347
+
3348
+ __webpack_require__.d(__webpack_exports__, {
3349
+ C: () => (findPackageRoot)
3350
+ });
3351
+
3352
+
3353
+ },
3354
+ 721(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) {
3355
+ /* import */ var fs_promises__rspack_import_0 = __webpack_require__(943);
3356
+ /* import */ var path__rspack_import_1 = __webpack_require__(928);
3357
+
3358
+
3359
+
3360
+ const IGNORED = new Set(["node_modules", ".git"]);
3361
+
3362
+ /**
3363
+ * When the frontend being served was built, against when its source last
3364
+ * changed, for a checkout where the source is newer.
3365
+ *
3366
+ * `dev` serves whatever was last built into `dist`, and nothing it prints says
3367
+ * how old that is. A checkout with unbuilt changes then runs the UI from
3368
+ * before them, which reads as the change having no effect at all.
3369
+ *
3370
+ * Returns null where the bundle is current, and where the source is absent -
3371
+ * an installed copy ships `dist` alone and has nothing to compare against.
3372
+ */
3373
+ async function findStaleBundle(distPath, sourcePath) {
3374
+ const builtAt = await findModifiedTime(path__rspack_import_1.join(distPath, "main.js"));
3375
+ const changedAt = await findNewestChange(sourcePath);
3376
+
3377
+ if (!builtAt || !changedAt || changedAt <= builtAt) {
3378
+ return null;
3379
+ }
3380
+
3381
+ return { builtAt, changedAt };
3382
+ }
3383
+
3384
+ async function findModifiedTime(filename) {
3385
+ try {
3386
+ return (await (0,fs_promises__rspack_import_0.stat)(filename)).mtimeMs;
3387
+ } catch {
3388
+ return null;
3389
+ }
3390
+ }
3391
+
3392
+ async function findNewestChange(directory) {
3393
+ let entries;
3394
+
3395
+ try {
3396
+ entries = await (0,fs_promises__rspack_import_0.readdir)(directory, { withFileTypes: true });
3397
+ } catch {
3398
+ return null;
3399
+ }
3400
+
3401
+ const times = await Promise.all(
3402
+ entries.map((entry) => {
3403
+ const entryPath = path__rspack_import_1.join(directory, entry.name);
3404
+
3405
+ if (entry.isDirectory()) {
3406
+ return IGNORED.has(entry.name) ? null : findNewestChange(entryPath);
3407
+ }
3408
+
3409
+ return findModifiedTime(entryPath);
3410
+ }),
3411
+ );
3412
+
3413
+ return Math.max(0, ...times.filter(Boolean)) || null;
3414
+ }
3415
+
3416
+ __webpack_require__.d(__webpack_exports__, {
3417
+ H: () => (findStaleBundle)
3418
+ });
3419
+
3420
+
3421
+ },
3422
+
3423
+ });
3424
+ // The module cache
3425
+ var __webpack_module_cache__ = {};
3426
+
3427
+ // The require function
3428
+ function __webpack_require__(moduleId) {
3429
+
3430
+ // Check if module is in cache
3431
+ var cachedModule = __webpack_module_cache__[moduleId];
3432
+ if (cachedModule !== undefined) {
3433
+ return cachedModule.exports;
3434
+ }
3435
+ // Create a new module (and put it into the cache)
3436
+ var module = (__webpack_module_cache__[moduleId] = {
3437
+ exports: {}
3438
+ });
3439
+ // Execute the module function
3440
+ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
3441
+
3442
+ // Return the exports of the module
3443
+ return module.exports;
3444
+
3445
+ }
3446
+
3447
+ // expose the module cache
3448
+ __webpack_require__.c = __webpack_module_cache__;
3449
+
3450
+ // webpack/runtime/async_module
3451
+ (() => {
3452
+ var hasSymbol = typeof Symbol === "function";
3453
+ var rspackQueues = hasSymbol ? Symbol("rspack queues") : "__rspack_queues";
3454
+ var rspackExports = __webpack_require__.aE = hasSymbol ? Symbol("rspack exports") : "__webpack_exports__";
3455
+ var rspackError = hasSymbol ? Symbol("rspack error") : "__rspack_error";
3456
+ var rspackDone = hasSymbol ? Symbol("rspack done") : "__rspack_done";
3457
+ var rspackDefer = __webpack_require__.zS = hasSymbol ? Symbol("rspack defer") : "__rspack_defer";
3458
+ __webpack_require__.zT = (asyncDeps) => {
3459
+ var hasUnresolvedAsyncSubgraph = asyncDeps.some((id) => {
3460
+ var cache = __webpack_module_cache__[id];
3461
+ return !cache || cache[rspackDone] === false;
3462
+ });
3463
+ if (hasUnresolvedAsyncSubgraph) {
3464
+ return ({ then(onFulfilled, onRejected) { return Promise.all(asyncDeps.map(__webpack_require__)).then(onFulfilled, onRejected) } });
3465
+ }
3466
+ }
3467
+ var resolveQueue = (queue) => {
3468
+ if (queue && queue.d < 1) {
3469
+ queue.d = 1;
3470
+ queue.forEach((fn) => (fn.r--));
3471
+ queue.forEach((fn) => (fn.r-- ? fn.r++ : fn()));
3472
+ }
3473
+ }
3474
+ var wrapDeps = (deps) => {
3475
+ return deps.map((dep) => {
3476
+ if (dep !== null && typeof dep === "object") {
3477
+ if(!dep[rspackQueues] && dep[rspackDefer]) {
3478
+ var asyncDeps = __webpack_require__.zT(dep[rspackDefer]);
3479
+ if (asyncDeps) {
3480
+ var d = dep;
3481
+ dep = {
3482
+ then(onFulfilled, onRejected) {
3483
+ asyncDeps.then(() => (onFulfilled(d)), onRejected);
3484
+ }
3485
+ };
3486
+ } else return dep;
3487
+ }
3488
+ if (dep[rspackQueues]) return dep;
3489
+ if (dep.then) {
3490
+ var queue = [];
3491
+ queue.d = 0;
3492
+ dep.then((r) => {
3493
+ obj[rspackExports] = r;
3494
+ resolveQueue(queue);
3495
+ },(e) => {
3496
+ obj[rspackError] = e;
3497
+ resolveQueue(queue);
3498
+ });
3499
+ var obj = {};
3500
+ obj[rspackDefer] = false;
3501
+ obj[rspackQueues] = (fn) => (fn(queue));
3502
+ return obj;
3503
+ }
3504
+ }
3505
+ var ret = {};
3506
+ ret[rspackQueues] = () => {};
3507
+ ret[rspackExports] = dep;
3508
+ return ret;
3509
+ });
3510
+ };
3511
+ __webpack_require__.a = (module, body, hasAwait, useModuleExports) => {
3512
+ var queue;
3513
+ hasAwait && ((queue = []).d = -1);
3514
+ var depQueues = new Set();
3515
+ var exports = module.exports;
3516
+ var currentDeps;
3517
+ var outerResolve;
3518
+ var reject;
3519
+ var promise = new Promise((resolve, rej) => {
3520
+ reject = rej;
3521
+ outerResolve = resolve;
3522
+ });
3523
+ promise[rspackExports] = exports;
3524
+ promise[rspackQueues] = (fn) => { queue && fn(queue), depQueues.forEach(fn), promise["catch"](() => {}); };
3525
+ module.exports = promise;
3526
+ var asyncModule = module;
3527
+ if (useModuleExports) {
3528
+ asyncModule = Object.create(module);
3529
+ asyncModule.exports = exports;
3530
+ }
3531
+ var handle = (deps) => {
3532
+ currentDeps = wrapDeps(deps);
3533
+ var fn;
3534
+ var getResult = () => {
3535
+ return currentDeps.map((d) => {
3536
+ if(d[rspackDefer]) return d;
3537
+ if (d[rspackError]) throw d[rspackError];
3538
+ return d[rspackExports];
3539
+ });
3540
+ }
3541
+ var promise = new Promise((resolve) => {
3542
+ fn = () => (resolve(getResult));
3543
+ fn.r = 0;
3544
+ var fnQueue = (q) => (q !== queue && !depQueues.has(q) && (depQueues.add(q), q && !q.d && (fn.r++, q.push(fn))));
3545
+ currentDeps.map((dep) => (dep[rspackDefer] || dep[rspackQueues](fnQueue)));
3546
+ });
3547
+ return fn.r ? promise : getResult();
3548
+ };
3549
+ var done = (err) => ((err ? reject(promise[rspackError] = err) : (useModuleExports && (exports = promise[rspackExports] = asyncModule.exports), outerResolve(exports))), resolveQueue(queue), promise[rspackDone] = true);
3550
+ body(handle, done, asyncModule);
3551
+ queue && queue.d < 0 && (queue.d = 0);
3552
+ };
3553
+
3554
+ })();
3555
+ // webpack/runtime/define_property_getters
3556
+ (() => {
3557
+ __webpack_require__.d = (exports, getters, values) => {
3558
+ var define = (defs, kind) => {
3559
+ for(var key in defs) {
3560
+ if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) {
3561
+ Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] });
3562
+ }
3563
+ }
3564
+ };
3565
+ define(getters, "get");
3566
+ define(values, "value");
3567
+ };
3568
+ })();
3569
+ // webpack/runtime/has_own_property
3570
+ (() => {
3571
+ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
3572
+ })();
3573
+ // webpack/runtime/make_namespace_object
3574
+ (() => {
3575
+ // define __esModule on exports
3576
+ __webpack_require__.r = (exports) => {
3577
+ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
3578
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3579
+ }
3580
+ Object.defineProperty(exports, '__esModule', { value: true });
3581
+ };
3582
+ })();
3583
+ // module cache are used so entry inlining is disabled
3584
+ // startup
3585
+ // Load entry module and return exports
3586
+ var __webpack_exports__ = __webpack_require__(331);