@lemonriver/core 0.1.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{build-f-fM2ZY4.js → build-Bqo69DWP.js} +1 -1
- package/dist/cli/bin.js +4 -4
- package/dist/{config-DO45GU3e.js → config-DJ5rkMMg.js} +3123 -523
- package/dist/{config-B6JaKJM4.d.ts → config-teo3kWz7.d.ts} +6 -2
- package/dist/{dev-CqS2xpgE.js → dev-B2FJD5bJ.js} +2 -2
- package/dist/index.d.ts +3 -3
- package/dist/index.js +4 -3
- package/dist/locale/index.d.ts +5 -2
- package/dist/locale/index.js +2 -2
- package/dist/{preview-BihgMlEl.js → preview-C93BOZL1.js} +1 -1
- package/dist/{types-BjW4glip.d.ts → types-DFK02XVv.d.ts} +120 -27
- package/dist/{update-C_R0ycVC.js → update-DsxZBtwv.js} +154 -90
- package/dist/vite/index.d.ts +1 -1
- package/dist/vite/index.js +1 -1
- package/dist/{zh-tw-Ci0jK8eg.js → zh-tw-DwTAZKa6.js} +1091 -104
- package/package.json +13 -6
- package/skills/apply-comments/SKILL.md +10 -6
- package/skills/create-slide/SKILL.md +2 -0
- package/skills/current-slide/SKILL.md +1 -0
- package/skills/slide-authoring/SKILL.md +31 -1
- package/src/agent/prompt.ts +141 -0
- package/src/agent/provider.ts +123 -0
- package/src/agent/types.ts +151 -0
- package/src/app/app.tsx +7 -18
- package/src/app/assets/open-slide.svg +39 -0
- package/src/app/components/agent/agent-dock.tsx +35 -0
- package/src/app/components/agent/agent-markdown.tsx +45 -0
- package/src/app/components/agent/agent-panel.tsx +695 -0
- package/src/app/components/agent/agent-presence.tsx +74 -0
- package/src/app/components/agent/composer.tsx +120 -0
- package/src/app/components/agent/connect-view.tsx +184 -0
- package/src/app/components/agent/history-view.tsx +136 -0
- package/src/app/components/agent/provider-logo.tsx +34 -0
- package/src/app/components/agent/transcript.tsx +620 -0
- package/src/app/components/asset-view.tsx +6 -6
- package/src/app/components/command/command-menu.tsx +2 -1
- package/src/app/components/command/slide-command-menu.tsx +10 -0
- package/src/app/components/icon-switcher-indicator.tsx +1 -1
- package/src/app/components/inspector/asset-picker-dialog.tsx +7 -5
- package/src/app/components/inspector/comment-layer.tsx +1012 -0
- package/src/app/components/inspector/image-crop-dialog.tsx +1 -5
- package/src/app/components/inspector/inspect-overlay.tsx +2 -39
- package/src/app/components/inspector/inspector-panel.tsx +12 -95
- package/src/app/components/inspector/inspector-provider.tsx +121 -47
- package/src/app/components/panel/editor-sidebar.tsx +85 -16
- package/src/app/components/panel/panel-shell.tsx +2 -2
- package/src/app/components/panel/resize-handle.tsx +129 -0
- package/src/app/components/player.tsx +0 -1
- package/src/app/components/preview-step-host.tsx +16 -0
- package/src/app/components/sidebar/sidebar-footer.tsx +1 -1
- package/src/app/components/sidebar/sidebar.tsx +4 -3
- package/src/app/components/style-panel/style-panel.tsx +3 -2
- package/src/app/components/themes/theme-detail.tsx +4 -2
- package/src/app/components/thumbnail-rail.tsx +77 -29
- package/src/app/favicon.ico +0 -0
- package/src/app/favicon.svg +39 -0
- package/src/app/index.html +2 -1
- package/src/app/lemonriver/agent/lemon.tsx +64 -0
- package/src/app/{components → lemonriver}/board/board-canvas.tsx +154 -23
- package/src/app/{routes/board.tsx → lemonriver/board/board-page.tsx} +63 -25
- package/src/app/{components → lemonriver}/board/board.css +51 -0
- package/src/app/{components → lemonriver}/board/layout.test.ts +53 -1
- package/src/app/{components → lemonriver}/board/layout.ts +51 -3
- package/src/app/lemonriver/board/model/cards.test.ts +239 -0
- package/src/app/lemonriver/board/model/cards.ts +234 -0
- package/src/app/lemonriver/board/model/structure.test.ts +101 -0
- package/src/app/lemonriver/board/model/structure.ts +82 -0
- package/src/app/lemonriver/board/page-node.tsx +481 -0
- package/src/app/lemonriver/board/use-board-cards.ts +210 -0
- package/src/app/{components → lemonriver}/board/use-board-columns.ts +7 -7
- package/src/app/{components → lemonriver}/board/use-page-order.ts +27 -15
- package/src/app/lemonriver/brand/app-icon.svg +44 -0
- package/src/app/lemonriver/brand/apple-touch-icon.png +0 -0
- package/src/app/lemonriver/brand/favicon-32.png +0 -0
- package/src/app/lemonriver/brand/mascot.tsx +59 -0
- package/src/app/lemonriver/brand/mascots/lemon-done.png +0 -0
- package/src/app/lemonriver/brand/mascots/lemon-idle.png +0 -0
- package/src/app/lemonriver/brand/mascots/lemon-needs-you.png +0 -0
- package/src/app/lemonriver/brand/mascots/lemon-thinking.png +0 -0
- package/src/app/lemonriver/brand/mascots/lemon-working.png +0 -0
- package/src/app/lemonriver/chrome/app-chrome.tsx +99 -0
- package/src/app/lemonriver/chrome/nav-row.tsx +34 -0
- package/src/app/lemonriver/chrome/not-found.tsx +34 -0
- package/src/app/lemonriver/chrome/sidebar-extras.tsx +57 -0
- package/src/app/lemonriver/chrome/use-slot.ts +23 -0
- package/src/app/lemonriver/features.test.ts +29 -0
- package/src/app/lemonriver/features.ts +26 -0
- package/src/app/lemonriver/feedback/export.ts +7 -0
- package/src/app/lemonriver/feedback/lemon-empty.tsx +54 -0
- package/src/app/lemonriver/feedback/offline-banner.tsx +41 -0
- package/src/app/lemonriver/feedback/pending-toast.test.ts +44 -0
- package/src/app/lemonriver/feedback/pending-toast.ts +39 -0
- package/src/app/lemonriver/feedback/toaster.tsx +34 -0
- package/src/app/lemonriver/feedback/upload.test.ts +26 -0
- package/src/app/lemonriver/feedback/upload.ts +19 -0
- package/src/app/lemonriver/home/brief-card.tsx +63 -0
- package/src/app/lemonriver/home/brief.test.ts +38 -0
- package/src/app/lemonriver/home/brief.ts +34 -0
- package/src/app/lemonriver/home/controls.tsx +93 -0
- package/src/app/lemonriver/home/deck-card.tsx +183 -0
- package/src/app/lemonriver/home/dialogs.tsx +292 -0
- package/src/app/lemonriver/home/home-page.tsx +335 -0
- package/src/app/lemonriver/home/sorting.test.ts +24 -0
- package/src/app/lemonriver/home/sorting.ts +59 -0
- package/src/app/lemonriver/home/time.test.ts +33 -0
- package/src/app/lemonriver/home/time.ts +33 -0
- package/src/app/lemonriver/home/use-deck-times.ts +27 -0
- package/src/app/lemonriver/home/use-delayed.ts +15 -0
- package/src/app/lemonriver/routes.test.tsx +37 -0
- package/src/app/lemonriver/routes.tsx +38 -0
- package/src/app/lemonriver/settings/settings-page.tsx +103 -0
- package/src/app/lemonriver/slide-extensions.tsx +73 -0
- package/src/app/lemonriver/text/all.ts +19 -0
- package/src/app/lemonriver/text/en.ts +106 -0
- package/src/app/lemonriver/text/es.ts +108 -0
- package/src/app/lemonriver/text/index.ts +9 -0
- package/src/app/lemonriver/text/ja.ts +106 -0
- package/src/app/lemonriver/text/text.test.ts +57 -0
- package/src/app/lemonriver/text/types.ts +111 -0
- package/src/app/lemonriver/text/zh-cn.ts +101 -0
- package/src/app/lemonriver/text/zh-tw.ts +101 -0
- package/src/app/lemonriver/theme/app.css +288 -0
- package/src/app/lemonriver/theme/controls.css +463 -0
- package/src/app/lemonriver/theme/index.css +3 -0
- package/src/app/lemonriver/theme/motion.ts +52 -0
- package/src/app/lemonriver/theme/pages.test.ts +66 -0
- package/src/app/lemonriver/theme/pages.ts +56 -0
- package/src/app/lemonriver/theme/theme-menu.tsx +64 -0
- package/src/app/lemonriver/theme/themes.test.ts +18 -0
- package/src/app/lemonriver/theme/themes.ts +16 -0
- package/src/app/lemonriver/theme/tokens.css +226 -0
- package/src/app/lemonriver/theme/use-theme.tsx +49 -0
- package/src/app/lemonriver/trash/api.test.ts +19 -0
- package/src/app/lemonriver/trash/api.ts +77 -0
- package/src/app/lemonriver/trash/trash-page.tsx +131 -0
- package/src/app/lib/agent/use-agent.ts +543 -0
- package/src/app/lib/inspector/freeze-motion.ts +61 -0
- package/src/app/lib/inspector/use-comments.ts +32 -3
- package/src/app/lib/locale-store.ts +6 -1
- package/src/app/lib/pptx/raster.ts +1 -1
- package/src/app/lib/print-ready.ts +9 -6
- package/src/app/lib/use-auto-grow.ts +15 -0
- package/src/app/lib/utils.ts +4 -0
- package/src/app/main.tsx +8 -1
- package/src/app/routes/home-shell.tsx +4 -2
- package/src/app/routes/home.tsx +43 -7
- package/src/app/routes/presenter.tsx +1 -16
- package/src/app/routes/preview.tsx +169 -0
- package/src/app/routes/slide.tsx +232 -188
- package/src/app/styles.css +235 -80
- package/src/editing/placeholder-id.ts +1 -0
- package/src/locale/en.ts +113 -26
- package/src/locale/es.ts +658 -0
- package/src/locale/index.ts +1 -0
- package/src/locale/ja.ts +106 -26
- package/src/locale/types.ts +119 -28
- package/src/locale/zh-cn.ts +106 -28
- package/src/locale/zh-tw.ts +106 -28
- package/src/app/assets/open-slide.png +0 -0
- package/src/app/components/board/page-node.tsx +0 -204
- package/src/app/components/inspector/comment-widget.tsx +0 -119
|
@@ -1,18 +1,2840 @@
|
|
|
1
1
|
import { n as defaultDesign } from "./design-Cpqx7SJs.js";
|
|
2
|
-
import { A as
|
|
2
|
+
import { A as reorderNotesArrayInSource, B as CONFIG_FILES, C as duplicatePageInDefaultExportInSource, D as removePageFromDefaultExportInSource, E as removeNotesElementInSource, F as validateSlideName, H as isFrameworkSpecifier, I as declaredFrameworkSpecifier, L as isLoopbackRequest, M as rmSlideDir, N as slugifyTitle, O as renameSlideDir, P as updateMetaTitleInSource, R as validateMutationRequest, S as duplicateNotesElementInSource, T as readMetaTitleInSource, _ as writeManifest, a as json, b as SLIDE_ID_RE, c as readSlideSource, d as foldersManifestPath, f as newFolderId, g as validateReorder, h as validateName, i as BodyTooLargeError, j as resolveSlideEntry, k as reorderDefaultExportPagesInSource, l as resolveSlideEntryPath, m as validateIcon, n as registerUpdateRoutes, o as makeContext, p as readManifest, r as runCommand, s as readBody, t as detectPackageManager, u as FOLDER_ID_RE, v as shortId, w as duplicateSlideDir, x as createBlankSlideDir } from "./update-DsxZBtwv.js";
|
|
3
3
|
import { createRequire } from "node:module";
|
|
4
4
|
import path from "node:path";
|
|
5
|
-
import { fileURLToPath } from "node:url";
|
|
6
|
-
import { existsSync, readFileSync } from "node:fs";
|
|
5
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
6
|
+
import { existsSync, readFileSync, rmSync, statSync } from "node:fs";
|
|
7
|
+
import { spawn } from "node:child_process";
|
|
7
8
|
import fs from "node:fs/promises";
|
|
8
9
|
import { parse } from "@babel/parser";
|
|
9
|
-
import { randomUUID } from "node:crypto";
|
|
10
|
+
import { randomBytes, randomUUID } from "node:crypto";
|
|
10
11
|
import tailwindcss from "@tailwindcss/vite";
|
|
11
12
|
import react from "@vitejs/plugin-react";
|
|
12
|
-
import * as t from "@babel/types";
|
|
13
|
-
import { isJSXElement, isJSXFragment } from "@babel/types";
|
|
14
13
|
import fg from "fast-glob";
|
|
15
14
|
import { loadConfigFromFile, normalizePath } from "vite";
|
|
15
|
+
import os from "node:os";
|
|
16
|
+
import * as t from "@babel/types";
|
|
17
|
+
import { isJSXElement, isJSXFragment } from "@babel/types";
|
|
18
|
+
//#region src/app/lemonriver/theme/pages.ts
|
|
19
|
+
/**
|
|
20
|
+
* BRAND_PAGES as a path pattern, for the pre-paint script, which runs before
|
|
21
|
+
* any module loads. pages.test.ts keeps the two in step.
|
|
22
|
+
*/
|
|
23
|
+
const BRAND_PATH_SOURCE = "^/(themes(/.*)?|assets|settings|trash)?/*$";
|
|
24
|
+
/** Agent screenshots and thumbnails render through this route; nothing may cover it. */
|
|
25
|
+
const PREVIEW_PATH_SOURCE = "^/s/[^/]+/preview/*$";
|
|
26
|
+
const REDUCE_MOTION_KEY = "lemonriver:reduce-motion";
|
|
27
|
+
const SPLASH_ID = "lr-splash";
|
|
28
|
+
//#endregion
|
|
29
|
+
//#region src/lemonriver/vite-plugin.ts
|
|
30
|
+
/**
|
|
31
|
+
* Runs before the bundle: marks <html> for our styles, picks the lime look on
|
|
32
|
+
* the pages that wear it, and shows the splash until the app mounts. The
|
|
33
|
+
* preview route renders agent screenshots, so it gets no splash. The official
|
|
34
|
+
* script above it has already toggled `dark`.
|
|
35
|
+
*/
|
|
36
|
+
function prePaintScript(base) {
|
|
37
|
+
return [
|
|
38
|
+
"(function(){",
|
|
39
|
+
"var d=document.documentElement;d.setAttribute('data-lr-app','');",
|
|
40
|
+
`var b=${JSON.stringify(base.replace(/\/+$/, ""))},p=location.pathname;if(b&&p.indexOf(b)===0)p=p.slice(b.length)||'/';`,
|
|
41
|
+
`var brand=new RegExp(${JSON.stringify(BRAND_PATH_SOURCE)}).test(p);`,
|
|
42
|
+
`var preview=new RegExp(${JSON.stringify(PREVIEW_PATH_SOURCE)}).test(p);`,
|
|
43
|
+
"var theme=null;try{theme=localStorage.getItem('theme');",
|
|
44
|
+
`if(localStorage.getItem(${JSON.stringify(REDUCE_MOTION_KEY)})==='1')d.setAttribute('data-lr-reduce-motion','');}catch(e){}`,
|
|
45
|
+
"if(theme==='lime'){d.classList.remove('dark');d.classList.add('lime');d.style.colorScheme='light';}",
|
|
46
|
+
"if(brand)d.setAttribute('data-lr-brand','');",
|
|
47
|
+
"if(!preview)d.setAttribute('data-lr-splash','');",
|
|
48
|
+
"})();"
|
|
49
|
+
].join("");
|
|
50
|
+
}
|
|
51
|
+
const SPLASH_STYLE = `
|
|
52
|
+
#${SPLASH_ID}{display:none}
|
|
53
|
+
html[data-lr-splash] #${SPLASH_ID}{position:fixed;inset:0;z-index:2147483000;display:grid;place-items:center;pointer-events:none;
|
|
54
|
+
background:linear-gradient(160deg,#eef56a 0%,#c9e23f 40%,#9bc929 100%);color:#12300f;
|
|
55
|
+
font:700 28px/1.2 -apple-system,BlinkMacSystemFont,"SF Pro Display","Inter","PingFang SC","Hiragino Sans GB","Microsoft YaHei",sans-serif;
|
|
56
|
+
opacity:0;animation:lr-splash-in 240ms cubic-bezier(.2,.8,.2,1) 200ms forwards;transition:opacity 240ms cubic-bezier(.2,.8,.2,1)}
|
|
57
|
+
#${SPLASH_ID} div{display:flex;align-items:center;gap:14px}
|
|
58
|
+
#${SPLASH_ID} img{width:56px;height:56px}
|
|
59
|
+
#${SPLASH_ID}[data-leaving]{opacity:0!important;animation:none}
|
|
60
|
+
@keyframes lr-splash-in{to{opacity:1}}
|
|
61
|
+
@media (prefers-reduced-motion: reduce){html[data-lr-splash] #${SPLASH_ID}{animation:none;opacity:1;transition:none}}
|
|
62
|
+
html[data-lr-reduce-motion] #${SPLASH_ID}{animation:none;opacity:1;transition:none}
|
|
63
|
+
`;
|
|
64
|
+
function lemonRiverAppPlugin() {
|
|
65
|
+
let base = "/";
|
|
66
|
+
return {
|
|
67
|
+
name: "lemonriver:app",
|
|
68
|
+
configResolved(config) {
|
|
69
|
+
base = config.base;
|
|
70
|
+
},
|
|
71
|
+
transformIndexHtml: {
|
|
72
|
+
order: "pre",
|
|
73
|
+
handler(html) {
|
|
74
|
+
return {
|
|
75
|
+
html,
|
|
76
|
+
tags: [
|
|
77
|
+
{
|
|
78
|
+
tag: "link",
|
|
79
|
+
attrs: {
|
|
80
|
+
rel: "apple-touch-icon",
|
|
81
|
+
href: "./lemonriver/brand/apple-touch-icon.png"
|
|
82
|
+
},
|
|
83
|
+
injectTo: "head"
|
|
84
|
+
},
|
|
85
|
+
{
|
|
86
|
+
tag: "style",
|
|
87
|
+
children: SPLASH_STYLE,
|
|
88
|
+
injectTo: "head"
|
|
89
|
+
},
|
|
90
|
+
{
|
|
91
|
+
tag: "script",
|
|
92
|
+
children: prePaintScript(base),
|
|
93
|
+
injectTo: "head"
|
|
94
|
+
},
|
|
95
|
+
{
|
|
96
|
+
tag: "div",
|
|
97
|
+
attrs: {
|
|
98
|
+
id: SPLASH_ID,
|
|
99
|
+
"aria-hidden": "true"
|
|
100
|
+
},
|
|
101
|
+
children: [{
|
|
102
|
+
tag: "div",
|
|
103
|
+
children: [{
|
|
104
|
+
tag: "img",
|
|
105
|
+
attrs: {
|
|
106
|
+
src: "./lemonriver/brand/app-icon.svg",
|
|
107
|
+
alt: ""
|
|
108
|
+
}
|
|
109
|
+
}, {
|
|
110
|
+
tag: "span",
|
|
111
|
+
children: "LemonRiver"
|
|
112
|
+
}]
|
|
113
|
+
}],
|
|
114
|
+
injectTo: "body-prepend"
|
|
115
|
+
}
|
|
116
|
+
]
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
//#endregion
|
|
123
|
+
//#region src/app/lemonriver/board/model/cards.ts
|
|
124
|
+
const CARD_STATUSES = [
|
|
125
|
+
"todo",
|
|
126
|
+
"doing",
|
|
127
|
+
"review",
|
|
128
|
+
"done"
|
|
129
|
+
];
|
|
130
|
+
const TITLE_MAX$1 = 80;
|
|
131
|
+
const MEMO_MAX = 2e3;
|
|
132
|
+
function isCardStatus(value) {
|
|
133
|
+
return typeof value === "string" && CARD_STATUSES.includes(value);
|
|
134
|
+
}
|
|
135
|
+
function cleanCard(raw) {
|
|
136
|
+
if (!raw || typeof raw !== "object") return null;
|
|
137
|
+
const { title, status, memo } = raw;
|
|
138
|
+
const card = {};
|
|
139
|
+
if (typeof title === "string" && title.trim()) card.title = title.trim().slice(0, TITLE_MAX$1);
|
|
140
|
+
if (isCardStatus(status)) card.status = status;
|
|
141
|
+
if (typeof memo === "string" && memo.trim()) card.memo = memo.trim().slice(0, MEMO_MAX);
|
|
142
|
+
return Object.keys(card).length > 0 ? card : null;
|
|
143
|
+
}
|
|
144
|
+
function sanitizeCards(raw) {
|
|
145
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
|
|
146
|
+
const cards = {};
|
|
147
|
+
for (const [key, value] of Object.entries(raw)) {
|
|
148
|
+
const card = cleanCard(value);
|
|
149
|
+
if (key && card) cards[key] = card;
|
|
150
|
+
}
|
|
151
|
+
return cards;
|
|
152
|
+
}
|
|
153
|
+
const sameLink = (link, a, b) => link.a === a && link.b === b || link.a === b && link.b === a;
|
|
154
|
+
function linkCards(links, a, b) {
|
|
155
|
+
if (!a || !b || a === b || links.some((link) => sameLink(link, a, b))) return links;
|
|
156
|
+
return [...links, {
|
|
157
|
+
a,
|
|
158
|
+
b
|
|
159
|
+
}];
|
|
160
|
+
}
|
|
161
|
+
function sanitizeLinks(raw) {
|
|
162
|
+
if (!Array.isArray(raw)) return [];
|
|
163
|
+
return raw.reduce((links, item) => {
|
|
164
|
+
const { a, b } = item ?? {};
|
|
165
|
+
return typeof a === "string" && typeof b === "string" ? linkCards(links, a, b) : links;
|
|
166
|
+
}, []);
|
|
167
|
+
}
|
|
168
|
+
//#endregion
|
|
169
|
+
//#region src/app/lemonriver/board/model/structure.ts
|
|
170
|
+
function sanitizeStructure(parsed) {
|
|
171
|
+
if (!parsed || typeof parsed !== "object") return null;
|
|
172
|
+
const columns = parsed.columns;
|
|
173
|
+
if (!Array.isArray(columns)) return null;
|
|
174
|
+
const cleaned = columns.flatMap((column) => {
|
|
175
|
+
if (!column || typeof column !== "object") return [];
|
|
176
|
+
const { title, size } = column;
|
|
177
|
+
if (typeof size !== "number" || !Number.isInteger(size) || size < 0) return [];
|
|
178
|
+
return [{
|
|
179
|
+
title: typeof title === "string" ? title : "",
|
|
180
|
+
size
|
|
181
|
+
}];
|
|
182
|
+
});
|
|
183
|
+
return cleaned.length > 0 ? { columns: cleaned } : null;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Keeps a stored structure usable after the deck changed behind the board's
|
|
187
|
+
* back: pages added outside the board join the last column, and pages deleted
|
|
188
|
+
* outside it come off the end.
|
|
189
|
+
*/
|
|
190
|
+
function reconcileColumns(columns, pageCount) {
|
|
191
|
+
if (pageCount <= 0) return [];
|
|
192
|
+
const kept = columns.map((column) => ({ ...column }));
|
|
193
|
+
if (kept.length === 0) return [{
|
|
194
|
+
title: "",
|
|
195
|
+
size: pageCount
|
|
196
|
+
}];
|
|
197
|
+
let total = kept.reduce((sum, column) => sum + column.size, 0);
|
|
198
|
+
if (total === pageCount) return kept;
|
|
199
|
+
if (total < pageCount) {
|
|
200
|
+
kept[kept.length - 1].size += pageCount - total;
|
|
201
|
+
return kept;
|
|
202
|
+
}
|
|
203
|
+
for (let i = kept.length - 1; i >= 0 && total > pageCount; i--) {
|
|
204
|
+
const drop = Math.min(kept[i].size, total - pageCount);
|
|
205
|
+
kept[i].size -= drop;
|
|
206
|
+
total -= drop;
|
|
207
|
+
}
|
|
208
|
+
while (kept.length > 1 && kept[kept.length - 1].size === 0) kept.pop();
|
|
209
|
+
return kept;
|
|
210
|
+
}
|
|
211
|
+
//#endregion
|
|
212
|
+
//#region src/lemonriver/board/page-entries.ts
|
|
213
|
+
/**
|
|
214
|
+
* The deck's page array as written, one entry per page, with whitespace
|
|
215
|
+
* collapsed so reformatting the file keeps every entry the same. `null` when
|
|
216
|
+
* the array cannot be read one entry per page: a spread stands for any number
|
|
217
|
+
* of pages, and a default export that is not an array literal hides them.
|
|
218
|
+
*/
|
|
219
|
+
function defaultExportEntriesInSource(source) {
|
|
220
|
+
let body;
|
|
221
|
+
try {
|
|
222
|
+
body = parse(source, {
|
|
223
|
+
sourceType: "module",
|
|
224
|
+
plugins: ["typescript", "jsx"],
|
|
225
|
+
errorRecovery: true
|
|
226
|
+
}).program.body;
|
|
227
|
+
} catch {
|
|
228
|
+
return null;
|
|
229
|
+
}
|
|
230
|
+
for (const node of body) {
|
|
231
|
+
if (node.type !== "ExportDefaultDeclaration") continue;
|
|
232
|
+
let inner = node.declaration;
|
|
233
|
+
while (inner.type === "TSAsExpression" || inner.type === "TSSatisfiesExpression") inner = inner.expression;
|
|
234
|
+
if (inner.type !== "ArrayExpression") return null;
|
|
235
|
+
const entries = [];
|
|
236
|
+
for (const element of inner.elements) {
|
|
237
|
+
if (!element || element.type === "SpreadElement") return null;
|
|
238
|
+
if (element.start == null || element.end == null) return null;
|
|
239
|
+
entries.push(source.slice(element.start, element.end).replace(/\s+/g, " "));
|
|
240
|
+
}
|
|
241
|
+
return entries;
|
|
242
|
+
}
|
|
243
|
+
return null;
|
|
244
|
+
}
|
|
245
|
+
//#endregion
|
|
246
|
+
//#region src/lemonriver/board/page-insert.ts
|
|
247
|
+
function findDefaultExportArray(source) {
|
|
248
|
+
let ast;
|
|
249
|
+
try {
|
|
250
|
+
ast = parse(source, {
|
|
251
|
+
sourceType: "module",
|
|
252
|
+
plugins: ["typescript", "jsx"],
|
|
253
|
+
errorRecovery: true
|
|
254
|
+
});
|
|
255
|
+
} catch {
|
|
256
|
+
return null;
|
|
257
|
+
}
|
|
258
|
+
const body = ast.program?.body ?? [];
|
|
259
|
+
for (const node of body) {
|
|
260
|
+
if (node.type !== "ExportDefaultDeclaration") continue;
|
|
261
|
+
let inner = node.declaration;
|
|
262
|
+
while (inner && (inner.type === "TSAsExpression" || inner.type === "TSSatisfiesExpression")) inner = inner.expression;
|
|
263
|
+
if (inner?.type !== "ArrayExpression") return null;
|
|
264
|
+
const arrayStart = inner.start;
|
|
265
|
+
const arrayEnd = inner.end;
|
|
266
|
+
const rawElements = inner.elements ?? [];
|
|
267
|
+
const elements = [];
|
|
268
|
+
for (const el of rawElements) {
|
|
269
|
+
if (!el || typeof el.start !== "number" || typeof el.end !== "number") return null;
|
|
270
|
+
elements.push({
|
|
271
|
+
start: el.start,
|
|
272
|
+
end: el.end
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
return {
|
|
276
|
+
elements,
|
|
277
|
+
arrayStart,
|
|
278
|
+
arrayEnd,
|
|
279
|
+
statementStart: node.start
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
return null;
|
|
283
|
+
}
|
|
284
|
+
function findNotesArray(source) {
|
|
285
|
+
let ast;
|
|
286
|
+
try {
|
|
287
|
+
ast = parse(source, {
|
|
288
|
+
sourceType: "module",
|
|
289
|
+
plugins: ["typescript", "jsx"],
|
|
290
|
+
errorRecovery: true
|
|
291
|
+
});
|
|
292
|
+
} catch {
|
|
293
|
+
return "invalid";
|
|
294
|
+
}
|
|
295
|
+
const body = ast.program?.body ?? [];
|
|
296
|
+
for (const stmt of body) {
|
|
297
|
+
if (stmt.type !== "ExportNamedDeclaration") continue;
|
|
298
|
+
const decl = stmt.declaration;
|
|
299
|
+
if (decl?.type !== "VariableDeclaration") continue;
|
|
300
|
+
const declarations = decl.declarations ?? [];
|
|
301
|
+
for (const d of declarations) {
|
|
302
|
+
const id = d.id;
|
|
303
|
+
if (id?.type !== "Identifier" || id.name !== "notes") continue;
|
|
304
|
+
const init = d.init;
|
|
305
|
+
if (init?.type !== "ArrayExpression") return "invalid";
|
|
306
|
+
const arrayStart = init.start;
|
|
307
|
+
const arrayEnd = init.end;
|
|
308
|
+
if (typeof arrayStart !== "number" || typeof arrayEnd !== "number") return "invalid";
|
|
309
|
+
const rawElements = init.elements ?? [];
|
|
310
|
+
const elementTexts = [];
|
|
311
|
+
for (const el of rawElements) {
|
|
312
|
+
if (el === null) {
|
|
313
|
+
elementTexts.push("undefined");
|
|
314
|
+
continue;
|
|
315
|
+
}
|
|
316
|
+
if (el.type === "SpreadElement") return "invalid";
|
|
317
|
+
const start = el.start;
|
|
318
|
+
const end = el.end;
|
|
319
|
+
if (typeof start !== "number" || typeof end !== "number") return "invalid";
|
|
320
|
+
elementTexts.push(source.slice(start, end));
|
|
321
|
+
}
|
|
322
|
+
return {
|
|
323
|
+
arrayStart,
|
|
324
|
+
arrayEnd,
|
|
325
|
+
elementTexts
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
return null;
|
|
330
|
+
}
|
|
331
|
+
function rebuildNotesArray(source, arrayStart, arrayEnd, elements) {
|
|
332
|
+
const trimmed = elements.slice();
|
|
333
|
+
while (trimmed.length > 0 && trimmed[trimmed.length - 1] === "undefined") trimmed.pop();
|
|
334
|
+
const replacement = trimmed.length === 0 ? "[]" : `[\n${trimmed.map((s) => ` ${s},`).join("\n")}\n]`;
|
|
335
|
+
if (replacement === source.slice(arrayStart, arrayEnd)) return source;
|
|
336
|
+
return source.slice(0, arrayStart) + replacement + source.slice(arrayEnd);
|
|
337
|
+
}
|
|
338
|
+
function chooseInsertSeparator(prefix, existingSeparators) {
|
|
339
|
+
const sample = existingSeparators.find((s) => s.includes(","));
|
|
340
|
+
if (sample) return sample;
|
|
341
|
+
if (prefix.includes("\n")) {
|
|
342
|
+
const m = prefix.match(/\n([ \t]*)$/);
|
|
343
|
+
return `,\n${m ? m[1] : " "}`;
|
|
344
|
+
}
|
|
345
|
+
return ", ";
|
|
346
|
+
}
|
|
347
|
+
/** Separator slots for an array that gained an element at `index`. */
|
|
348
|
+
function separatorsAroundInsert(separators, index, count, insertSep) {
|
|
349
|
+
const out = [];
|
|
350
|
+
for (let i = 0; i < count - 1; i++) if (i === index) out.push(insertSep);
|
|
351
|
+
else if (i === index - 1) out.push(separators[index - 1] ?? insertSep);
|
|
352
|
+
else out.push(separators[i > index ? i - 1 : i] ?? insertSep);
|
|
353
|
+
return out;
|
|
354
|
+
}
|
|
355
|
+
/** Rebuild `[...]` with `text` sitting at `index`, reusing the author's separators. */
|
|
356
|
+
function insertIntoDefaultExportArray(source, found, index, text) {
|
|
357
|
+
const { elements, arrayStart, arrayEnd } = found;
|
|
358
|
+
const n = elements.length;
|
|
359
|
+
const prefix = source.slice(arrayStart, elements[0].start);
|
|
360
|
+
const suffix = source.slice(elements[n - 1].end, arrayEnd);
|
|
361
|
+
const separators = [];
|
|
362
|
+
for (let i = 0; i < n - 1; i++) separators.push(source.slice(elements[i].end, elements[i + 1].start));
|
|
363
|
+
const texts = elements.map((el) => source.slice(el.start, el.end));
|
|
364
|
+
texts.splice(index, 0, text);
|
|
365
|
+
const insertSep = chooseInsertSeparator(prefix, separators);
|
|
366
|
+
const seps = separatorsAroundInsert(separators, index, texts.length, insertSep);
|
|
367
|
+
let rebuilt = prefix + texts[0];
|
|
368
|
+
for (let i = 1; i < texts.length; i++) rebuilt += seps[i - 1] + texts[i];
|
|
369
|
+
rebuilt += suffix;
|
|
370
|
+
return source.slice(0, arrayStart) + rebuilt + source.slice(arrayEnd);
|
|
371
|
+
}
|
|
372
|
+
function chooseBlankPageName(source) {
|
|
373
|
+
const used = new Set(source.match(/[A-Za-z_$][\w$]*/g) ?? []);
|
|
374
|
+
for (let i = 1;; i++) {
|
|
375
|
+
const name = `NewPage${i}`;
|
|
376
|
+
if (!used.has(name)) return name;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
/**
|
|
380
|
+
* Insert a brand-new blank page at `index`, declaring its component above the
|
|
381
|
+
* default export and adding it to the array. Unlike duplication, nothing is
|
|
382
|
+
* copied: the page is an empty full-bleed surface for the author to build on.
|
|
383
|
+
*
|
|
384
|
+
* Returns `null` when the default export isn't an array literal or `index` is
|
|
385
|
+
* past the end of the deck.
|
|
386
|
+
*/
|
|
387
|
+
function insertBlankPageInDefaultExportInSource(source, index) {
|
|
388
|
+
const found = findDefaultExportArray(source);
|
|
389
|
+
if (!found) return null;
|
|
390
|
+
const n = found.elements.length;
|
|
391
|
+
if (!Number.isInteger(index) || index < 0 || index > n) return null;
|
|
392
|
+
const name = chooseBlankPageName(source);
|
|
393
|
+
const withArray = insertIntoDefaultExportArray(source, found, index, name);
|
|
394
|
+
const before = withArray.slice(0, found.statementStart);
|
|
395
|
+
const gap = before.endsWith("\n\n") ? "" : before.endsWith("\n") ? "\n" : "\n\n";
|
|
396
|
+
return before + `const ${name} = () => (\n <div style={{ width: '100%', height: '100%', background: '#ffffff' }} />\n);\n` + gap + withArray.slice(found.statementStart);
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* Insert an empty note slot at `index` so `notes` stays aligned with the pages
|
|
400
|
+
* after a page is inserted. Trailing empty slots are dropped again by
|
|
401
|
+
* {@link rebuildNotesArray}, which is correct: an absent note is `undefined`.
|
|
402
|
+
*/
|
|
403
|
+
function insertNotesElementInSource(source, index) {
|
|
404
|
+
if (!Number.isInteger(index) || index < 0) return null;
|
|
405
|
+
const found = findNotesArray(source);
|
|
406
|
+
if (found === "invalid") return null;
|
|
407
|
+
if (found === null) return source;
|
|
408
|
+
const { arrayStart, arrayEnd, elementTexts } = found;
|
|
409
|
+
if (index > elementTexts.length) return source;
|
|
410
|
+
const next = elementTexts.slice();
|
|
411
|
+
next.splice(index, 0, "undefined");
|
|
412
|
+
return rebuildNotesArray(source, arrayStart, arrayEnd, next);
|
|
413
|
+
}
|
|
414
|
+
//#endregion
|
|
415
|
+
//#region src/lemonriver/board/store.ts
|
|
416
|
+
function boardStructurePath(userCwd, slideId) {
|
|
417
|
+
return path.join(userCwd, ".open-slide", "board", `${slideId}.json`);
|
|
418
|
+
}
|
|
419
|
+
/** The whole board file. Columns, cards and links each own one field of it. */
|
|
420
|
+
async function readBoardFile(file) {
|
|
421
|
+
try {
|
|
422
|
+
const parsed = JSON.parse(await fs.readFile(file, "utf8"));
|
|
423
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
424
|
+
} catch {
|
|
425
|
+
return {};
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
async function readBoardStructure(file) {
|
|
429
|
+
return sanitizeStructure(await readBoardFile(file));
|
|
430
|
+
}
|
|
431
|
+
const pending = /* @__PURE__ */ new Map();
|
|
432
|
+
/**
|
|
433
|
+
* Rewrites the fields `fields` names and keeps every other one. Updates to the
|
|
434
|
+
* same file run one after another: the columns and the cards are saved by
|
|
435
|
+
* separate requests, and two read-modify-writes racing would drop one of them.
|
|
436
|
+
*/
|
|
437
|
+
function updateBoardFile(file, fields) {
|
|
438
|
+
const run = (pending.get(file) ?? Promise.resolve()).catch(() => void 0).then(async () => {
|
|
439
|
+
const current = await readBoardFile(file);
|
|
440
|
+
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
441
|
+
await fs.writeFile(file, `${JSON.stringify({
|
|
442
|
+
...current,
|
|
443
|
+
...fields
|
|
444
|
+
}, null, 2)}\n`, "utf8");
|
|
445
|
+
});
|
|
446
|
+
pending.set(file, run);
|
|
447
|
+
run.finally(() => {
|
|
448
|
+
if (pending.get(file) === run) pending.delete(file);
|
|
449
|
+
}).catch(() => void 0);
|
|
450
|
+
return run;
|
|
451
|
+
}
|
|
452
|
+
async function writeBoardStructure(file, structure) {
|
|
453
|
+
await updateBoardFile(file, { columns: structure.columns });
|
|
454
|
+
}
|
|
455
|
+
//#endregion
|
|
456
|
+
//#region src/lemonriver/board/routes.ts
|
|
457
|
+
function registerBoardRoutes(server, ctx) {
|
|
458
|
+
server.middlewares.use("/__board", async (req, res, next) => {
|
|
459
|
+
const url = new URL(req.url ?? "/", "http://local");
|
|
460
|
+
const method = req.method ?? "GET";
|
|
461
|
+
try {
|
|
462
|
+
if (method === "GET" && url.pathname === "/") {
|
|
463
|
+
const slideId = url.searchParams.get("slideId") ?? "";
|
|
464
|
+
if (!resolveSlideEntryPath(ctx, slideId)) return json(res, 400, { error: "invalid slideId" });
|
|
465
|
+
const stored = await readBoardStructure(boardStructurePath(ctx.userCwd, slideId));
|
|
466
|
+
if (!stored) return json(res, 200, { columns: null });
|
|
467
|
+
const pages = Number(url.searchParams.get("pages") ?? "0");
|
|
468
|
+
const columns = pages > 0 ? reconcileColumns(stored.columns, pages) : stored.columns;
|
|
469
|
+
return json(res, 200, { columns });
|
|
470
|
+
}
|
|
471
|
+
if (method === "PUT" && url.pathname === "/") {
|
|
472
|
+
const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
|
|
473
|
+
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
474
|
+
const body = await readBody(req);
|
|
475
|
+
const slideId = body.slideId ?? "";
|
|
476
|
+
if (!resolveSlideEntryPath(ctx, slideId)) return json(res, 400, { error: "invalid slideId" });
|
|
477
|
+
if (!Array.isArray(body.columns)) return json(res, 400, { error: "missing columns" });
|
|
478
|
+
const structure = { columns: body.columns.flatMap((column) => {
|
|
479
|
+
const { title, size } = column ?? {};
|
|
480
|
+
if (typeof size !== "number" || !Number.isInteger(size) || size < 0) return [];
|
|
481
|
+
return [{
|
|
482
|
+
title: typeof title === "string" ? title : "",
|
|
483
|
+
size
|
|
484
|
+
}];
|
|
485
|
+
}) };
|
|
486
|
+
if (structure.columns.length === 0) return json(res, 400, { error: "no usable columns" });
|
|
487
|
+
await writeBoardStructure(boardStructurePath(ctx.userCwd, slideId), structure);
|
|
488
|
+
return json(res, 200, { ok: true });
|
|
489
|
+
}
|
|
490
|
+
if (method === "GET" && url.pathname === "/cards") {
|
|
491
|
+
const slideId = url.searchParams.get("slideId") ?? "";
|
|
492
|
+
if (!resolveSlideEntryPath(ctx, slideId)) return json(res, 400, { error: "invalid slideId" });
|
|
493
|
+
const stored = await readBoardFile(boardStructurePath(ctx.userCwd, slideId));
|
|
494
|
+
return json(res, 200, {
|
|
495
|
+
cards: sanitizeCards(stored.cards),
|
|
496
|
+
links: sanitizeLinks(stored.links)
|
|
497
|
+
});
|
|
498
|
+
}
|
|
499
|
+
if (method === "PUT" && url.pathname === "/cards") {
|
|
500
|
+
const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
|
|
501
|
+
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
502
|
+
const body = await readBody(req);
|
|
503
|
+
const slideId = body.slideId ?? "";
|
|
504
|
+
if (!resolveSlideEntryPath(ctx, slideId)) return json(res, 400, { error: "invalid slideId" });
|
|
505
|
+
await updateBoardFile(boardStructurePath(ctx.userCwd, slideId), {
|
|
506
|
+
cards: sanitizeCards(body.cards),
|
|
507
|
+
links: sanitizeLinks(body.links)
|
|
508
|
+
});
|
|
509
|
+
return json(res, 200, { ok: true });
|
|
510
|
+
}
|
|
511
|
+
if (method === "POST" && url.pathname === "/pages/insert") {
|
|
512
|
+
const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
|
|
513
|
+
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
514
|
+
const body = await readBody(req);
|
|
515
|
+
const slideId = typeof body?.slideId === "string" ? body.slideId : "";
|
|
516
|
+
const index = typeof body?.index === "number" ? body.index : NaN;
|
|
517
|
+
if (!Number.isInteger(index) || index < 0) return json(res, 400, { error: "invalid index" });
|
|
518
|
+
const entry = resolveSlideEntry(ctx.slidesRoot, slideId);
|
|
519
|
+
if (!entry) return json(res, 400, { error: "invalid slideId" });
|
|
520
|
+
let source;
|
|
521
|
+
try {
|
|
522
|
+
source = await fs.readFile(entry, "utf8");
|
|
523
|
+
} catch {
|
|
524
|
+
return json(res, 404, { error: "slide not found" });
|
|
525
|
+
}
|
|
526
|
+
const withPage = insertBlankPageInDefaultExportInSource(source, index);
|
|
527
|
+
if (withPage === null) return json(res, 422, { error: "could not insert a page — index out of range or default export is not an array" });
|
|
528
|
+
const withNotes = insertNotesElementInSource(withPage, index);
|
|
529
|
+
if (withNotes === null) return json(res, 422, { error: "could not insert a page — `notes` export has an unexpected shape" });
|
|
530
|
+
if (withNotes !== source) await fs.writeFile(entry, withNotes, "utf8");
|
|
531
|
+
return json(res, 200, {
|
|
532
|
+
ok: true,
|
|
533
|
+
slideId,
|
|
534
|
+
index
|
|
535
|
+
});
|
|
536
|
+
}
|
|
537
|
+
if (method === "GET" && url.pathname === "/entries") {
|
|
538
|
+
const slideId = url.searchParams.get("slideId") ?? "";
|
|
539
|
+
const entry = resolveSlideEntryPath(ctx, slideId);
|
|
540
|
+
if (!entry) return json(res, 400, { error: "invalid slideId" });
|
|
541
|
+
const source = await readSlideSource(entry);
|
|
542
|
+
return json(res, 200, { entries: source ? defaultExportEntriesInSource(source) : null });
|
|
543
|
+
}
|
|
544
|
+
next();
|
|
545
|
+
} catch (err) {
|
|
546
|
+
json(res, 500, { error: String(err.message ?? err) });
|
|
547
|
+
}
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
//#endregion
|
|
551
|
+
//#region src/lemonriver/decks/routes.ts
|
|
552
|
+
const ENTRY_NAMES$1 = [
|
|
553
|
+
"index.tsx",
|
|
554
|
+
"index.jsx",
|
|
555
|
+
"index.ts",
|
|
556
|
+
"index.js"
|
|
557
|
+
];
|
|
558
|
+
async function readDeckTimes(slidesRoot) {
|
|
559
|
+
let names;
|
|
560
|
+
try {
|
|
561
|
+
names = await fs.readdir(slidesRoot);
|
|
562
|
+
} catch {
|
|
563
|
+
return {};
|
|
564
|
+
}
|
|
565
|
+
const decks = {};
|
|
566
|
+
for (const name of names) {
|
|
567
|
+
if (!SLIDE_ID_RE.test(name)) continue;
|
|
568
|
+
for (const entry of ENTRY_NAMES$1) try {
|
|
569
|
+
const stat = await fs.stat(path.join(slidesRoot, name, entry));
|
|
570
|
+
decks[name] = { modifiedAt: Math.round(stat.mtimeMs) };
|
|
571
|
+
break;
|
|
572
|
+
} catch {}
|
|
573
|
+
}
|
|
574
|
+
return decks;
|
|
575
|
+
}
|
|
576
|
+
function registerDeckRoutes(server, ctx) {
|
|
577
|
+
server.middlewares.use("/__lr/decks", async (req, res, next) => {
|
|
578
|
+
const url = new URL(req.url ?? "/", "http://local");
|
|
579
|
+
if ((req.method ?? "GET") !== "GET" || url.pathname !== "/") return next();
|
|
580
|
+
try {
|
|
581
|
+
json(res, 200, { decks: await readDeckTimes(ctx.slidesRoot) });
|
|
582
|
+
} catch (err) {
|
|
583
|
+
json(res, 500, { error: String(err.message ?? err) });
|
|
584
|
+
}
|
|
585
|
+
});
|
|
586
|
+
}
|
|
587
|
+
//#endregion
|
|
588
|
+
//#region src/vite/recent-writes.ts
|
|
589
|
+
const recentWrites = /* @__PURE__ */ new Map();
|
|
590
|
+
/** Record that `file` was just written by us. */
|
|
591
|
+
function recordWrite(file, now = Date.now()) {
|
|
592
|
+
recentWrites.set(file, now);
|
|
593
|
+
}
|
|
594
|
+
/**
|
|
595
|
+
* True if `file` was recorded within the recent-write window. Expired entries
|
|
596
|
+
* are pruned so a stale path can no longer suppress a later genuine edit.
|
|
597
|
+
*/
|
|
598
|
+
function hasRecentWrite(file, now = Date.now()) {
|
|
599
|
+
const ts = recentWrites.get(file);
|
|
600
|
+
if (ts == null) return false;
|
|
601
|
+
if (now - ts < 1500) return true;
|
|
602
|
+
recentWrites.delete(file);
|
|
603
|
+
return false;
|
|
604
|
+
}
|
|
605
|
+
//#endregion
|
|
606
|
+
//#region src/vite/open-slide-plugin.ts
|
|
607
|
+
const SLIDES_VMOD = "virtual:open-slide/slides";
|
|
608
|
+
const CONFIG_VMOD = "virtual:open-slide/config";
|
|
609
|
+
const FOLDERS_VMOD = "virtual:open-slide/folders";
|
|
610
|
+
function resolved$1(id) {
|
|
611
|
+
return `\0${id}`;
|
|
612
|
+
}
|
|
613
|
+
async function findSlides(userCwd, slidesDir) {
|
|
614
|
+
const abs = path.resolve(userCwd, slidesDir);
|
|
615
|
+
if (!existsSync(abs)) return [];
|
|
616
|
+
return (await fg("*/index.{tsx,jsx,ts,js}", {
|
|
617
|
+
cwd: abs,
|
|
618
|
+
absolute: true,
|
|
619
|
+
onlyFiles: true
|
|
620
|
+
})).sort();
|
|
621
|
+
}
|
|
622
|
+
function toId(absFile, slidesRoot) {
|
|
623
|
+
return path.relative(slidesRoot, absFile).split(path.sep)[0];
|
|
624
|
+
}
|
|
625
|
+
const META_THEME_RE = /(?:^|[\s,{])theme\s*:\s*['"]([^'"]+)['"]/;
|
|
626
|
+
const META_CREATED_AT_RE = /(?:^|[\s,{])createdAt\s*:\s*['"]([^'"]+)['"]/;
|
|
627
|
+
function extractMeta(src) {
|
|
628
|
+
const empty = {
|
|
629
|
+
theme: null,
|
|
630
|
+
createdAt: null
|
|
631
|
+
};
|
|
632
|
+
const metaStart = src.search(/export\s+const\s+meta\b/);
|
|
633
|
+
if (metaStart === -1) return empty;
|
|
634
|
+
const eqIdx = src.indexOf("=", metaStart);
|
|
635
|
+
if (eqIdx === -1) return empty;
|
|
636
|
+
const openBrace = src.indexOf("{", eqIdx);
|
|
637
|
+
if (openBrace === -1) return empty;
|
|
638
|
+
let depth = 0;
|
|
639
|
+
let closeBrace = -1;
|
|
640
|
+
for (let i = openBrace; i < src.length; i++) {
|
|
641
|
+
const ch = src[i];
|
|
642
|
+
if (ch === "{") depth++;
|
|
643
|
+
else if (ch === "}") {
|
|
644
|
+
depth--;
|
|
645
|
+
if (depth === 0) {
|
|
646
|
+
closeBrace = i;
|
|
647
|
+
break;
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
if (closeBrace === -1) return empty;
|
|
652
|
+
const body = src.slice(openBrace + 1, closeBrace);
|
|
653
|
+
const themeMatch = body.match(META_THEME_RE);
|
|
654
|
+
const createdAtMatch = body.match(META_CREATED_AT_RE);
|
|
655
|
+
return {
|
|
656
|
+
theme: themeMatch ? themeMatch[1] : null,
|
|
657
|
+
createdAt: createdAtMatch ? createdAtMatch[1] : null
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
async function readSlideMeta(abs) {
|
|
661
|
+
try {
|
|
662
|
+
return extractMeta(await fs.readFile(abs, "utf8"));
|
|
663
|
+
} catch {
|
|
664
|
+
return {
|
|
665
|
+
theme: null,
|
|
666
|
+
createdAt: null
|
|
667
|
+
};
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
function parseCreatedAtMs(iso) {
|
|
671
|
+
if (!iso) return null;
|
|
672
|
+
const ms = Date.parse(iso);
|
|
673
|
+
return Number.isFinite(ms) ? ms : null;
|
|
674
|
+
}
|
|
675
|
+
const warnedInvalidSlideIds = /* @__PURE__ */ new Set();
|
|
676
|
+
async function generateSlidesModule(files, slidesRoot, isDev) {
|
|
677
|
+
const scanned = await Promise.all(files.map(async (abs) => {
|
|
678
|
+
const id = toId(abs, slidesRoot);
|
|
679
|
+
const importPath = isDev ? `@fs/${normalizePath(abs).replace(/^\/+/, "")}` : abs;
|
|
680
|
+
const meta = await readSlideMeta(abs);
|
|
681
|
+
return {
|
|
682
|
+
id,
|
|
683
|
+
importPath,
|
|
684
|
+
theme: meta.theme,
|
|
685
|
+
createdAt: parseCreatedAtMs(meta.createdAt)
|
|
686
|
+
};
|
|
687
|
+
}));
|
|
688
|
+
const entries = scanned.filter((e) => SLIDE_ID_RE.test(e.id));
|
|
689
|
+
const ignored = scanned.filter((e) => !SLIDE_ID_RE.test(e.id)).map((e) => e.id);
|
|
690
|
+
const ids = JSON.stringify(entries.map((e) => e.id).sort());
|
|
691
|
+
const themesMap = {};
|
|
692
|
+
const createdAtMap = {};
|
|
693
|
+
for (const e of entries) {
|
|
694
|
+
if (e.theme) themesMap[e.id] = e.theme;
|
|
695
|
+
if (e.createdAt !== null) createdAtMap[e.id] = e.createdAt;
|
|
696
|
+
}
|
|
697
|
+
const themesJson = JSON.stringify(themesMap);
|
|
698
|
+
const createdAtJson = JSON.stringify(createdAtMap);
|
|
699
|
+
const importTokens = JSON.stringify(Object.fromEntries(entries.map((e) => [e.id, 0])));
|
|
700
|
+
return {
|
|
701
|
+
code: `// virtual:open-slide/slides — generated
|
|
702
|
+
export const slideIds = ${ids};
|
|
703
|
+
export const slideThemes = ${themesJson};
|
|
704
|
+
export const slideCreatedAt = ${createdAtJson};
|
|
705
|
+
${isDev ? `
|
|
706
|
+
const slideImportTokens = ${importTokens};
|
|
707
|
+
if (import.meta.hot) {
|
|
708
|
+
import.meta.hot.on('open-slide:slide-changed', (data) => {
|
|
709
|
+
const ids = Array.isArray(data?.slideIds) ? data.slideIds : [];
|
|
710
|
+
const token = Date.now();
|
|
711
|
+
for (const id of ids) {
|
|
712
|
+
if (Object.prototype.hasOwnProperty.call(slideImportTokens, id)) slideImportTokens[id] = token;
|
|
713
|
+
}
|
|
714
|
+
});
|
|
715
|
+
}
|
|
716
|
+
` : ""}
|
|
717
|
+
|
|
718
|
+
export async function loadSlide(id) {
|
|
719
|
+
switch (id) {
|
|
720
|
+
${entries.map((e) => {
|
|
721
|
+
const importExpr = isDev ? `import(/* @vite-ignore */ import.meta.env.BASE_URL + ${JSON.stringify(`${e.importPath}?t=`)} + slideImportTokens[${JSON.stringify(e.id)}])` : `import(${JSON.stringify(e.importPath)})`;
|
|
722
|
+
return ` case ${JSON.stringify(e.id)}: return ${importExpr};`;
|
|
723
|
+
}).join("\n")}
|
|
724
|
+
default: throw new Error('Slide not found: ' + id);
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
`,
|
|
728
|
+
ignored
|
|
729
|
+
};
|
|
730
|
+
}
|
|
731
|
+
function lemonRiverPlugin(opts) {
|
|
732
|
+
const { userCwd, config, coreVersion } = opts;
|
|
733
|
+
const slidesDir = config.slidesDir ?? "slides";
|
|
734
|
+
const slidesRoot = path.resolve(userCwd, slidesDir);
|
|
735
|
+
const manifestPath = foldersManifestPath(slidesRoot);
|
|
736
|
+
let isDev = false;
|
|
737
|
+
const slideIdForEntry = (p) => {
|
|
738
|
+
const rel = path.relative(slidesRoot, p);
|
|
739
|
+
if (rel.startsWith("..") || path.isAbsolute(rel)) return null;
|
|
740
|
+
const parts = rel.split(path.sep);
|
|
741
|
+
if (parts.length !== 2) return null;
|
|
742
|
+
if (!/^index\.(tsx|jsx|ts|js)$/.test(parts[1])) return null;
|
|
743
|
+
return parts[0];
|
|
744
|
+
};
|
|
745
|
+
let slideChangeTimer = null;
|
|
746
|
+
const pendingSlideChanges = /* @__PURE__ */ new Set();
|
|
747
|
+
const queueSlideChanged = (server, id) => {
|
|
748
|
+
pendingSlideChanges.add(id);
|
|
749
|
+
if (slideChangeTimer) clearTimeout(slideChangeTimer);
|
|
750
|
+
slideChangeTimer = setTimeout(() => {
|
|
751
|
+
slideChangeTimer = null;
|
|
752
|
+
const mod = server.moduleGraph.getModuleById(resolved$1(SLIDES_VMOD));
|
|
753
|
+
if (mod) server.moduleGraph.invalidateModule(mod);
|
|
754
|
+
const slideIds = Array.from(pendingSlideChanges);
|
|
755
|
+
pendingSlideChanges.clear();
|
|
756
|
+
server.ws.send({
|
|
757
|
+
type: "custom",
|
|
758
|
+
event: "open-slide:slide-changed",
|
|
759
|
+
data: { slideIds }
|
|
760
|
+
});
|
|
761
|
+
}, 100);
|
|
762
|
+
};
|
|
763
|
+
return {
|
|
764
|
+
name: "lemonriver",
|
|
765
|
+
config(_c, env) {
|
|
766
|
+
isDev = env.command === "serve";
|
|
767
|
+
},
|
|
768
|
+
resolveId(id) {
|
|
769
|
+
if (id === SLIDES_VMOD) return resolved$1(SLIDES_VMOD);
|
|
770
|
+
if (id === CONFIG_VMOD) return resolved$1(CONFIG_VMOD);
|
|
771
|
+
if (id === FOLDERS_VMOD) return resolved$1(FOLDERS_VMOD);
|
|
772
|
+
return null;
|
|
773
|
+
},
|
|
774
|
+
async load(id) {
|
|
775
|
+
if (id === resolved$1(SLIDES_VMOD)) {
|
|
776
|
+
const { code, ignored } = await generateSlidesModule(await findSlides(userCwd, slidesDir), slidesRoot, isDev);
|
|
777
|
+
for (const slideId of ignored) {
|
|
778
|
+
if (warnedInvalidSlideIds.has(slideId)) continue;
|
|
779
|
+
warnedInvalidSlideIds.add(slideId);
|
|
780
|
+
this.warn(`Ignoring slide folder "${slideId}": slide ids must match ${SLIDE_ID_RE} (lowercase/uppercase letters, digits, "-", "_"). Rename the folder under "${slidesDir}/" to a kebab-case id so it appears in the browser and can be moved into folders.`);
|
|
781
|
+
}
|
|
782
|
+
return code;
|
|
783
|
+
}
|
|
784
|
+
if (id === resolved$1(CONFIG_VMOD)) {
|
|
785
|
+
const userBuild = config.build ?? {};
|
|
786
|
+
const buildResolved = isDev ? {
|
|
787
|
+
showSlideBrowser: true,
|
|
788
|
+
showSlideUi: true,
|
|
789
|
+
allowHtmlDownload: true
|
|
790
|
+
} : {
|
|
791
|
+
showSlideBrowser: userBuild.showSlideBrowser ?? true,
|
|
792
|
+
showSlideUi: userBuild.showSlideUi ?? true,
|
|
793
|
+
allowHtmlDownload: userBuild.allowHtmlDownload ?? true
|
|
794
|
+
};
|
|
795
|
+
const resolvedConfig = {
|
|
796
|
+
...config,
|
|
797
|
+
build: buildResolved,
|
|
798
|
+
version: coreVersion
|
|
799
|
+
};
|
|
800
|
+
return `export default ${JSON.stringify(resolvedConfig)};\n`;
|
|
801
|
+
}
|
|
802
|
+
if (id === resolved$1(FOLDERS_VMOD)) {
|
|
803
|
+
const manifest = await readManifest(manifestPath);
|
|
804
|
+
return `export default ${JSON.stringify(manifest)};\n`;
|
|
805
|
+
}
|
|
806
|
+
return null;
|
|
807
|
+
},
|
|
808
|
+
handleHotUpdate(ctx) {
|
|
809
|
+
const slideId = slideIdForEntry(ctx.file);
|
|
810
|
+
if (!slideId) return;
|
|
811
|
+
if (hasRecentWrite(ctx.file)) return [];
|
|
812
|
+
queueSlideChanged(ctx.server, slideId);
|
|
813
|
+
return [];
|
|
814
|
+
},
|
|
815
|
+
configureServer(server) {
|
|
816
|
+
const isSlideEntry = (p) => slideIdForEntry(p) !== null;
|
|
817
|
+
let reloadTimer = null;
|
|
818
|
+
const reload = () => {
|
|
819
|
+
if (reloadTimer) clearTimeout(reloadTimer);
|
|
820
|
+
reloadTimer = setTimeout(() => {
|
|
821
|
+
reloadTimer = null;
|
|
822
|
+
const mod = server.moduleGraph.getModuleById(resolved$1(SLIDES_VMOD));
|
|
823
|
+
if (mod) server.moduleGraph.invalidateModule(mod);
|
|
824
|
+
server.ws.send({ type: "full-reload" });
|
|
825
|
+
}, 150);
|
|
826
|
+
};
|
|
827
|
+
if (existsSync(slidesRoot)) server.watcher.add(slidesRoot);
|
|
828
|
+
server.watcher.on("add", (p) => {
|
|
829
|
+
if (isSlideEntry(p) && !hasRecentWrite(p)) reload();
|
|
830
|
+
});
|
|
831
|
+
server.watcher.on("unlink", (p) => {
|
|
832
|
+
if (isSlideEntry(p) && !hasRecentWrite(p)) reload();
|
|
833
|
+
});
|
|
834
|
+
let foldersTimer = null;
|
|
835
|
+
const invalidateFolders = () => {
|
|
836
|
+
if (foldersTimer) clearTimeout(foldersTimer);
|
|
837
|
+
foldersTimer = setTimeout(() => {
|
|
838
|
+
foldersTimer = null;
|
|
839
|
+
const mod = server.moduleGraph.getModuleById(resolved$1(FOLDERS_VMOD));
|
|
840
|
+
if (mod) server.moduleGraph.invalidateModule(mod);
|
|
841
|
+
}, 100);
|
|
842
|
+
};
|
|
843
|
+
server.watcher.add(manifestPath);
|
|
844
|
+
server.watcher.on("change", (p) => {
|
|
845
|
+
if (p === manifestPath) invalidateFolders();
|
|
846
|
+
});
|
|
847
|
+
server.watcher.on("add", (p) => {
|
|
848
|
+
if (p === manifestPath) invalidateFolders();
|
|
849
|
+
});
|
|
850
|
+
server.watcher.on("unlink", (p) => {
|
|
851
|
+
if (p === manifestPath) invalidateFolders();
|
|
852
|
+
});
|
|
853
|
+
}
|
|
854
|
+
};
|
|
855
|
+
}
|
|
856
|
+
function invalidateSlidesModule(server) {
|
|
857
|
+
const mod = server.moduleGraph.getModuleById(resolved$1(SLIDES_VMOD));
|
|
858
|
+
if (mod) server.moduleGraph.invalidateModule(mod);
|
|
859
|
+
}
|
|
860
|
+
async function loadUserConfig(userCwd) {
|
|
861
|
+
const file = CONFIG_FILES.map((name) => path.join(userCwd, name)).find((p) => existsSync(p));
|
|
862
|
+
if (!file) return {};
|
|
863
|
+
return (await loadConfigFromFile({
|
|
864
|
+
command: "serve",
|
|
865
|
+
mode: "development"
|
|
866
|
+
}, file, userCwd, "silent"))?.config ?? {};
|
|
867
|
+
}
|
|
868
|
+
//#endregion
|
|
869
|
+
//#region src/lemonriver/trash/store.ts
|
|
870
|
+
const TRASH_RETENTION_MS = 2592e6;
|
|
871
|
+
/** `<slideId>.<deletedAt>` — unique per deletion, and safe as a single path segment. */
|
|
872
|
+
const ENTRY_ID_RE = /^[a-z0-9_-]+\.\d{1,16}$/i;
|
|
873
|
+
const ENTRY_FILE = "entry.json";
|
|
874
|
+
const SLIDE_DIR = "slide";
|
|
875
|
+
function trashRootFor(userCwd) {
|
|
876
|
+
return path.join(userCwd, "node_modules", ".open-slide", "trash");
|
|
877
|
+
}
|
|
878
|
+
function isTrashEntryId(id) {
|
|
879
|
+
return ENTRY_ID_RE.test(id);
|
|
880
|
+
}
|
|
881
|
+
function inside(root, id) {
|
|
882
|
+
const dir = path.resolve(root, id);
|
|
883
|
+
return dir.startsWith(path.resolve(root) + path.sep) ? dir : null;
|
|
884
|
+
}
|
|
885
|
+
async function exists(p) {
|
|
886
|
+
try {
|
|
887
|
+
await fs.access(p);
|
|
888
|
+
return true;
|
|
889
|
+
} catch {
|
|
890
|
+
return false;
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
async function moveDir(from, to) {
|
|
894
|
+
try {
|
|
895
|
+
await fs.rename(from, to);
|
|
896
|
+
} catch (err) {
|
|
897
|
+
if (err.code !== "EXDEV") throw err;
|
|
898
|
+
await fs.cp(from, to, {
|
|
899
|
+
recursive: true,
|
|
900
|
+
errorOnExist: true,
|
|
901
|
+
force: false
|
|
902
|
+
});
|
|
903
|
+
await fs.rm(from, {
|
|
904
|
+
recursive: true,
|
|
905
|
+
force: true
|
|
906
|
+
});
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
async function readTitle(slideDir, fallback) {
|
|
910
|
+
try {
|
|
911
|
+
const read = readMetaTitleInSource(await fs.readFile(path.join(slideDir, "index.tsx"), "utf8"));
|
|
912
|
+
return read.kind === "found" && read.title.trim() ? read.title : fallback;
|
|
913
|
+
} catch {
|
|
914
|
+
return fallback;
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
function toEntry(id, raw) {
|
|
918
|
+
if (!raw || typeof raw !== "object") return null;
|
|
919
|
+
const r = raw;
|
|
920
|
+
if (typeof r.slideId !== "string" || !SLIDE_ID_RE.test(r.slideId)) return null;
|
|
921
|
+
if (typeof r.deletedAt !== "number" || !Number.isFinite(r.deletedAt)) return null;
|
|
922
|
+
return {
|
|
923
|
+
id,
|
|
924
|
+
slideId: r.slideId,
|
|
925
|
+
title: typeof r.title === "string" && r.title ? r.title : r.slideId,
|
|
926
|
+
folderId: typeof r.folderId === "string" ? r.folderId : null,
|
|
927
|
+
deletedAt: r.deletedAt,
|
|
928
|
+
expiresAt: r.deletedAt + TRASH_RETENTION_MS
|
|
929
|
+
};
|
|
930
|
+
}
|
|
931
|
+
async function readEntry(trashRoot, id) {
|
|
932
|
+
if (!isTrashEntryId(id)) return null;
|
|
933
|
+
const dir = inside(trashRoot, id);
|
|
934
|
+
if (!dir) return null;
|
|
935
|
+
try {
|
|
936
|
+
const entry = toEntry(id, JSON.parse(await fs.readFile(path.join(dir, ENTRY_FILE), "utf8")));
|
|
937
|
+
return entry && await exists(path.join(dir, SLIDE_DIR)) ? entry : null;
|
|
938
|
+
} catch {
|
|
939
|
+
return null;
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
async function idTaken(slidesRoot, slideId) {
|
|
943
|
+
try {
|
|
944
|
+
const want = slideId.toLowerCase();
|
|
945
|
+
return (await fs.readdir(slidesRoot)).some((name) => name.toLowerCase() === want);
|
|
946
|
+
} catch {
|
|
947
|
+
return false;
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
async function freeSlideId(slidesRoot, slideId) {
|
|
951
|
+
if (!await idTaken(slidesRoot, slideId)) return slideId;
|
|
952
|
+
for (let n = 1;; n++) {
|
|
953
|
+
const candidate = n === 1 ? `${slideId}-restored` : `${slideId}-restored-${n}`;
|
|
954
|
+
if (!await idTaken(slidesRoot, candidate)) return candidate;
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
async function listTrash(paths, now = Date.now()) {
|
|
958
|
+
let names;
|
|
959
|
+
try {
|
|
960
|
+
names = await fs.readdir(paths.trashRoot);
|
|
961
|
+
} catch {
|
|
962
|
+
return [];
|
|
963
|
+
}
|
|
964
|
+
const entries = [];
|
|
965
|
+
for (const name of names) {
|
|
966
|
+
const entry = await readEntry(paths.trashRoot, name);
|
|
967
|
+
if (!entry) continue;
|
|
968
|
+
if (now >= entry.expiresAt) {
|
|
969
|
+
await purgeTrashEntry(paths, entry.id);
|
|
970
|
+
continue;
|
|
971
|
+
}
|
|
972
|
+
entries.push(entry);
|
|
973
|
+
}
|
|
974
|
+
return entries.sort((a, b) => b.deletedAt - a.deletedAt);
|
|
975
|
+
}
|
|
976
|
+
async function moveSlideToTrash(paths, slideId, now = Date.now()) {
|
|
977
|
+
if (!SLIDE_ID_RE.test(slideId)) return {
|
|
978
|
+
ok: false,
|
|
979
|
+
status: 400,
|
|
980
|
+
error: "invalid slideId"
|
|
981
|
+
};
|
|
982
|
+
const slideDir = inside(paths.slidesRoot, slideId);
|
|
983
|
+
if (!slideDir || !await exists(slideDir)) return {
|
|
984
|
+
ok: false,
|
|
985
|
+
status: 404,
|
|
986
|
+
error: "slide not found"
|
|
987
|
+
};
|
|
988
|
+
let deletedAt = now;
|
|
989
|
+
while (await exists(path.join(paths.trashRoot, `${slideId}.${deletedAt}`))) deletedAt++;
|
|
990
|
+
const id = `${slideId}.${deletedAt}`;
|
|
991
|
+
const entryDir = path.join(paths.trashRoot, id);
|
|
992
|
+
const manifest = await readManifest(paths.manifestPath);
|
|
993
|
+
const folderId = manifest.assignments[slideId] ?? null;
|
|
994
|
+
const title = await readTitle(slideDir, slideId);
|
|
995
|
+
await fs.mkdir(entryDir, { recursive: true });
|
|
996
|
+
await fs.writeFile(path.join(entryDir, ENTRY_FILE), `${JSON.stringify({
|
|
997
|
+
slideId,
|
|
998
|
+
title,
|
|
999
|
+
folderId,
|
|
1000
|
+
deletedAt
|
|
1001
|
+
}, null, 2)}\n`, "utf8");
|
|
1002
|
+
try {
|
|
1003
|
+
await moveDir(slideDir, path.join(entryDir, SLIDE_DIR));
|
|
1004
|
+
} catch (err) {
|
|
1005
|
+
await fs.rm(entryDir, {
|
|
1006
|
+
recursive: true,
|
|
1007
|
+
force: true
|
|
1008
|
+
});
|
|
1009
|
+
throw err;
|
|
1010
|
+
}
|
|
1011
|
+
if (folderId !== null) {
|
|
1012
|
+
delete manifest.assignments[slideId];
|
|
1013
|
+
await writeManifest(paths.manifestPath, manifest);
|
|
1014
|
+
}
|
|
1015
|
+
return {
|
|
1016
|
+
ok: true,
|
|
1017
|
+
entry: {
|
|
1018
|
+
id,
|
|
1019
|
+
slideId,
|
|
1020
|
+
title,
|
|
1021
|
+
folderId,
|
|
1022
|
+
deletedAt,
|
|
1023
|
+
expiresAt: deletedAt + TRASH_RETENTION_MS
|
|
1024
|
+
}
|
|
1025
|
+
};
|
|
1026
|
+
}
|
|
1027
|
+
async function restoreTrashEntry(paths, id, beforeMove = () => {}) {
|
|
1028
|
+
const entry = await readEntry(paths.trashRoot, id);
|
|
1029
|
+
if (!entry) return {
|
|
1030
|
+
ok: false,
|
|
1031
|
+
status: 404,
|
|
1032
|
+
error: "trash entry not found"
|
|
1033
|
+
};
|
|
1034
|
+
const entryDir = path.join(paths.trashRoot, id);
|
|
1035
|
+
const slideId = await freeSlideId(paths.slidesRoot, entry.slideId);
|
|
1036
|
+
const slideDir = inside(paths.slidesRoot, slideId);
|
|
1037
|
+
if (!slideDir) return {
|
|
1038
|
+
ok: false,
|
|
1039
|
+
status: 400,
|
|
1040
|
+
error: "invalid slideId"
|
|
1041
|
+
};
|
|
1042
|
+
await fs.mkdir(paths.slidesRoot, { recursive: true });
|
|
1043
|
+
beforeMove(slideId);
|
|
1044
|
+
await moveDir(path.join(entryDir, SLIDE_DIR), slideDir);
|
|
1045
|
+
await fs.rm(entryDir, {
|
|
1046
|
+
recursive: true,
|
|
1047
|
+
force: true
|
|
1048
|
+
});
|
|
1049
|
+
if (entry.folderId !== null) {
|
|
1050
|
+
const manifest = await readManifest(paths.manifestPath);
|
|
1051
|
+
if (manifest.folders.some((f) => f.id === entry.folderId)) {
|
|
1052
|
+
manifest.assignments[slideId] = entry.folderId;
|
|
1053
|
+
await writeManifest(paths.manifestPath, manifest);
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
return {
|
|
1057
|
+
ok: true,
|
|
1058
|
+
slideId
|
|
1059
|
+
};
|
|
1060
|
+
}
|
|
1061
|
+
async function purgeTrashEntry(paths, id) {
|
|
1062
|
+
if (!isTrashEntryId(id)) return false;
|
|
1063
|
+
const dir = inside(paths.trashRoot, id);
|
|
1064
|
+
if (!dir || !await exists(dir)) return false;
|
|
1065
|
+
await fs.rm(dir, {
|
|
1066
|
+
recursive: true,
|
|
1067
|
+
force: true
|
|
1068
|
+
});
|
|
1069
|
+
return true;
|
|
1070
|
+
}
|
|
1071
|
+
//#endregion
|
|
1072
|
+
//#region src/lemonriver/trash/routes.ts
|
|
1073
|
+
const ENTRY_NAMES = [
|
|
1074
|
+
"index.tsx",
|
|
1075
|
+
"index.jsx",
|
|
1076
|
+
"index.ts",
|
|
1077
|
+
"index.js"
|
|
1078
|
+
];
|
|
1079
|
+
const DECKS_CHANGED_EVENT = "lemonriver:decks-changed";
|
|
1080
|
+
function registerTrashRoutes(server, ctx) {
|
|
1081
|
+
const paths = {
|
|
1082
|
+
slidesRoot: ctx.slidesRoot,
|
|
1083
|
+
manifestPath: ctx.manifestPath,
|
|
1084
|
+
trashRoot: trashRootFor(ctx.userCwd)
|
|
1085
|
+
};
|
|
1086
|
+
const quietWatcher = (slideId) => {
|
|
1087
|
+
for (const name of ENTRY_NAMES) recordWrite(path.join(ctx.slidesRoot, slideId, name));
|
|
1088
|
+
};
|
|
1089
|
+
const reloadClients = () => {
|
|
1090
|
+
invalidateSlidesModule(server);
|
|
1091
|
+
server.ws.send({
|
|
1092
|
+
type: "custom",
|
|
1093
|
+
event: DECKS_CHANGED_EVENT
|
|
1094
|
+
});
|
|
1095
|
+
};
|
|
1096
|
+
server.middlewares.use("/__lr/trash", async (req, res, next) => {
|
|
1097
|
+
const url = new URL(req.url ?? "/", "http://local");
|
|
1098
|
+
const method = req.method ?? "GET";
|
|
1099
|
+
try {
|
|
1100
|
+
if (method === "GET" && url.pathname === "/") return json(res, 200, { entries: await listTrash(paths) });
|
|
1101
|
+
if (method === "POST" && url.pathname === "/") {
|
|
1102
|
+
const check = validateMutationRequest(req, { requireJsonBody: true });
|
|
1103
|
+
if (!check.ok) return json(res, check.status, { error: check.error });
|
|
1104
|
+
const body = await readBody(req);
|
|
1105
|
+
const slideId = typeof body?.slideId === "string" ? body.slideId : "";
|
|
1106
|
+
if (!SLIDE_ID_RE.test(slideId)) return json(res, 400, { error: "invalid slideId" });
|
|
1107
|
+
quietWatcher(slideId);
|
|
1108
|
+
const moved = await moveSlideToTrash(paths, slideId);
|
|
1109
|
+
if (!moved.ok) return json(res, moved.status, { error: moved.error });
|
|
1110
|
+
json(res, 200, {
|
|
1111
|
+
ok: true,
|
|
1112
|
+
entry: moved.entry
|
|
1113
|
+
});
|
|
1114
|
+
return reloadClients();
|
|
1115
|
+
}
|
|
1116
|
+
const restoreMatch = url.pathname.match(/^\/([^/]+)\/restore$/);
|
|
1117
|
+
if (method === "POST" && restoreMatch) {
|
|
1118
|
+
const check = validateMutationRequest(req);
|
|
1119
|
+
if (!check.ok) return json(res, check.status, { error: check.error });
|
|
1120
|
+
const id = decodeURIComponent(restoreMatch[1]);
|
|
1121
|
+
if (!isTrashEntryId(id)) return json(res, 400, { error: "invalid trash id" });
|
|
1122
|
+
const restored = await restoreTrashEntry(paths, id, quietWatcher);
|
|
1123
|
+
if (!restored.ok) return json(res, restored.status, { error: restored.error });
|
|
1124
|
+
json(res, 200, {
|
|
1125
|
+
ok: true,
|
|
1126
|
+
slideId: restored.slideId
|
|
1127
|
+
});
|
|
1128
|
+
return reloadClients();
|
|
1129
|
+
}
|
|
1130
|
+
const entryMatch = url.pathname.match(/^\/([^/]+)$/);
|
|
1131
|
+
if (method === "DELETE" && entryMatch) {
|
|
1132
|
+
const check = validateMutationRequest(req);
|
|
1133
|
+
if (!check.ok) return json(res, check.status, { error: check.error });
|
|
1134
|
+
const id = decodeURIComponent(entryMatch[1]);
|
|
1135
|
+
if (!isTrashEntryId(id)) return json(res, 400, { error: "invalid trash id" });
|
|
1136
|
+
if (!await purgeTrashEntry(paths, id)) return json(res, 404, { error: "trash entry not found" });
|
|
1137
|
+
return json(res, 200, { ok: true });
|
|
1138
|
+
}
|
|
1139
|
+
next();
|
|
1140
|
+
} catch (err) {
|
|
1141
|
+
json(res, 500, { error: String(err.message ?? err) });
|
|
1142
|
+
}
|
|
1143
|
+
});
|
|
1144
|
+
}
|
|
1145
|
+
//#endregion
|
|
1146
|
+
//#region src/lemonriver/routes.ts
|
|
1147
|
+
function registerLemonRiverRoutes(server, ctx) {
|
|
1148
|
+
registerBoardRoutes(server, ctx);
|
|
1149
|
+
registerTrashRoutes(server, ctx);
|
|
1150
|
+
registerDeckRoutes(server, ctx);
|
|
1151
|
+
}
|
|
1152
|
+
//#endregion
|
|
1153
|
+
//#region src/editing/placeholder-id.ts
|
|
1154
|
+
const UNTITLED_SLIDE_ID_RE = /^untitled(-\d+)?$/;
|
|
1155
|
+
//#endregion
|
|
1156
|
+
//#region src/agent/provider.ts
|
|
1157
|
+
var ProviderUnavailableError = class extends Error {
|
|
1158
|
+
constructor(provider) {
|
|
1159
|
+
super(`${provider.name} is not connected: install ${provider.sdkPackage} in this workspace to use it from the agent panel.`);
|
|
1160
|
+
this.name = "ProviderUnavailableError";
|
|
1161
|
+
}
|
|
1162
|
+
};
|
|
1163
|
+
const DETAIL_MAX = 400;
|
|
1164
|
+
function clipDetail(value) {
|
|
1165
|
+
if (value === void 0 || value === null) return null;
|
|
1166
|
+
const text = typeof value === "string" ? value : safeJson(value);
|
|
1167
|
+
if (!text) return null;
|
|
1168
|
+
const oneLine = text.replace(/\s+/g, " ").trim();
|
|
1169
|
+
return oneLine.length > DETAIL_MAX ? `${oneLine.slice(0, 399)}…` : oneLine;
|
|
1170
|
+
}
|
|
1171
|
+
function safeJson(value) {
|
|
1172
|
+
try {
|
|
1173
|
+
return JSON.stringify(value);
|
|
1174
|
+
} catch {
|
|
1175
|
+
return String(value);
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
function isInsideRoots(cwd, file, roots) {
|
|
1179
|
+
if (typeof file !== "string" || !file) return false;
|
|
1180
|
+
const resolved = path.resolve(cwd, file);
|
|
1181
|
+
return roots.some((root) => {
|
|
1182
|
+
const rel = path.relative(root, resolved);
|
|
1183
|
+
return rel === "" || !rel.startsWith("..") && !path.isAbsolute(rel);
|
|
1184
|
+
});
|
|
1185
|
+
}
|
|
1186
|
+
function relativeToCwd(cwd, file) {
|
|
1187
|
+
if (typeof file !== "string" || !file) return null;
|
|
1188
|
+
const normalizedCwd = cwd.replace(/[\\/]+$/, "");
|
|
1189
|
+
if (file.startsWith(normalizedCwd)) return file.slice(normalizedCwd.length).replace(/^[\\/]+/, "") || ".";
|
|
1190
|
+
return file;
|
|
1191
|
+
}
|
|
1192
|
+
function parseQuestions(input) {
|
|
1193
|
+
const raw = Array.isArray(input.questions) ? input.questions : [];
|
|
1194
|
+
const questions = [];
|
|
1195
|
+
for (const q of raw) {
|
|
1196
|
+
if (!q || typeof q !== "object") continue;
|
|
1197
|
+
const r = q;
|
|
1198
|
+
const options = Array.isArray(r.options) ? r.options.map((o) => {
|
|
1199
|
+
if (!o || typeof o !== "object") return null;
|
|
1200
|
+
const opt = o;
|
|
1201
|
+
if (typeof opt.label !== "string") return null;
|
|
1202
|
+
return {
|
|
1203
|
+
label: opt.label,
|
|
1204
|
+
description: typeof opt.description === "string" ? opt.description : void 0
|
|
1205
|
+
};
|
|
1206
|
+
}).filter((o) => o !== null) : [];
|
|
1207
|
+
if (typeof r.question !== "string") continue;
|
|
1208
|
+
questions.push({
|
|
1209
|
+
header: typeof r.header === "string" ? r.header : "",
|
|
1210
|
+
question: r.question,
|
|
1211
|
+
options,
|
|
1212
|
+
multiSelect: r.multiSelect === true
|
|
1213
|
+
});
|
|
1214
|
+
}
|
|
1215
|
+
return questions;
|
|
1216
|
+
}
|
|
1217
|
+
//#endregion
|
|
1218
|
+
//#region src/agent/prompt.ts
|
|
1219
|
+
const PAGE_BY_PAGE = "Write a new deck page by page so the user can follow along on the canvas: first replace the file with the imports, meta (keeping its existing createdAt), design and the cover page only, then add each remaining page with its own separate edit, keeping the file compiling after every write.";
|
|
1220
|
+
const DECK_SLUG = "This deck's folder still has a placeholder name. Never rename or move the folder yourself: once the deck has content, end your final reply with a slug for it on a line of its own as <deck-slug>short-kebab-case-english-slug</deck-slug>, and LemonRiver renames the folder from it.";
|
|
1221
|
+
function systemPromptAppend(askInstruction) {
|
|
1222
|
+
return [
|
|
1223
|
+
"You are running inside the LemonRiver dev server, driven from its in-app agent panel in the browser rather than a terminal.",
|
|
1224
|
+
"The workspace is a LemonRiver project: decks live under slides/<id>/index.tsx and the dev server hot-reloads every edit, so the user sees changes immediately.",
|
|
1225
|
+
"Use the project skills: create-slide to draft a new deck, apply-comments to resolve @slide-comment markers left by the inspector, create-theme for themes, and slide-authoring as the technical reference before writing a page.",
|
|
1226
|
+
PAGE_BY_PAGE,
|
|
1227
|
+
"Keep replies short and concrete: the panel is narrow. Prefer doing the work over describing it, and finish with a one-line summary of what changed.",
|
|
1228
|
+
askInstruction
|
|
1229
|
+
].join(" ");
|
|
1230
|
+
}
|
|
1231
|
+
function buildTurnPrompt(text, context) {
|
|
1232
|
+
const lines = contextLines(context);
|
|
1233
|
+
if (lines.length === 0) return text;
|
|
1234
|
+
return `${text}\n\n<open-slide-context>\n${lines.join("\n")}\n</open-slide-context>`;
|
|
1235
|
+
}
|
|
1236
|
+
const escapeTag = (s) => s.replace(/</g, "<");
|
|
1237
|
+
function contextLines(context) {
|
|
1238
|
+
if (!context?.slideId) return [];
|
|
1239
|
+
const file = `slides/${context.slideId}/index.tsx`;
|
|
1240
|
+
const lines = [];
|
|
1241
|
+
if (context.newDeck) {
|
|
1242
|
+
lines.push(`${file} is a blank deck created for this request. Draft the deck the user describes into it with the create-slide skill: replace the placeholder page, keep the slide id, and do not create another folder.`, "Ask the create-slide scoping questions in a single round, only for what the request leaves unclear; skip any it already answers.", PAGE_BY_PAGE, DECK_SLUG);
|
|
1243
|
+
return lines;
|
|
1244
|
+
}
|
|
1245
|
+
lines.push(`The user is viewing slide "${context.slideId}": ${file}.`);
|
|
1246
|
+
if (UNTITLED_SLIDE_ID_RE.test(context.slideId)) lines.push(DECK_SLUG);
|
|
1247
|
+
if (context.slideTitle) lines.push(`<slide-title>${escapeTag(context.slideTitle)}</slide-title>`);
|
|
1248
|
+
if (context.pageNumber && context.totalPages) lines.push(`They are on page ${context.pageNumber} of ${context.totalPages} (0-based index ${context.pageNumber - 1} in the default export array).`);
|
|
1249
|
+
if (context.selection) {
|
|
1250
|
+
const { line, column, tagName, text } = context.selection;
|
|
1251
|
+
lines.push(`They have selected a <${escapeTag(tagName)}> element at ${file}:${line}:${column}.${text ? " Its text is in <selected-text>." : ""} "This element" refers to it.`);
|
|
1252
|
+
if (text) lines.push(`<selected-text>${escapeTag(text)}</selected-text>`);
|
|
1253
|
+
}
|
|
1254
|
+
if (context.pendingComments) lines.push(`There are ${context.pendingComments} pending @slide-comment markers in this slide's source.`);
|
|
1255
|
+
return lines;
|
|
1256
|
+
}
|
|
1257
|
+
const DECK_SLUG_RE = /\s*<deck-slug>\s*([^<]*?)\s*<\/deck-slug>\s*/gi;
|
|
1258
|
+
function extractDeckSlug(text) {
|
|
1259
|
+
let slug = null;
|
|
1260
|
+
for (const match of text.matchAll(DECK_SLUG_RE)) slug = match[1] || slug;
|
|
1261
|
+
return slug;
|
|
1262
|
+
}
|
|
1263
|
+
function stripDeckSlug(text) {
|
|
1264
|
+
return text.replace(DECK_SLUG_RE, "\n").replace(/\s*<deck-slug>[^<]*$/i, "").trimEnd();
|
|
1265
|
+
}
|
|
1266
|
+
const QUESTIONS_RE = /<open-slide-questions>([\s\S]*?)<\/open-slide-questions>/i;
|
|
1267
|
+
const TEXT_QUESTIONS_INSTRUCTION = "You cannot ask the user anything interactively here, and nothing you print in the middle of a turn can be answered. When you need answers before continuing, stop working and end your turn with a final message holding only an <open-slide-questions> block: a JSON array of at most 4 questions shaped like [{\"header\":\"Pages\",\"question\":\"How many pages?\",\"multiSelect\":false,\"options\":[{\"label\":\"6-10 (Recommended)\",\"description\":\"Standard length\"}]}], each with 2 to 4 options, written in the user's language. The panel shows them as a form and sends the answers back as your next message. Write nothing after the block and do not continue the task in the same turn.";
|
|
1268
|
+
function extractQuestionBlock(text) {
|
|
1269
|
+
const match = QUESTIONS_RE.exec(text);
|
|
1270
|
+
if (!match) return null;
|
|
1271
|
+
const body = match[1].trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "");
|
|
1272
|
+
let raw;
|
|
1273
|
+
try {
|
|
1274
|
+
raw = JSON.parse(body);
|
|
1275
|
+
} catch {
|
|
1276
|
+
return null;
|
|
1277
|
+
}
|
|
1278
|
+
const questions = parseQuestions({ questions: Array.isArray(raw) ? raw : raw?.questions });
|
|
1279
|
+
if (questions.length === 0) return null;
|
|
1280
|
+
return {
|
|
1281
|
+
text: text.replace(QUESTIONS_RE, "").trim(),
|
|
1282
|
+
questions
|
|
1283
|
+
};
|
|
1284
|
+
}
|
|
1285
|
+
function answersPrompt(questions, answers) {
|
|
1286
|
+
if (!answers) return "I skipped your questions. Continue the task with your best judgement and sensible defaults.";
|
|
1287
|
+
return `My answers:\n${questions.map((q) => `- ${q.question} ${answers[q.question] || "(no answer)"}`).join("\n")}\n\nContinue the task with these answers.`;
|
|
1288
|
+
}
|
|
1289
|
+
function editedPrompt(original, text) {
|
|
1290
|
+
return `I went back and edited an earlier message of mine. Treat everything after it in this conversation, including your replies, as discarded, and respond to the edited version instead. Files keep whatever changes were already made.\n\n<original-message>\n${escapeTag(original)}\n</original-message>\n\n${text}`;
|
|
1291
|
+
}
|
|
1292
|
+
function rewoundPrompt(text) {
|
|
1293
|
+
return `${text}\n\n<open-slide-note>I went back and edited this message. Files keep the changes made after it in the discarded part of this conversation, so read the current files before editing them.</open-slide-note>`;
|
|
1294
|
+
}
|
|
1295
|
+
//#endregion
|
|
1296
|
+
//#region src/agent/detect.ts
|
|
1297
|
+
const IS_WINDOWS = process.platform === "win32";
|
|
1298
|
+
const VERSION_TIMEOUT_MS = 5e3;
|
|
1299
|
+
function findOnPath(command, env = process.env) {
|
|
1300
|
+
const dirs = (env.PATH ?? env.Path ?? "").split(path.delimiter).filter(Boolean);
|
|
1301
|
+
const exts = IS_WINDOWS ? (env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";") : [""];
|
|
1302
|
+
for (const dir of dirs) for (const ext of exts) {
|
|
1303
|
+
const candidate = path.join(dir, command + ext.toLowerCase());
|
|
1304
|
+
try {
|
|
1305
|
+
if (statSync(candidate, { throwIfNoEntry: false })?.isFile()) return candidate;
|
|
1306
|
+
} catch {}
|
|
1307
|
+
}
|
|
1308
|
+
return null;
|
|
1309
|
+
}
|
|
1310
|
+
function findSpawnableCli(command, env = process.env) {
|
|
1311
|
+
const found = findOnPath(command, env);
|
|
1312
|
+
if (!found || !IS_WINDOWS) return found;
|
|
1313
|
+
return found.toLowerCase().endsWith(".exe") ? found : null;
|
|
1314
|
+
}
|
|
1315
|
+
const versionCache = /* @__PURE__ */ new Map();
|
|
1316
|
+
function commandVersion(file) {
|
|
1317
|
+
let cached = versionCache.get(file);
|
|
1318
|
+
if (!cached) {
|
|
1319
|
+
cached = readVersion(file);
|
|
1320
|
+
versionCache.set(file, cached);
|
|
1321
|
+
}
|
|
1322
|
+
return cached;
|
|
1323
|
+
}
|
|
1324
|
+
function readVersion(file) {
|
|
1325
|
+
return new Promise((resolve) => {
|
|
1326
|
+
let out = "";
|
|
1327
|
+
let child;
|
|
1328
|
+
try {
|
|
1329
|
+
child = spawn(file, ["--version"], {
|
|
1330
|
+
stdio: [
|
|
1331
|
+
"ignore",
|
|
1332
|
+
"pipe",
|
|
1333
|
+
"pipe"
|
|
1334
|
+
],
|
|
1335
|
+
shell: IS_WINDOWS,
|
|
1336
|
+
windowsHide: true
|
|
1337
|
+
});
|
|
1338
|
+
} catch {
|
|
1339
|
+
resolve(null);
|
|
1340
|
+
return;
|
|
1341
|
+
}
|
|
1342
|
+
const timer = setTimeout(() => {
|
|
1343
|
+
child.kill();
|
|
1344
|
+
resolve(null);
|
|
1345
|
+
}, VERSION_TIMEOUT_MS);
|
|
1346
|
+
child.stdout?.on("data", (c) => {
|
|
1347
|
+
out += c.toString("utf8");
|
|
1348
|
+
});
|
|
1349
|
+
child.stderr?.on("data", (c) => {
|
|
1350
|
+
out += c.toString("utf8");
|
|
1351
|
+
});
|
|
1352
|
+
child.on("error", () => {
|
|
1353
|
+
clearTimeout(timer);
|
|
1354
|
+
resolve(null);
|
|
1355
|
+
});
|
|
1356
|
+
child.on("close", () => {
|
|
1357
|
+
clearTimeout(timer);
|
|
1358
|
+
resolve(parseVersion(out));
|
|
1359
|
+
});
|
|
1360
|
+
});
|
|
1361
|
+
}
|
|
1362
|
+
function parseVersion(output) {
|
|
1363
|
+
const m = /(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)/.exec(output);
|
|
1364
|
+
return m ? m[1] : null;
|
|
1365
|
+
}
|
|
1366
|
+
function entryFromPackageJson(pkg) {
|
|
1367
|
+
const root = pickExport(pkg.exports);
|
|
1368
|
+
if (root) return root;
|
|
1369
|
+
return pkg.module ?? pkg.main ?? null;
|
|
1370
|
+
}
|
|
1371
|
+
function pickExport(exportsField) {
|
|
1372
|
+
if (!exportsField) return null;
|
|
1373
|
+
if (typeof exportsField === "string") return exportsField;
|
|
1374
|
+
if (typeof exportsField !== "object") return null;
|
|
1375
|
+
const record = exportsField;
|
|
1376
|
+
return pickCondition(Object.keys(record).some((k) => k.startsWith(".")) ? record["."] : exportsField);
|
|
1377
|
+
}
|
|
1378
|
+
function pickCondition(target) {
|
|
1379
|
+
if (!target) return null;
|
|
1380
|
+
if (typeof target === "string") return target;
|
|
1381
|
+
if (Array.isArray(target)) {
|
|
1382
|
+
for (const t of target) {
|
|
1383
|
+
const hit = pickCondition(t);
|
|
1384
|
+
if (hit) return hit;
|
|
1385
|
+
}
|
|
1386
|
+
return null;
|
|
1387
|
+
}
|
|
1388
|
+
if (typeof target !== "object") return null;
|
|
1389
|
+
const record = target;
|
|
1390
|
+
for (const key of [
|
|
1391
|
+
"import",
|
|
1392
|
+
"node",
|
|
1393
|
+
"default",
|
|
1394
|
+
"require"
|
|
1395
|
+
]) if (key in record) {
|
|
1396
|
+
const hit = pickCondition(record[key]);
|
|
1397
|
+
if (hit) return hit;
|
|
1398
|
+
}
|
|
1399
|
+
return null;
|
|
1400
|
+
}
|
|
1401
|
+
function resolveWorkspacePackage(userCwd, name) {
|
|
1402
|
+
let dir = path.resolve(userCwd);
|
|
1403
|
+
while (true) {
|
|
1404
|
+
const pkgJsonPath = path.join(dir, "node_modules", name, "package.json");
|
|
1405
|
+
if (existsSync(pkgJsonPath)) {
|
|
1406
|
+
let pkg;
|
|
1407
|
+
try {
|
|
1408
|
+
pkg = JSON.parse(readFileSync(pkgJsonPath, "utf8"));
|
|
1409
|
+
} catch {
|
|
1410
|
+
return null;
|
|
1411
|
+
}
|
|
1412
|
+
const entry = entryFromPackageJson(pkg);
|
|
1413
|
+
if (!entry) return null;
|
|
1414
|
+
const pkgDir = path.dirname(pkgJsonPath);
|
|
1415
|
+
return {
|
|
1416
|
+
dir: pkgDir,
|
|
1417
|
+
version: pkg.version ?? "0.0.0",
|
|
1418
|
+
entry: path.resolve(pkgDir, entry)
|
|
1419
|
+
};
|
|
1420
|
+
}
|
|
1421
|
+
const parent = path.dirname(dir);
|
|
1422
|
+
if (parent === dir) return null;
|
|
1423
|
+
dir = parent;
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
async function importWorkspacePackage(userCwd, name) {
|
|
1427
|
+
const resolved = resolveWorkspacePackage(userCwd, name);
|
|
1428
|
+
if (!resolved) return null;
|
|
1429
|
+
return await import(pathToFileURL(resolved.entry).href);
|
|
1430
|
+
}
|
|
1431
|
+
//#endregion
|
|
1432
|
+
//#region src/agent/providers/claude.ts
|
|
1433
|
+
const CLAUDE_SDK_PACKAGE = "@anthropic-ai/claude-agent-sdk";
|
|
1434
|
+
const CLAUDE_EFFORTS = [
|
|
1435
|
+
"low",
|
|
1436
|
+
"medium",
|
|
1437
|
+
"high",
|
|
1438
|
+
"xhigh",
|
|
1439
|
+
"max"
|
|
1440
|
+
];
|
|
1441
|
+
const CLAUDE_MODELS = [
|
|
1442
|
+
{
|
|
1443
|
+
id: "opus",
|
|
1444
|
+
label: "Opus",
|
|
1445
|
+
efforts: CLAUDE_EFFORTS
|
|
1446
|
+
},
|
|
1447
|
+
{
|
|
1448
|
+
id: "sonnet",
|
|
1449
|
+
label: "Sonnet",
|
|
1450
|
+
efforts: CLAUDE_EFFORTS
|
|
1451
|
+
},
|
|
1452
|
+
{
|
|
1453
|
+
id: "haiku",
|
|
1454
|
+
label: "Haiku",
|
|
1455
|
+
efforts: []
|
|
1456
|
+
}
|
|
1457
|
+
];
|
|
1458
|
+
const EDIT_TOOLS = /* @__PURE__ */ new Set([
|
|
1459
|
+
"Edit",
|
|
1460
|
+
"MultiEdit",
|
|
1461
|
+
"Write",
|
|
1462
|
+
"NotebookEdit"
|
|
1463
|
+
]);
|
|
1464
|
+
function claudeEffort(effort) {
|
|
1465
|
+
return effort && effort !== "minimal" ? effort : void 0;
|
|
1466
|
+
}
|
|
1467
|
+
function describeClaudeTool(name, input, cwd) {
|
|
1468
|
+
const file = relativeToCwd(cwd, input.file_path ?? input.path ?? input.notebook_path);
|
|
1469
|
+
switch (name) {
|
|
1470
|
+
case "Read": return {
|
|
1471
|
+
title: "Read",
|
|
1472
|
+
detail: file
|
|
1473
|
+
};
|
|
1474
|
+
case "Edit":
|
|
1475
|
+
case "MultiEdit":
|
|
1476
|
+
case "Write":
|
|
1477
|
+
case "NotebookEdit": return {
|
|
1478
|
+
title: name === "Write" ? "Write" : "Edit",
|
|
1479
|
+
detail: file
|
|
1480
|
+
};
|
|
1481
|
+
case "Bash": return {
|
|
1482
|
+
title: "Run command",
|
|
1483
|
+
detail: clipDetail(input.command)
|
|
1484
|
+
};
|
|
1485
|
+
case "Glob":
|
|
1486
|
+
case "Grep": return {
|
|
1487
|
+
title: "Search",
|
|
1488
|
+
detail: clipDetail(input.pattern)
|
|
1489
|
+
};
|
|
1490
|
+
case "WebFetch": return {
|
|
1491
|
+
title: "Fetch",
|
|
1492
|
+
detail: clipDetail(input.url)
|
|
1493
|
+
};
|
|
1494
|
+
case "WebSearch": return {
|
|
1495
|
+
title: "Web search",
|
|
1496
|
+
detail: clipDetail(input.query)
|
|
1497
|
+
};
|
|
1498
|
+
case "Skill": return {
|
|
1499
|
+
title: "Skill",
|
|
1500
|
+
detail: clipDetail(input.skill ?? input.name)
|
|
1501
|
+
};
|
|
1502
|
+
case "Task": return {
|
|
1503
|
+
title: "Subagent",
|
|
1504
|
+
detail: clipDetail(input.description)
|
|
1505
|
+
};
|
|
1506
|
+
case "AskUserQuestion": return {
|
|
1507
|
+
title: "Question",
|
|
1508
|
+
detail: null
|
|
1509
|
+
};
|
|
1510
|
+
case "TodoWrite": return {
|
|
1511
|
+
title: "Plan",
|
|
1512
|
+
detail: null
|
|
1513
|
+
};
|
|
1514
|
+
default: return {
|
|
1515
|
+
title: name,
|
|
1516
|
+
detail: clipDetail(input)
|
|
1517
|
+
};
|
|
1518
|
+
}
|
|
1519
|
+
}
|
|
1520
|
+
function createClaudeMapper(emit, cwd) {
|
|
1521
|
+
let counter = 0;
|
|
1522
|
+
const nextId = () => `t-${Date.now().toString(36)}-${(counter++).toString(36)}`;
|
|
1523
|
+
const textByIndex = /* @__PURE__ */ new Map();
|
|
1524
|
+
const openTextIds = [];
|
|
1525
|
+
let resultSeen = false;
|
|
1526
|
+
const handleBlocks = (blocks) => {
|
|
1527
|
+
for (const block of blocks) if (block.type === "text") {
|
|
1528
|
+
const { text } = block;
|
|
1529
|
+
const id = openTextIds.shift();
|
|
1530
|
+
if (id) emit({
|
|
1531
|
+
type: "text-end",
|
|
1532
|
+
id,
|
|
1533
|
+
text
|
|
1534
|
+
});
|
|
1535
|
+
else if (text.trim()) {
|
|
1536
|
+
const fresh = nextId();
|
|
1537
|
+
emit({
|
|
1538
|
+
type: "text-start",
|
|
1539
|
+
id: fresh
|
|
1540
|
+
});
|
|
1541
|
+
emit({
|
|
1542
|
+
type: "text-end",
|
|
1543
|
+
id: fresh,
|
|
1544
|
+
text
|
|
1545
|
+
});
|
|
1546
|
+
}
|
|
1547
|
+
} else if (block.type === "tool_use") {
|
|
1548
|
+
const { title, detail } = describeClaudeTool(block.name, block.input ?? {}, cwd);
|
|
1549
|
+
emit({
|
|
1550
|
+
type: "tool-start",
|
|
1551
|
+
id: block.id,
|
|
1552
|
+
name: block.name,
|
|
1553
|
+
title,
|
|
1554
|
+
detail
|
|
1555
|
+
});
|
|
1556
|
+
}
|
|
1557
|
+
textByIndex.clear();
|
|
1558
|
+
openTextIds.length = 0;
|
|
1559
|
+
};
|
|
1560
|
+
return {
|
|
1561
|
+
get resultSeen() {
|
|
1562
|
+
return resultSeen;
|
|
1563
|
+
},
|
|
1564
|
+
handle(msg) {
|
|
1565
|
+
if (!msg || typeof msg !== "object") return;
|
|
1566
|
+
if (msg.type === "system" && msg.subtype === "init") {
|
|
1567
|
+
emit({
|
|
1568
|
+
type: "session-id",
|
|
1569
|
+
id: msg.session_id
|
|
1570
|
+
});
|
|
1571
|
+
return;
|
|
1572
|
+
}
|
|
1573
|
+
if (msg.type === "stream_event") {
|
|
1574
|
+
if (msg.parent_tool_use_id) return;
|
|
1575
|
+
const ev = msg.event;
|
|
1576
|
+
if (ev.type === "content_block_start") {
|
|
1577
|
+
if (ev.content_block.type === "text") {
|
|
1578
|
+
const id = nextId();
|
|
1579
|
+
textByIndex.set(ev.index, id);
|
|
1580
|
+
openTextIds.push(id);
|
|
1581
|
+
emit({
|
|
1582
|
+
type: "text-start",
|
|
1583
|
+
id
|
|
1584
|
+
});
|
|
1585
|
+
}
|
|
1586
|
+
} else if (ev.type === "content_block_delta") {
|
|
1587
|
+
const id = textByIndex.get(ev.index);
|
|
1588
|
+
if (id && ev.delta.type === "text_delta" && ev.delta.text) emit({
|
|
1589
|
+
type: "text-delta",
|
|
1590
|
+
id,
|
|
1591
|
+
text: ev.delta.text
|
|
1592
|
+
});
|
|
1593
|
+
}
|
|
1594
|
+
return;
|
|
1595
|
+
}
|
|
1596
|
+
if (msg.type === "assistant") {
|
|
1597
|
+
if (msg.parent_tool_use_id) return;
|
|
1598
|
+
handleBlocks(msg.message?.content ?? []);
|
|
1599
|
+
if (msg.uuid) emit({
|
|
1600
|
+
type: "checkpoint",
|
|
1601
|
+
id: msg.uuid
|
|
1602
|
+
});
|
|
1603
|
+
return;
|
|
1604
|
+
}
|
|
1605
|
+
if (msg.type === "user") {
|
|
1606
|
+
if (msg.parent_tool_use_id) return;
|
|
1607
|
+
if (msg.uuid) emit({
|
|
1608
|
+
type: "checkpoint",
|
|
1609
|
+
id: msg.uuid
|
|
1610
|
+
});
|
|
1611
|
+
const content = msg.message?.content;
|
|
1612
|
+
if (!Array.isArray(content)) return;
|
|
1613
|
+
for (const block of content) if (block.type === "tool_result") emit({
|
|
1614
|
+
type: "tool-end",
|
|
1615
|
+
id: block.tool_use_id,
|
|
1616
|
+
ok: !block.is_error
|
|
1617
|
+
});
|
|
1618
|
+
return;
|
|
1619
|
+
}
|
|
1620
|
+
if (msg.type === "result") {
|
|
1621
|
+
resultSeen = true;
|
|
1622
|
+
if (msg.session_id) emit({
|
|
1623
|
+
type: "session-id",
|
|
1624
|
+
id: msg.session_id
|
|
1625
|
+
});
|
|
1626
|
+
if (msg.is_error || msg.subtype && msg.subtype !== "success") emit({
|
|
1627
|
+
type: "error",
|
|
1628
|
+
text: (Array.isArray(msg.errors) && msg.errors.length ? msg.errors.join("\n") : null) ?? (typeof msg.result === "string" && msg.result ? msg.result : null) ?? `Claude Code stopped: ${msg.subtype ?? "error"}`
|
|
1629
|
+
});
|
|
1630
|
+
emit({
|
|
1631
|
+
type: "result",
|
|
1632
|
+
durationMs: typeof msg.duration_ms === "number" ? msg.duration_ms : null,
|
|
1633
|
+
costUsd: typeof msg.total_cost_usd === "number" ? msg.total_cost_usd : null
|
|
1634
|
+
});
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1637
|
+
};
|
|
1638
|
+
}
|
|
1639
|
+
function createClaudeProvider() {
|
|
1640
|
+
return {
|
|
1641
|
+
id: "claude",
|
|
1642
|
+
name: "Claude Code",
|
|
1643
|
+
sdkPackage: CLAUDE_SDK_PACKAGE,
|
|
1644
|
+
cliCommand: "claude",
|
|
1645
|
+
askInstruction: "Ask the user questions with the AskUserQuestion tool, never as plain text.",
|
|
1646
|
+
canRewind: true,
|
|
1647
|
+
async models() {
|
|
1648
|
+
return CLAUDE_MODELS;
|
|
1649
|
+
},
|
|
1650
|
+
async run(opts) {
|
|
1651
|
+
const sdk = await importWorkspacePackage(opts.cwd, CLAUDE_SDK_PACKAGE);
|
|
1652
|
+
if (!sdk || typeof sdk.query !== "function") throw new ProviderUnavailableError(this);
|
|
1653
|
+
const mapper = createClaudeMapper(opts.emit, opts.cwd);
|
|
1654
|
+
if (opts.signal.aborted) return;
|
|
1655
|
+
const abortController = new AbortController();
|
|
1656
|
+
opts.signal.addEventListener("abort", () => abortController.abort(), { once: true });
|
|
1657
|
+
const canUseTool = async (toolName, input) => {
|
|
1658
|
+
if (toolName === "AskUserQuestion") {
|
|
1659
|
+
const questions = parseQuestions(input);
|
|
1660
|
+
const answers = await opts.askUser(questions);
|
|
1661
|
+
if (!answers) return {
|
|
1662
|
+
behavior: "deny",
|
|
1663
|
+
message: "The user dismissed the question."
|
|
1664
|
+
};
|
|
1665
|
+
return {
|
|
1666
|
+
behavior: "allow",
|
|
1667
|
+
updatedInput: {
|
|
1668
|
+
...input,
|
|
1669
|
+
answers
|
|
1670
|
+
}
|
|
1671
|
+
};
|
|
1672
|
+
}
|
|
1673
|
+
const target = input.file_path ?? input.notebook_path;
|
|
1674
|
+
if (EDIT_TOOLS.has(toolName) && isInsideRoots(opts.cwd, target, opts.writableRoots)) return {
|
|
1675
|
+
behavior: "allow",
|
|
1676
|
+
updatedInput: input
|
|
1677
|
+
};
|
|
1678
|
+
const { title, detail } = describeClaudeTool(toolName, input, opts.cwd);
|
|
1679
|
+
return await opts.requestPermission({
|
|
1680
|
+
tool: toolName,
|
|
1681
|
+
title,
|
|
1682
|
+
detail
|
|
1683
|
+
}) ? {
|
|
1684
|
+
behavior: "allow",
|
|
1685
|
+
updatedInput: input
|
|
1686
|
+
} : {
|
|
1687
|
+
behavior: "deny",
|
|
1688
|
+
message: "The user declined this action in the LemonRiver agent panel."
|
|
1689
|
+
};
|
|
1690
|
+
};
|
|
1691
|
+
const localCli = findSpawnableCli("claude");
|
|
1692
|
+
const effort = claudeEffort(opts.effort);
|
|
1693
|
+
let stderr = "";
|
|
1694
|
+
const stream = sdk.query({
|
|
1695
|
+
prompt: opts.prompt,
|
|
1696
|
+
options: {
|
|
1697
|
+
cwd: opts.cwd,
|
|
1698
|
+
permissionMode: "default",
|
|
1699
|
+
settingSources: [
|
|
1700
|
+
"user",
|
|
1701
|
+
"project",
|
|
1702
|
+
"local"
|
|
1703
|
+
],
|
|
1704
|
+
systemPrompt: {
|
|
1705
|
+
type: "preset",
|
|
1706
|
+
preset: "claude_code",
|
|
1707
|
+
append: opts.systemPromptAppend
|
|
1708
|
+
},
|
|
1709
|
+
includePartialMessages: true,
|
|
1710
|
+
abortController,
|
|
1711
|
+
canUseTool,
|
|
1712
|
+
...opts.resume ? { resume: opts.resume } : {},
|
|
1713
|
+
...opts.resume && opts.resumeAt ? { resumeSessionAt: opts.resumeAt } : {},
|
|
1714
|
+
...opts.model ? { model: opts.model } : {},
|
|
1715
|
+
...effort ? { effort } : {},
|
|
1716
|
+
...localCli ? { pathToClaudeCodeExecutable: localCli } : {},
|
|
1717
|
+
stderr: (data) => {
|
|
1718
|
+
stderr = (stderr + data).slice(-2e3);
|
|
1719
|
+
}
|
|
1720
|
+
}
|
|
1721
|
+
});
|
|
1722
|
+
try {
|
|
1723
|
+
for await (const message of stream) mapper.handle(message);
|
|
1724
|
+
} catch (err) {
|
|
1725
|
+
if (opts.signal.aborted || mapper.resultSeen) return;
|
|
1726
|
+
const base = err instanceof Error ? err.message : String(err);
|
|
1727
|
+
const tail = stderr.trim();
|
|
1728
|
+
throw new Error(tail && !base.includes(tail) ? `${base}\n${tail}` : base);
|
|
1729
|
+
}
|
|
1730
|
+
}
|
|
1731
|
+
};
|
|
1732
|
+
}
|
|
1733
|
+
//#endregion
|
|
1734
|
+
//#region src/agent/types.ts
|
|
1735
|
+
const AGENT_PROVIDER_IDS = ["claude", "codex"];
|
|
1736
|
+
const AGENT_EFFORTS = [
|
|
1737
|
+
"minimal",
|
|
1738
|
+
"low",
|
|
1739
|
+
"medium",
|
|
1740
|
+
"high",
|
|
1741
|
+
"xhigh",
|
|
1742
|
+
"max"
|
|
1743
|
+
];
|
|
1744
|
+
function isAgentProviderId(value) {
|
|
1745
|
+
return typeof value === "string" && AGENT_PROVIDER_IDS.includes(value);
|
|
1746
|
+
}
|
|
1747
|
+
function isAgentEffort(value) {
|
|
1748
|
+
return typeof value === "string" && AGENT_EFFORTS.includes(value);
|
|
1749
|
+
}
|
|
1750
|
+
function sessionSummary(session) {
|
|
1751
|
+
const { providerSessionId: _p, providerCheckpoint: _c, trimmed: _t, items: _i, ...summary } = session;
|
|
1752
|
+
return summary;
|
|
1753
|
+
}
|
|
1754
|
+
//#endregion
|
|
1755
|
+
//#region src/agent/providers/codex.ts
|
|
1756
|
+
const CODEX_SDK_PACKAGE = "@openai/codex-sdk";
|
|
1757
|
+
const CODEX_DEFAULT_MODEL = {
|
|
1758
|
+
id: "",
|
|
1759
|
+
label: "Default",
|
|
1760
|
+
efforts: [
|
|
1761
|
+
"low",
|
|
1762
|
+
"medium",
|
|
1763
|
+
"high"
|
|
1764
|
+
]
|
|
1765
|
+
};
|
|
1766
|
+
function parseCodexModelsCache(raw) {
|
|
1767
|
+
const list = raw?.models;
|
|
1768
|
+
if (!Array.isArray(list)) return [];
|
|
1769
|
+
const models = [];
|
|
1770
|
+
for (const entry of list) {
|
|
1771
|
+
if (!entry || typeof entry !== "object") continue;
|
|
1772
|
+
const m = entry;
|
|
1773
|
+
if (typeof m.slug !== "string" || !m.slug) continue;
|
|
1774
|
+
if (m.visibility !== void 0 && m.visibility !== "list") continue;
|
|
1775
|
+
const efforts = (Array.isArray(m.supported_reasoning_levels) ? m.supported_reasoning_levels : []).map((l) => l && typeof l === "object" ? l.effort : l).filter(isAgentEffort);
|
|
1776
|
+
models.push({
|
|
1777
|
+
option: {
|
|
1778
|
+
id: m.slug,
|
|
1779
|
+
label: typeof m.display_name === "string" && m.display_name ? m.display_name : m.slug,
|
|
1780
|
+
efforts
|
|
1781
|
+
},
|
|
1782
|
+
priority: typeof m.priority === "number" ? m.priority : Number.MAX_SAFE_INTEGER
|
|
1783
|
+
});
|
|
1784
|
+
}
|
|
1785
|
+
return models.sort((a, b) => a.priority - b.priority).map((m) => m.option);
|
|
1786
|
+
}
|
|
1787
|
+
async function readCodexModels() {
|
|
1788
|
+
const home = process.env.CODEX_HOME || path.join(os.homedir(), ".codex");
|
|
1789
|
+
try {
|
|
1790
|
+
const models = parseCodexModelsCache(JSON.parse(await fs.readFile(path.join(home, "models_cache.json"), "utf8")));
|
|
1791
|
+
return models.length > 0 ? models : [CODEX_DEFAULT_MODEL];
|
|
1792
|
+
} catch {
|
|
1793
|
+
return [CODEX_DEFAULT_MODEL];
|
|
1794
|
+
}
|
|
1795
|
+
}
|
|
1796
|
+
function createCodexMapper(emit) {
|
|
1797
|
+
const started = /* @__PURE__ */ new Set();
|
|
1798
|
+
let resultSeen = false;
|
|
1799
|
+
const startTool = (item, name, title, detail) => {
|
|
1800
|
+
if (started.has(item.id)) return;
|
|
1801
|
+
started.add(item.id);
|
|
1802
|
+
emit({
|
|
1803
|
+
type: "tool-start",
|
|
1804
|
+
id: item.id,
|
|
1805
|
+
name,
|
|
1806
|
+
title,
|
|
1807
|
+
detail
|
|
1808
|
+
});
|
|
1809
|
+
};
|
|
1810
|
+
const describe = (item) => {
|
|
1811
|
+
switch (item.type) {
|
|
1812
|
+
case "command_execution": return {
|
|
1813
|
+
name: "command",
|
|
1814
|
+
title: "Run command",
|
|
1815
|
+
detail: clipDetail(item.command)
|
|
1816
|
+
};
|
|
1817
|
+
case "file_change": return {
|
|
1818
|
+
name: "file_change",
|
|
1819
|
+
title: "Edit",
|
|
1820
|
+
detail: clipDetail(item.changes.map((c) => c.path).join(", "))
|
|
1821
|
+
};
|
|
1822
|
+
case "mcp_tool_call": return {
|
|
1823
|
+
name: "mcp",
|
|
1824
|
+
title: `${item.server}: ${item.tool}`,
|
|
1825
|
+
detail: null
|
|
1826
|
+
};
|
|
1827
|
+
case "web_search": return {
|
|
1828
|
+
name: "web_search",
|
|
1829
|
+
title: "Web search",
|
|
1830
|
+
detail: clipDetail(item.query)
|
|
1831
|
+
};
|
|
1832
|
+
default: return {
|
|
1833
|
+
name: item.type,
|
|
1834
|
+
title: item.type,
|
|
1835
|
+
detail: null
|
|
1836
|
+
};
|
|
1837
|
+
}
|
|
1838
|
+
};
|
|
1839
|
+
const handleItem = (phase, item) => {
|
|
1840
|
+
switch (item.type) {
|
|
1841
|
+
case "agent_message": {
|
|
1842
|
+
if (phase !== "completed" || !item.text.trim()) return;
|
|
1843
|
+
const asked = extractQuestionBlock(item.text);
|
|
1844
|
+
const text = asked ? asked.text : item.text;
|
|
1845
|
+
if (text) {
|
|
1846
|
+
emit({
|
|
1847
|
+
type: "text-start",
|
|
1848
|
+
id: item.id
|
|
1849
|
+
});
|
|
1850
|
+
emit({
|
|
1851
|
+
type: "text-end",
|
|
1852
|
+
id: item.id,
|
|
1853
|
+
text
|
|
1854
|
+
});
|
|
1855
|
+
}
|
|
1856
|
+
if (asked) emit({
|
|
1857
|
+
type: "questions",
|
|
1858
|
+
questions: asked.questions
|
|
1859
|
+
});
|
|
1860
|
+
return;
|
|
1861
|
+
}
|
|
1862
|
+
case "error":
|
|
1863
|
+
if (phase === "completed") emit({
|
|
1864
|
+
type: "error",
|
|
1865
|
+
text: item.message
|
|
1866
|
+
});
|
|
1867
|
+
return;
|
|
1868
|
+
case "command_execution":
|
|
1869
|
+
case "file_change":
|
|
1870
|
+
case "mcp_tool_call":
|
|
1871
|
+
case "web_search": {
|
|
1872
|
+
const { name, title, detail } = describe(item);
|
|
1873
|
+
startTool(item, name, title, detail);
|
|
1874
|
+
if (phase === "completed") {
|
|
1875
|
+
const status = "status" in item ? item.status : "completed";
|
|
1876
|
+
emit({
|
|
1877
|
+
type: "tool-end",
|
|
1878
|
+
id: item.id,
|
|
1879
|
+
ok: status !== "failed"
|
|
1880
|
+
});
|
|
1881
|
+
}
|
|
1882
|
+
return;
|
|
1883
|
+
}
|
|
1884
|
+
default: return;
|
|
1885
|
+
}
|
|
1886
|
+
};
|
|
1887
|
+
return {
|
|
1888
|
+
get resultSeen() {
|
|
1889
|
+
return resultSeen;
|
|
1890
|
+
},
|
|
1891
|
+
handle(event) {
|
|
1892
|
+
if (!event || typeof event !== "object") return;
|
|
1893
|
+
switch (event.type) {
|
|
1894
|
+
case "thread.started":
|
|
1895
|
+
emit({
|
|
1896
|
+
type: "session-id",
|
|
1897
|
+
id: event.thread_id
|
|
1898
|
+
});
|
|
1899
|
+
return;
|
|
1900
|
+
case "item.started":
|
|
1901
|
+
handleItem("started", event.item);
|
|
1902
|
+
return;
|
|
1903
|
+
case "item.updated":
|
|
1904
|
+
handleItem("updated", event.item);
|
|
1905
|
+
return;
|
|
1906
|
+
case "item.completed":
|
|
1907
|
+
handleItem("completed", event.item);
|
|
1908
|
+
return;
|
|
1909
|
+
case "turn.failed":
|
|
1910
|
+
resultSeen = true;
|
|
1911
|
+
emit({
|
|
1912
|
+
type: "error",
|
|
1913
|
+
text: event.error.message
|
|
1914
|
+
});
|
|
1915
|
+
emit({
|
|
1916
|
+
type: "result",
|
|
1917
|
+
durationMs: null,
|
|
1918
|
+
costUsd: null
|
|
1919
|
+
});
|
|
1920
|
+
return;
|
|
1921
|
+
case "error":
|
|
1922
|
+
emit({
|
|
1923
|
+
type: "error",
|
|
1924
|
+
text: event.message
|
|
1925
|
+
});
|
|
1926
|
+
return;
|
|
1927
|
+
case "turn.completed":
|
|
1928
|
+
resultSeen = true;
|
|
1929
|
+
emit({
|
|
1930
|
+
type: "result",
|
|
1931
|
+
durationMs: null,
|
|
1932
|
+
costUsd: null
|
|
1933
|
+
});
|
|
1934
|
+
return;
|
|
1935
|
+
default: return;
|
|
1936
|
+
}
|
|
1937
|
+
}
|
|
1938
|
+
};
|
|
1939
|
+
}
|
|
1940
|
+
function createCodexProvider() {
|
|
1941
|
+
return {
|
|
1942
|
+
id: "codex",
|
|
1943
|
+
name: "Codex",
|
|
1944
|
+
sdkPackage: CODEX_SDK_PACKAGE,
|
|
1945
|
+
askInstruction: TEXT_QUESTIONS_INSTRUCTION,
|
|
1946
|
+
canRewind: false,
|
|
1947
|
+
cliCommand: "codex",
|
|
1948
|
+
models: readCodexModels,
|
|
1949
|
+
async run(opts) {
|
|
1950
|
+
const sdk = await importWorkspacePackage(opts.cwd, CODEX_SDK_PACKAGE);
|
|
1951
|
+
if (!sdk || typeof sdk.Codex !== "function") throw new ProviderUnavailableError(this);
|
|
1952
|
+
const localCli = findSpawnableCli("codex");
|
|
1953
|
+
const codex = new sdk.Codex(localCli ? { codexPathOverride: localCli } : {});
|
|
1954
|
+
const threadOptions = {
|
|
1955
|
+
workingDirectory: opts.cwd,
|
|
1956
|
+
skipGitRepoCheck: true,
|
|
1957
|
+
sandboxMode: "workspace-write",
|
|
1958
|
+
approvalPolicy: "never",
|
|
1959
|
+
...opts.model ? { model: opts.model } : {},
|
|
1960
|
+
...opts.effort ? { modelReasoningEffort: opts.effort } : {}
|
|
1961
|
+
};
|
|
1962
|
+
const thread = opts.resume ? codex.resumeThread(opts.resume, threadOptions) : codex.startThread(threadOptions);
|
|
1963
|
+
const input = opts.resume ? opts.prompt : `${opts.systemPromptAppend}\n\n${opts.prompt}`;
|
|
1964
|
+
const mapper = createCodexMapper(opts.emit);
|
|
1965
|
+
const { events } = await thread.runStreamed(input, { signal: opts.signal });
|
|
1966
|
+
try {
|
|
1967
|
+
for await (const event of events) mapper.handle(event);
|
|
1968
|
+
} catch (err) {
|
|
1969
|
+
if (opts.signal.aborted || mapper.resultSeen) return;
|
|
1970
|
+
throw err;
|
|
1971
|
+
}
|
|
1972
|
+
if (thread.id) opts.emit({
|
|
1973
|
+
type: "session-id",
|
|
1974
|
+
id: thread.id
|
|
1975
|
+
});
|
|
1976
|
+
}
|
|
1977
|
+
};
|
|
1978
|
+
}
|
|
1979
|
+
//#endregion
|
|
1980
|
+
//#region src/agent/providers/index.ts
|
|
1981
|
+
function createProviders() {
|
|
1982
|
+
return {
|
|
1983
|
+
claude: createClaudeProvider(),
|
|
1984
|
+
codex: createCodexProvider()
|
|
1985
|
+
};
|
|
1986
|
+
}
|
|
1987
|
+
//#endregion
|
|
1988
|
+
//#region src/agent/store.ts
|
|
1989
|
+
const MAX_SESSIONS = 30;
|
|
1990
|
+
const MAX_ITEMS_PER_SESSION = 400;
|
|
1991
|
+
const SAVE_DEBOUNCE_MS = 150;
|
|
1992
|
+
const TITLE_MAX = 60;
|
|
1993
|
+
function newId(prefix) {
|
|
1994
|
+
return `${prefix}-${randomBytes(6).toString("hex")}`;
|
|
1995
|
+
}
|
|
1996
|
+
function titleFromPrompt(text) {
|
|
1997
|
+
const line = text.split("\n").map((l) => l.trim()).find((l) => l.length > 0);
|
|
1998
|
+
if (!line) return "Untitled";
|
|
1999
|
+
return line.length > TITLE_MAX ? `${line.slice(0, 59)}…` : line;
|
|
2000
|
+
}
|
|
2001
|
+
function readPersisted(file) {
|
|
2002
|
+
if (!existsSync(file)) return [];
|
|
2003
|
+
try {
|
|
2004
|
+
const parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
2005
|
+
if (parsed?.version !== 1 || !Array.isArray(parsed.sessions)) return [];
|
|
2006
|
+
return parsed.sessions.map((s) => ({
|
|
2007
|
+
...s,
|
|
2008
|
+
status: "idle",
|
|
2009
|
+
items: s.items.map(closePending)
|
|
2010
|
+
}));
|
|
2011
|
+
} catch {
|
|
2012
|
+
return [];
|
|
2013
|
+
}
|
|
2014
|
+
}
|
|
2015
|
+
function closePending(item) {
|
|
2016
|
+
if (item.kind === "assistant" && item.streaming) return {
|
|
2017
|
+
...item,
|
|
2018
|
+
streaming: false
|
|
2019
|
+
};
|
|
2020
|
+
if (item.kind === "tool" && item.status === "running") return {
|
|
2021
|
+
...item,
|
|
2022
|
+
status: "error"
|
|
2023
|
+
};
|
|
2024
|
+
if (item.kind === "question" && item.status === "pending") return {
|
|
2025
|
+
...item,
|
|
2026
|
+
status: "cancelled"
|
|
2027
|
+
};
|
|
2028
|
+
if (item.kind === "permission" && item.status === "pending") return {
|
|
2029
|
+
...item,
|
|
2030
|
+
status: "denied"
|
|
2031
|
+
};
|
|
2032
|
+
return item;
|
|
2033
|
+
}
|
|
2034
|
+
function createSessionStore(opts) {
|
|
2035
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
2036
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
2037
|
+
let saveTimer = null;
|
|
2038
|
+
let seq = 0;
|
|
2039
|
+
const order = /* @__PURE__ */ new Map();
|
|
2040
|
+
if (opts.file) for (const s of readPersisted(opts.file)) {
|
|
2041
|
+
sessions.set(s.id, s);
|
|
2042
|
+
order.set(s.id, seq++);
|
|
2043
|
+
}
|
|
2044
|
+
const emit = (event) => {
|
|
2045
|
+
for (const l of listeners) l(event);
|
|
2046
|
+
};
|
|
2047
|
+
const scheduleSave = () => {
|
|
2048
|
+
if (!opts.file) return;
|
|
2049
|
+
if (saveTimer) clearTimeout(saveTimer);
|
|
2050
|
+
saveTimer = setTimeout(() => {
|
|
2051
|
+
saveTimer = null;
|
|
2052
|
+
save();
|
|
2053
|
+
}, SAVE_DEBOUNCE_MS);
|
|
2054
|
+
};
|
|
2055
|
+
const writeSnapshot = async (file) => {
|
|
2056
|
+
const body = {
|
|
2057
|
+
version: 1,
|
|
2058
|
+
sessions: list().flatMap((s) => sessions.get(s.id) ?? [])
|
|
2059
|
+
};
|
|
2060
|
+
const tmp = `${file}.tmp`;
|
|
2061
|
+
try {
|
|
2062
|
+
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
2063
|
+
await fs.writeFile(tmp, JSON.stringify(body), {
|
|
2064
|
+
encoding: "utf8",
|
|
2065
|
+
mode: 384
|
|
2066
|
+
});
|
|
2067
|
+
await fs.rename(tmp, file);
|
|
2068
|
+
} catch (err) {
|
|
2069
|
+
console.error("[open-slide] failed to save agent sessions:", err);
|
|
2070
|
+
await fs.rm(tmp, { force: true }).catch(() => {});
|
|
2071
|
+
}
|
|
2072
|
+
};
|
|
2073
|
+
let saving = Promise.resolve();
|
|
2074
|
+
const save = () => {
|
|
2075
|
+
const file = opts.file;
|
|
2076
|
+
if (!file) return saving;
|
|
2077
|
+
saving = saving.then(() => writeSnapshot(file));
|
|
2078
|
+
return saving;
|
|
2079
|
+
};
|
|
2080
|
+
const touch = (session) => {
|
|
2081
|
+
session.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
2082
|
+
order.set(session.id, seq++);
|
|
2083
|
+
emit({
|
|
2084
|
+
type: "session",
|
|
2085
|
+
session: sessionSummary(session)
|
|
2086
|
+
});
|
|
2087
|
+
scheduleSave();
|
|
2088
|
+
};
|
|
2089
|
+
const require = (id) => {
|
|
2090
|
+
const session = sessions.get(id);
|
|
2091
|
+
if (!session) throw new Error(`unknown agent session: ${id}`);
|
|
2092
|
+
return session;
|
|
2093
|
+
};
|
|
2094
|
+
function list() {
|
|
2095
|
+
return Array.from(sessions.values()).sort((a, b) => {
|
|
2096
|
+
if (a.updatedAt !== b.updatedAt) return a.updatedAt < b.updatedAt ? 1 : -1;
|
|
2097
|
+
return (order.get(b.id) ?? 0) - (order.get(a.id) ?? 0);
|
|
2098
|
+
}).map(sessionSummary);
|
|
2099
|
+
}
|
|
2100
|
+
function get(id) {
|
|
2101
|
+
return sessions.get(id) ?? null;
|
|
2102
|
+
}
|
|
2103
|
+
function create(provider, slideId) {
|
|
2104
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
2105
|
+
const session = {
|
|
2106
|
+
id: newId("s"),
|
|
2107
|
+
provider,
|
|
2108
|
+
title: "New session",
|
|
2109
|
+
createdAt: now,
|
|
2110
|
+
updatedAt: now,
|
|
2111
|
+
status: "idle",
|
|
2112
|
+
slideId,
|
|
2113
|
+
providerSessionId: null,
|
|
2114
|
+
items: []
|
|
2115
|
+
};
|
|
2116
|
+
sessions.set(session.id, session);
|
|
2117
|
+
order.set(session.id, seq++);
|
|
2118
|
+
const idle = list().filter((s) => s.status === "idle");
|
|
2119
|
+
for (const stale of idle.slice(MAX_SESSIONS)) {
|
|
2120
|
+
sessions.delete(stale.id);
|
|
2121
|
+
order.delete(stale.id);
|
|
2122
|
+
emit({
|
|
2123
|
+
type: "session-removed",
|
|
2124
|
+
sessionId: stale.id
|
|
2125
|
+
});
|
|
2126
|
+
}
|
|
2127
|
+
touch(session);
|
|
2128
|
+
return session;
|
|
2129
|
+
}
|
|
2130
|
+
function remove(id) {
|
|
2131
|
+
if (!sessions.delete(id)) return false;
|
|
2132
|
+
order.delete(id);
|
|
2133
|
+
emit({
|
|
2134
|
+
type: "session-removed",
|
|
2135
|
+
sessionId: id
|
|
2136
|
+
});
|
|
2137
|
+
scheduleSave();
|
|
2138
|
+
return true;
|
|
2139
|
+
}
|
|
2140
|
+
function patch(id, changes) {
|
|
2141
|
+
const session = require(id);
|
|
2142
|
+
Object.assign(session, changes);
|
|
2143
|
+
touch(session);
|
|
2144
|
+
return session;
|
|
2145
|
+
}
|
|
2146
|
+
function appendItem(sessionId, item) {
|
|
2147
|
+
const session = require(sessionId);
|
|
2148
|
+
session.items.push(item);
|
|
2149
|
+
if (session.items.length > MAX_ITEMS_PER_SESSION) {
|
|
2150
|
+
session.items.splice(0, session.items.length - MAX_ITEMS_PER_SESSION);
|
|
2151
|
+
session.trimmed = true;
|
|
2152
|
+
}
|
|
2153
|
+
emit({
|
|
2154
|
+
type: "item",
|
|
2155
|
+
sessionId,
|
|
2156
|
+
item
|
|
2157
|
+
});
|
|
2158
|
+
touch(session);
|
|
2159
|
+
return item;
|
|
2160
|
+
}
|
|
2161
|
+
function updateItem(sessionId, itemId, kind, changes) {
|
|
2162
|
+
const session = require(sessionId);
|
|
2163
|
+
const index = session.items.findIndex((i) => i.id === itemId && i.kind === kind);
|
|
2164
|
+
if (index === -1) return null;
|
|
2165
|
+
const next = {
|
|
2166
|
+
...session.items[index],
|
|
2167
|
+
...changes
|
|
2168
|
+
};
|
|
2169
|
+
session.items[index] = next;
|
|
2170
|
+
emit({
|
|
2171
|
+
type: "item",
|
|
2172
|
+
sessionId,
|
|
2173
|
+
item: next
|
|
2174
|
+
});
|
|
2175
|
+
touch(session);
|
|
2176
|
+
return next;
|
|
2177
|
+
}
|
|
2178
|
+
function truncateFrom(sessionId, itemId) {
|
|
2179
|
+
const session = require(sessionId);
|
|
2180
|
+
const index = session.items.findIndex((i) => i.id === itemId);
|
|
2181
|
+
if (index === -1) return false;
|
|
2182
|
+
session.items.splice(index);
|
|
2183
|
+
emit({
|
|
2184
|
+
type: "truncate",
|
|
2185
|
+
sessionId,
|
|
2186
|
+
itemId
|
|
2187
|
+
});
|
|
2188
|
+
touch(session);
|
|
2189
|
+
return true;
|
|
2190
|
+
}
|
|
2191
|
+
function appendDelta(sessionId, itemId, text) {
|
|
2192
|
+
if (!text) return;
|
|
2193
|
+
const item = require(sessionId).items.find((i) => i.id === itemId);
|
|
2194
|
+
if (item?.kind !== "assistant") return;
|
|
2195
|
+
item.text += text;
|
|
2196
|
+
emit({
|
|
2197
|
+
type: "delta",
|
|
2198
|
+
sessionId,
|
|
2199
|
+
itemId,
|
|
2200
|
+
text
|
|
2201
|
+
});
|
|
2202
|
+
scheduleSave();
|
|
2203
|
+
}
|
|
2204
|
+
function subscribe(listener) {
|
|
2205
|
+
listeners.add(listener);
|
|
2206
|
+
return () => {
|
|
2207
|
+
listeners.delete(listener);
|
|
2208
|
+
};
|
|
2209
|
+
}
|
|
2210
|
+
async function flush() {
|
|
2211
|
+
if (saveTimer) {
|
|
2212
|
+
clearTimeout(saveTimer);
|
|
2213
|
+
saveTimer = null;
|
|
2214
|
+
}
|
|
2215
|
+
await save();
|
|
2216
|
+
}
|
|
2217
|
+
return {
|
|
2218
|
+
list,
|
|
2219
|
+
get,
|
|
2220
|
+
create,
|
|
2221
|
+
remove,
|
|
2222
|
+
patch,
|
|
2223
|
+
appendItem,
|
|
2224
|
+
updateItem,
|
|
2225
|
+
truncateFrom,
|
|
2226
|
+
appendDelta,
|
|
2227
|
+
subscribe,
|
|
2228
|
+
flush
|
|
2229
|
+
};
|
|
2230
|
+
}
|
|
2231
|
+
//#endregion
|
|
2232
|
+
//#region src/agent/runner.ts
|
|
2233
|
+
function cancelPrompt(prompt) {
|
|
2234
|
+
if (prompt.kind === "question") prompt.resolve(null);
|
|
2235
|
+
else prompt.resolve(false);
|
|
2236
|
+
}
|
|
2237
|
+
function createAgentRunner(opts) {
|
|
2238
|
+
const { userCwd, writableRoots, store, providers, onTurnEnd } = opts;
|
|
2239
|
+
const running = /* @__PURE__ */ new Map();
|
|
2240
|
+
const pending = /* @__PURE__ */ new Map();
|
|
2241
|
+
const lastOptions = /* @__PURE__ */ new Map();
|
|
2242
|
+
const now = () => (/* @__PURE__ */ new Date()).toISOString();
|
|
2243
|
+
function isRunning(sessionId) {
|
|
2244
|
+
return running.has(sessionId);
|
|
2245
|
+
}
|
|
2246
|
+
async function send(sessionId, options) {
|
|
2247
|
+
const session = store.get(sessionId);
|
|
2248
|
+
if (!session) throw new Error(`unknown agent session: ${sessionId}`);
|
|
2249
|
+
if (running.has(sessionId)) throw new Error("session is already running");
|
|
2250
|
+
const text = options.text.trim();
|
|
2251
|
+
if (!text) throw new Error("empty prompt");
|
|
2252
|
+
const provider = providers[session.provider];
|
|
2253
|
+
let context = options.context;
|
|
2254
|
+
let promptText = text;
|
|
2255
|
+
let resumeAt = null;
|
|
2256
|
+
if (options.edit) {
|
|
2257
|
+
const index = session.items.findIndex((i) => i.id === options.edit);
|
|
2258
|
+
const target = session.items[index];
|
|
2259
|
+
if (target?.kind !== "user") throw new Error("unknown message");
|
|
2260
|
+
if (!session.trimmed && !session.items.slice(0, index).some((i) => i.kind === "user")) {
|
|
2261
|
+
store.patch(sessionId, {
|
|
2262
|
+
providerSessionId: null,
|
|
2263
|
+
providerCheckpoint: null
|
|
2264
|
+
});
|
|
2265
|
+
if (target.newDeck && context) context = {
|
|
2266
|
+
...context,
|
|
2267
|
+
newDeck: true
|
|
2268
|
+
};
|
|
2269
|
+
} else if (provider.canRewind && target.resumeAt) {
|
|
2270
|
+
resumeAt = target.resumeAt;
|
|
2271
|
+
store.patch(sessionId, { providerCheckpoint: resumeAt });
|
|
2272
|
+
promptText = rewoundPrompt(text);
|
|
2273
|
+
} else promptText = editedPrompt(target.text, text);
|
|
2274
|
+
store.truncateFrom(sessionId, target.id);
|
|
2275
|
+
}
|
|
2276
|
+
const controller = new AbortController();
|
|
2277
|
+
running.set(sessionId, controller);
|
|
2278
|
+
lastOptions.set(sessionId, {
|
|
2279
|
+
...options,
|
|
2280
|
+
context,
|
|
2281
|
+
edit: void 0
|
|
2282
|
+
});
|
|
2283
|
+
if (session.items.length === 0) store.patch(sessionId, { title: titleFromPrompt(text) });
|
|
2284
|
+
if (options.context?.slideId && !session.slideId) store.patch(sessionId, { slideId: options.context.slideId });
|
|
2285
|
+
for (const item of session.items) if (item.kind === "question" && item.status === "pending" && item.id !== options.answering) store.updateItem(sessionId, item.id, "question", { status: "cancelled" });
|
|
2286
|
+
const userItemId = options.answering ?? newId("u");
|
|
2287
|
+
if (!options.answering) store.appendItem(sessionId, {
|
|
2288
|
+
kind: "user",
|
|
2289
|
+
id: userItemId,
|
|
2290
|
+
ts: now(),
|
|
2291
|
+
text,
|
|
2292
|
+
...session.providerCheckpoint ? { resumeAt: session.providerCheckpoint } : {},
|
|
2293
|
+
...context?.newDeck ? { newDeck: true } : {}
|
|
2294
|
+
});
|
|
2295
|
+
store.patch(sessionId, { status: "running" });
|
|
2296
|
+
const openText = /* @__PURE__ */ new Set();
|
|
2297
|
+
const openTools = /* @__PURE__ */ new Set();
|
|
2298
|
+
const startedAt = Date.now();
|
|
2299
|
+
let resultSeen = false;
|
|
2300
|
+
const appendQuestion = (questions) => store.appendItem(sessionId, {
|
|
2301
|
+
kind: "question",
|
|
2302
|
+
id: newId("q"),
|
|
2303
|
+
ts: now(),
|
|
2304
|
+
questions,
|
|
2305
|
+
answers: null,
|
|
2306
|
+
status: "pending"
|
|
2307
|
+
});
|
|
2308
|
+
const emit = (event) => {
|
|
2309
|
+
if (!store.get(sessionId)) return;
|
|
2310
|
+
switch (event.type) {
|
|
2311
|
+
case "session-id":
|
|
2312
|
+
store.patch(sessionId, { providerSessionId: event.id });
|
|
2313
|
+
return;
|
|
2314
|
+
case "checkpoint":
|
|
2315
|
+
store.patch(sessionId, { providerCheckpoint: event.id });
|
|
2316
|
+
return;
|
|
2317
|
+
case "text-start":
|
|
2318
|
+
openText.add(event.id);
|
|
2319
|
+
store.appendItem(sessionId, {
|
|
2320
|
+
kind: "assistant",
|
|
2321
|
+
id: event.id,
|
|
2322
|
+
ts: now(),
|
|
2323
|
+
text: "",
|
|
2324
|
+
streaming: true
|
|
2325
|
+
});
|
|
2326
|
+
return;
|
|
2327
|
+
case "text-delta":
|
|
2328
|
+
if (!openText.has(event.id)) emit({
|
|
2329
|
+
type: "text-start",
|
|
2330
|
+
id: event.id
|
|
2331
|
+
});
|
|
2332
|
+
store.appendDelta(sessionId, event.id, event.text);
|
|
2333
|
+
return;
|
|
2334
|
+
case "text-end": {
|
|
2335
|
+
if (!openText.has(event.id)) {
|
|
2336
|
+
if (!event.text) return;
|
|
2337
|
+
emit({
|
|
2338
|
+
type: "text-start",
|
|
2339
|
+
id: event.id
|
|
2340
|
+
});
|
|
2341
|
+
}
|
|
2342
|
+
openText.delete(event.id);
|
|
2343
|
+
const changes = event.text !== null ? {
|
|
2344
|
+
streaming: false,
|
|
2345
|
+
text: event.text
|
|
2346
|
+
} : { streaming: false };
|
|
2347
|
+
store.updateItem(sessionId, event.id, "assistant", changes);
|
|
2348
|
+
return;
|
|
2349
|
+
}
|
|
2350
|
+
case "tool-start":
|
|
2351
|
+
openTools.add(event.id);
|
|
2352
|
+
store.appendItem(sessionId, {
|
|
2353
|
+
kind: "tool",
|
|
2354
|
+
id: event.id,
|
|
2355
|
+
ts: now(),
|
|
2356
|
+
name: event.name,
|
|
2357
|
+
title: event.title,
|
|
2358
|
+
detail: event.detail,
|
|
2359
|
+
status: "running"
|
|
2360
|
+
});
|
|
2361
|
+
return;
|
|
2362
|
+
case "tool-end":
|
|
2363
|
+
openTools.delete(event.id);
|
|
2364
|
+
store.updateItem(sessionId, event.id, "tool", { status: event.ok ? "done" : "error" });
|
|
2365
|
+
return;
|
|
2366
|
+
case "error":
|
|
2367
|
+
store.appendItem(sessionId, {
|
|
2368
|
+
kind: "error",
|
|
2369
|
+
id: newId("e"),
|
|
2370
|
+
ts: now(),
|
|
2371
|
+
text: event.text
|
|
2372
|
+
});
|
|
2373
|
+
return;
|
|
2374
|
+
case "questions":
|
|
2375
|
+
appendQuestion(event.questions);
|
|
2376
|
+
return;
|
|
2377
|
+
case "result":
|
|
2378
|
+
resultSeen = true;
|
|
2379
|
+
store.appendItem(sessionId, {
|
|
2380
|
+
kind: "result",
|
|
2381
|
+
id: newId("r"),
|
|
2382
|
+
ts: now(),
|
|
2383
|
+
durationMs: event.durationMs ?? Date.now() - startedAt,
|
|
2384
|
+
costUsd: event.costUsd,
|
|
2385
|
+
aborted: false
|
|
2386
|
+
});
|
|
2387
|
+
return;
|
|
2388
|
+
}
|
|
2389
|
+
};
|
|
2390
|
+
const askUser = (questions) => new Promise((resolve) => {
|
|
2391
|
+
if (controller.signal.aborted) return resolve(null);
|
|
2392
|
+
const item = appendQuestion(questions);
|
|
2393
|
+
pending.set(item.id, {
|
|
2394
|
+
kind: "question",
|
|
2395
|
+
resolve: (answers) => {
|
|
2396
|
+
pending.delete(item.id);
|
|
2397
|
+
store.updateItem(sessionId, item.id, "question", {
|
|
2398
|
+
answers,
|
|
2399
|
+
status: answers ? "answered" : "cancelled"
|
|
2400
|
+
});
|
|
2401
|
+
resolve(answers);
|
|
2402
|
+
}
|
|
2403
|
+
});
|
|
2404
|
+
});
|
|
2405
|
+
const requestPermission = (request) => new Promise((resolve) => {
|
|
2406
|
+
if (controller.signal.aborted) return resolve(false);
|
|
2407
|
+
const item = store.appendItem(sessionId, {
|
|
2408
|
+
kind: "permission",
|
|
2409
|
+
id: newId("p"),
|
|
2410
|
+
ts: now(),
|
|
2411
|
+
tool: request.tool,
|
|
2412
|
+
title: request.title,
|
|
2413
|
+
detail: request.detail,
|
|
2414
|
+
status: options.autoApprove ? "allowed" : "pending"
|
|
2415
|
+
});
|
|
2416
|
+
if (options.autoApprove) return resolve(true);
|
|
2417
|
+
pending.set(item.id, {
|
|
2418
|
+
kind: "permission",
|
|
2419
|
+
resolve: (allow) => {
|
|
2420
|
+
pending.delete(item.id);
|
|
2421
|
+
store.updateItem(sessionId, item.id, "permission", { status: allow ? "allowed" : "denied" });
|
|
2422
|
+
resolve(allow);
|
|
2423
|
+
}
|
|
2424
|
+
});
|
|
2425
|
+
});
|
|
2426
|
+
const finish = () => {
|
|
2427
|
+
running.delete(sessionId);
|
|
2428
|
+
if (!store.get(sessionId)) return;
|
|
2429
|
+
for (const id of openText) store.updateItem(sessionId, id, "assistant", { streaming: false });
|
|
2430
|
+
for (const id of openTools) store.updateItem(sessionId, id, "tool", { status: "error" });
|
|
2431
|
+
if (!resultSeen) store.appendItem(sessionId, {
|
|
2432
|
+
kind: "result",
|
|
2433
|
+
id: newId("r"),
|
|
2434
|
+
ts: now(),
|
|
2435
|
+
durationMs: Date.now() - startedAt,
|
|
2436
|
+
costUsd: null,
|
|
2437
|
+
aborted: controller.signal.aborted
|
|
2438
|
+
});
|
|
2439
|
+
store.patch(sessionId, { status: "idle" });
|
|
2440
|
+
if (onTurnEnd) Promise.resolve().then(() => onTurnEnd({
|
|
2441
|
+
sessionId,
|
|
2442
|
+
userItemId
|
|
2443
|
+
})).catch((err) => {
|
|
2444
|
+
console.error("[open-slide] agent turn-end handler failed:", err);
|
|
2445
|
+
});
|
|
2446
|
+
};
|
|
2447
|
+
const prompt = buildTurnPrompt(promptText, context);
|
|
2448
|
+
provider.run({
|
|
2449
|
+
cwd: userCwd,
|
|
2450
|
+
writableRoots,
|
|
2451
|
+
prompt,
|
|
2452
|
+
systemPromptAppend: systemPromptAppend(provider.askInstruction),
|
|
2453
|
+
resume: session.providerSessionId,
|
|
2454
|
+
resumeAt,
|
|
2455
|
+
model: options.model ?? null,
|
|
2456
|
+
effort: options.effort ?? null,
|
|
2457
|
+
signal: controller.signal,
|
|
2458
|
+
emit,
|
|
2459
|
+
askUser,
|
|
2460
|
+
requestPermission
|
|
2461
|
+
}).catch((err) => {
|
|
2462
|
+
if (controller.signal.aborted) return;
|
|
2463
|
+
emit({
|
|
2464
|
+
type: "error",
|
|
2465
|
+
text: err instanceof Error ? err.message : String(err)
|
|
2466
|
+
});
|
|
2467
|
+
}).finally(finish);
|
|
2468
|
+
}
|
|
2469
|
+
function stop(sessionId) {
|
|
2470
|
+
const controller = running.get(sessionId);
|
|
2471
|
+
if (!controller) return false;
|
|
2472
|
+
const session = store.get(sessionId);
|
|
2473
|
+
if (session) for (const item of session.items) {
|
|
2474
|
+
const prompt = pending.get(item.id);
|
|
2475
|
+
if (prompt) cancelPrompt(prompt);
|
|
2476
|
+
}
|
|
2477
|
+
controller.abort();
|
|
2478
|
+
return true;
|
|
2479
|
+
}
|
|
2480
|
+
function respond(sessionId, itemId, payload, next = {}) {
|
|
2481
|
+
if (!store.get(sessionId)?.items.some((i) => i.id === itemId)) return false;
|
|
2482
|
+
const prompt = pending.get(itemId);
|
|
2483
|
+
if (!prompt) return answerInNextTurn(sessionId, itemId, payload, next);
|
|
2484
|
+
if ("cancel" in payload) {
|
|
2485
|
+
cancelPrompt(prompt);
|
|
2486
|
+
return true;
|
|
2487
|
+
}
|
|
2488
|
+
if (prompt.kind === "question" && "answers" in payload) {
|
|
2489
|
+
prompt.resolve(payload.answers);
|
|
2490
|
+
return true;
|
|
2491
|
+
}
|
|
2492
|
+
if (prompt.kind === "permission" && "allow" in payload) {
|
|
2493
|
+
prompt.resolve(payload.allow);
|
|
2494
|
+
return true;
|
|
2495
|
+
}
|
|
2496
|
+
return false;
|
|
2497
|
+
}
|
|
2498
|
+
function answerInNextTurn(sessionId, itemId, payload, next) {
|
|
2499
|
+
const item = store.get(sessionId)?.items.find((i) => i.id === itemId);
|
|
2500
|
+
if (item?.kind !== "question" || item.status !== "pending" || running.has(sessionId)) return false;
|
|
2501
|
+
if (!("answers" in payload) && !("cancel" in payload)) return false;
|
|
2502
|
+
const answers = "answers" in payload ? payload.answers : null;
|
|
2503
|
+
store.updateItem(sessionId, itemId, "question", {
|
|
2504
|
+
answers,
|
|
2505
|
+
status: answers ? "answered" : "cancelled"
|
|
2506
|
+
});
|
|
2507
|
+
const previous = {
|
|
2508
|
+
...lastOptions.get(sessionId),
|
|
2509
|
+
...next
|
|
2510
|
+
};
|
|
2511
|
+
const context = previous.context ? {
|
|
2512
|
+
...previous.context,
|
|
2513
|
+
newDeck: void 0
|
|
2514
|
+
} : void 0;
|
|
2515
|
+
send(sessionId, {
|
|
2516
|
+
...previous,
|
|
2517
|
+
context,
|
|
2518
|
+
text: answersPrompt(item.questions, answers),
|
|
2519
|
+
answering: itemId
|
|
2520
|
+
}).catch((err) => {
|
|
2521
|
+
console.error("[open-slide] agent turn failed:", err);
|
|
2522
|
+
});
|
|
2523
|
+
return true;
|
|
2524
|
+
}
|
|
2525
|
+
function stopAll() {
|
|
2526
|
+
for (const id of Array.from(running.keys())) stop(id);
|
|
2527
|
+
}
|
|
2528
|
+
return {
|
|
2529
|
+
send,
|
|
2530
|
+
stop,
|
|
2531
|
+
respond,
|
|
2532
|
+
isRunning,
|
|
2533
|
+
stopAll
|
|
2534
|
+
};
|
|
2535
|
+
}
|
|
2536
|
+
//#endregion
|
|
2537
|
+
//#region src/agent/status.ts
|
|
2538
|
+
const INSTALL_TIMEOUT_MS = 6e5;
|
|
2539
|
+
async function providerStatus(userCwd, provider) {
|
|
2540
|
+
const sdk = resolveWorkspacePackage(userCwd, provider.sdkPackage);
|
|
2541
|
+
const cliPath = findOnPath(provider.cliCommand);
|
|
2542
|
+
const [cliVersion, models] = await Promise.all([cliPath ? commandVersion(cliPath) : null, provider.models()]);
|
|
2543
|
+
return {
|
|
2544
|
+
id: provider.id,
|
|
2545
|
+
name: provider.name,
|
|
2546
|
+
sdkPackage: provider.sdkPackage,
|
|
2547
|
+
sdkVersion: sdk?.version ?? null,
|
|
2548
|
+
cliCommand: provider.cliCommand,
|
|
2549
|
+
cliFound: cliPath !== null,
|
|
2550
|
+
cliVersion,
|
|
2551
|
+
ready: sdk !== null,
|
|
2552
|
+
models
|
|
2553
|
+
};
|
|
2554
|
+
}
|
|
2555
|
+
async function agentStatus(userCwd, providers, packageManager) {
|
|
2556
|
+
return {
|
|
2557
|
+
enabled: true,
|
|
2558
|
+
packageManager,
|
|
2559
|
+
providers: await Promise.all(Object.values(providers).map((provider) => providerStatus(userCwd, provider)))
|
|
2560
|
+
};
|
|
2561
|
+
}
|
|
2562
|
+
function installCommandFor(packageManager, pkg) {
|
|
2563
|
+
switch (packageManager) {
|
|
2564
|
+
case "pnpm": return {
|
|
2565
|
+
cmd: "pnpm",
|
|
2566
|
+
args: [
|
|
2567
|
+
"add",
|
|
2568
|
+
"-D",
|
|
2569
|
+
pkg
|
|
2570
|
+
]
|
|
2571
|
+
};
|
|
2572
|
+
case "yarn": return {
|
|
2573
|
+
cmd: "yarn",
|
|
2574
|
+
args: [
|
|
2575
|
+
"add",
|
|
2576
|
+
"-D",
|
|
2577
|
+
pkg
|
|
2578
|
+
]
|
|
2579
|
+
};
|
|
2580
|
+
case "bun": return {
|
|
2581
|
+
cmd: "bun",
|
|
2582
|
+
args: [
|
|
2583
|
+
"add",
|
|
2584
|
+
"-d",
|
|
2585
|
+
pkg
|
|
2586
|
+
]
|
|
2587
|
+
};
|
|
2588
|
+
case "npm": return {
|
|
2589
|
+
cmd: "npm",
|
|
2590
|
+
args: [
|
|
2591
|
+
"install",
|
|
2592
|
+
"-D",
|
|
2593
|
+
pkg
|
|
2594
|
+
]
|
|
2595
|
+
};
|
|
2596
|
+
}
|
|
2597
|
+
}
|
|
2598
|
+
function installSdk(packageManager, pkg, cwd) {
|
|
2599
|
+
return runCommand(installCommandFor(packageManager, pkg), cwd, INSTALL_TIMEOUT_MS);
|
|
2600
|
+
}
|
|
2601
|
+
//#endregion
|
|
2602
|
+
//#region src/vite/routes/agent.ts
|
|
2603
|
+
function parseContext(raw) {
|
|
2604
|
+
if (!raw || typeof raw !== "object") return void 0;
|
|
2605
|
+
const r = raw;
|
|
2606
|
+
const ctx = {};
|
|
2607
|
+
if (typeof r.slideId === "string" && SLIDE_ID_RE.test(r.slideId)) ctx.slideId = r.slideId;
|
|
2608
|
+
if (typeof r.slideTitle === "string") ctx.slideTitle = r.slideTitle.slice(0, 120);
|
|
2609
|
+
if (typeof r.pageNumber === "number" && Number.isFinite(r.pageNumber)) ctx.pageNumber = Math.max(1, Math.floor(r.pageNumber));
|
|
2610
|
+
if (typeof r.totalPages === "number" && Number.isFinite(r.totalPages)) ctx.totalPages = Math.max(1, Math.floor(r.totalPages));
|
|
2611
|
+
if (typeof r.pendingComments === "number" && Number.isFinite(r.pendingComments)) ctx.pendingComments = Math.max(0, Math.floor(r.pendingComments));
|
|
2612
|
+
if (r.newDeck === true) ctx.newDeck = true;
|
|
2613
|
+
const sel = r.selection;
|
|
2614
|
+
if (sel && typeof sel === "object") {
|
|
2615
|
+
const s = sel;
|
|
2616
|
+
if (typeof s.line === "number" && typeof s.column === "number") ctx.selection = {
|
|
2617
|
+
line: Math.max(1, Math.floor(s.line)),
|
|
2618
|
+
column: Math.max(0, Math.floor(s.column)),
|
|
2619
|
+
tagName: typeof s.tagName === "string" ? s.tagName.slice(0, 32) : "element",
|
|
2620
|
+
text: typeof s.text === "string" ? s.text.slice(0, 120) : ""
|
|
2621
|
+
};
|
|
2622
|
+
}
|
|
2623
|
+
return ctx;
|
|
2624
|
+
}
|
|
2625
|
+
const MODEL_RE = /^[\w.:[\]-]{1,80}$/;
|
|
2626
|
+
function parseModel(raw) {
|
|
2627
|
+
return typeof raw === "string" && MODEL_RE.test(raw) ? raw : null;
|
|
2628
|
+
}
|
|
2629
|
+
async function renamePlaceholderDeck(server, ctx, store, broadcast, turn) {
|
|
2630
|
+
const session = store.get(turn.sessionId);
|
|
2631
|
+
const slideId = session?.slideId;
|
|
2632
|
+
if (!session || !slideId || !UNTITLED_SLIDE_ID_RE.test(slideId)) return;
|
|
2633
|
+
const start = session.items.findIndex((i) => i.id === turn.userItemId);
|
|
2634
|
+
let marked = null;
|
|
2635
|
+
for (const item of session.items.slice(start + 1)) {
|
|
2636
|
+
if (item.kind !== "assistant") continue;
|
|
2637
|
+
const slug = extractDeckSlug(item.text);
|
|
2638
|
+
if (slug === null) continue;
|
|
2639
|
+
marked = slug;
|
|
2640
|
+
store.updateItem(session.id, item.id, "assistant", { text: stripDeckSlug(item.text) });
|
|
2641
|
+
}
|
|
2642
|
+
if (store.list().some((s) => s.slideId === slideId && s.status === "running")) return;
|
|
2643
|
+
const entry = resolveSlideEntry(ctx.slidesRoot, slideId);
|
|
2644
|
+
if (!entry) return;
|
|
2645
|
+
let source;
|
|
2646
|
+
try {
|
|
2647
|
+
source = await fs.readFile(entry, "utf8");
|
|
2648
|
+
} catch {
|
|
2649
|
+
return;
|
|
2650
|
+
}
|
|
2651
|
+
const meta = readMetaTitleInSource(source);
|
|
2652
|
+
if (meta.kind !== "found" || meta.title === "Untitled") return;
|
|
2653
|
+
const desired = slugifyTitle(marked ?? "") || slugifyTitle(meta.title);
|
|
2654
|
+
if (!desired || UNTITLED_SLIDE_ID_RE.test(desired)) return;
|
|
2655
|
+
if (store.list().some((s) => s.slideId === slideId && s.status === "running")) return;
|
|
2656
|
+
recordWrite(entry);
|
|
2657
|
+
const renamed = await renameSlideDir(ctx.slidesRoot, slideId, desired);
|
|
2658
|
+
if (!renamed.ok) return;
|
|
2659
|
+
recordWrite(path.join(renamed.to, "index.tsx"));
|
|
2660
|
+
const manifest = await readManifest(ctx.manifestPath);
|
|
2661
|
+
const folderId = manifest.assignments[slideId];
|
|
2662
|
+
if (folderId) {
|
|
2663
|
+
delete manifest.assignments[slideId];
|
|
2664
|
+
manifest.assignments[renamed.slideId] = folderId;
|
|
2665
|
+
await writeManifest(ctx.manifestPath, manifest);
|
|
2666
|
+
}
|
|
2667
|
+
for (const s of store.list()) if (s.slideId === slideId) store.patch(s.id, { slideId: renamed.slideId });
|
|
2668
|
+
invalidateSlidesModule(server);
|
|
2669
|
+
broadcast({
|
|
2670
|
+
type: "slide-renamed",
|
|
2671
|
+
from: slideId,
|
|
2672
|
+
to: renamed.slideId
|
|
2673
|
+
});
|
|
2674
|
+
}
|
|
2675
|
+
function parseRespond(raw) {
|
|
2676
|
+
if (!raw || typeof raw !== "object") return null;
|
|
2677
|
+
const r = raw;
|
|
2678
|
+
if (r.cancel === true) return { cancel: true };
|
|
2679
|
+
if (typeof r.allow === "boolean") return { allow: r.allow };
|
|
2680
|
+
if (r.answers && typeof r.answers === "object") {
|
|
2681
|
+
const answers = {};
|
|
2682
|
+
for (const [k, v] of Object.entries(r.answers)) if (typeof v === "string") answers[k] = v;
|
|
2683
|
+
return { answers };
|
|
2684
|
+
}
|
|
2685
|
+
return null;
|
|
2686
|
+
}
|
|
2687
|
+
function parseTurnSettings(raw) {
|
|
2688
|
+
const settings = {};
|
|
2689
|
+
const context = parseContext(raw.context);
|
|
2690
|
+
if (context) settings.context = context;
|
|
2691
|
+
if (typeof raw.autoApprove === "boolean") settings.autoApprove = raw.autoApprove;
|
|
2692
|
+
if ("model" in raw) settings.model = parseModel(raw.model);
|
|
2693
|
+
if ("effort" in raw) settings.effort = isAgentEffort(raw.effort) ? raw.effort : null;
|
|
2694
|
+
return settings;
|
|
2695
|
+
}
|
|
2696
|
+
const AGENT_BODY_LIMIT = 1048576;
|
|
2697
|
+
function registerAgentRoutes(server, ctx) {
|
|
2698
|
+
const providers = createProviders();
|
|
2699
|
+
const store = createSessionStore({ file: path.join(ctx.userCwd, "node_modules", ".open-slide", "agent-sessions.json") });
|
|
2700
|
+
const streams = /* @__PURE__ */ new Set();
|
|
2701
|
+
const broadcast = (event) => {
|
|
2702
|
+
const frame = `data: ${JSON.stringify(event)}\n\n`;
|
|
2703
|
+
for (const stream of streams) stream.write(frame);
|
|
2704
|
+
};
|
|
2705
|
+
const heartbeat = setInterval(() => {
|
|
2706
|
+
for (const stream of streams) stream.write(": ping\n\n");
|
|
2707
|
+
}, 25e3);
|
|
2708
|
+
heartbeat.unref();
|
|
2709
|
+
const runner = createAgentRunner({
|
|
2710
|
+
userCwd: ctx.userCwd,
|
|
2711
|
+
writableRoots: [ctx.slidesRoot, ctx.globalAssetsRoot],
|
|
2712
|
+
store,
|
|
2713
|
+
providers,
|
|
2714
|
+
onTurnEnd: (turn) => renamePlaceholderDeck(server, ctx, store, broadcast, turn)
|
|
2715
|
+
});
|
|
2716
|
+
store.subscribe(broadcast);
|
|
2717
|
+
server.httpServer?.on("close", () => {
|
|
2718
|
+
clearInterval(heartbeat);
|
|
2719
|
+
for (const stream of streams) stream.end();
|
|
2720
|
+
runner.stopAll();
|
|
2721
|
+
store.flush();
|
|
2722
|
+
});
|
|
2723
|
+
const installsInFlight = /* @__PURE__ */ new Map();
|
|
2724
|
+
server.middlewares.use("/__agent", async (req, res, next) => {
|
|
2725
|
+
const url = new URL(req.url ?? "/", "http://local");
|
|
2726
|
+
const method = req.method ?? "GET";
|
|
2727
|
+
const segments = url.pathname.split("/").filter(Boolean);
|
|
2728
|
+
const enabled = ctx.agentEnabled && isLoopbackRequest(req);
|
|
2729
|
+
try {
|
|
2730
|
+
if (method === "GET" && url.pathname === "/status") {
|
|
2731
|
+
res.setHeader("cache-control", "no-store");
|
|
2732
|
+
if (!enabled) return json(res, 200, {
|
|
2733
|
+
enabled: false,
|
|
2734
|
+
packageManager: "",
|
|
2735
|
+
providers: []
|
|
2736
|
+
});
|
|
2737
|
+
const pm = await detectPackageManager(ctx.userCwd);
|
|
2738
|
+
return json(res, 200, await agentStatus(ctx.userCwd, providers, pm));
|
|
2739
|
+
}
|
|
2740
|
+
if (!enabled) return json(res, 404, { error: "agent panel disabled" });
|
|
2741
|
+
if (method === "GET" && url.pathname === "/events") {
|
|
2742
|
+
res.writeHead(200, {
|
|
2743
|
+
"content-type": "text/event-stream",
|
|
2744
|
+
"cache-control": "no-store",
|
|
2745
|
+
connection: "keep-alive"
|
|
2746
|
+
});
|
|
2747
|
+
res.write(": connected\n\n");
|
|
2748
|
+
streams.add(res);
|
|
2749
|
+
const drop = () => streams.delete(res);
|
|
2750
|
+
res.on("close", drop);
|
|
2751
|
+
res.on("error", drop);
|
|
2752
|
+
return;
|
|
2753
|
+
}
|
|
2754
|
+
if (method === "POST" && url.pathname === "/install") {
|
|
2755
|
+
const guard = validateMutationRequest(req, { requireJsonBody: true });
|
|
2756
|
+
if (!guard.ok) return json(res, guard.status, { error: guard.error });
|
|
2757
|
+
const body = await readBody(req, AGENT_BODY_LIMIT);
|
|
2758
|
+
if (!isAgentProviderId(body.provider)) return json(res, 400, { error: "invalid provider" });
|
|
2759
|
+
const provider = providers[body.provider];
|
|
2760
|
+
const pm = await detectPackageManager(ctx.userCwd);
|
|
2761
|
+
const pkg = provider.sdkPackage;
|
|
2762
|
+
let install = installsInFlight.get(pkg);
|
|
2763
|
+
if (!install) {
|
|
2764
|
+
install = installSdk(pm, pkg, ctx.userCwd).finally(() => installsInFlight.delete(pkg));
|
|
2765
|
+
installsInFlight.set(pkg, install);
|
|
2766
|
+
}
|
|
2767
|
+
await install;
|
|
2768
|
+
return json(res, 200, { ok: true });
|
|
2769
|
+
}
|
|
2770
|
+
if (method === "GET" && url.pathname === "/sessions") {
|
|
2771
|
+
res.setHeader("cache-control", "no-store");
|
|
2772
|
+
return json(res, 200, { sessions: store.list() });
|
|
2773
|
+
}
|
|
2774
|
+
if (method === "POST" && url.pathname === "/sessions") {
|
|
2775
|
+
const guard = validateMutationRequest(req, { requireJsonBody: true });
|
|
2776
|
+
if (!guard.ok) return json(res, guard.status, { error: guard.error });
|
|
2777
|
+
const body = await readBody(req, AGENT_BODY_LIMIT);
|
|
2778
|
+
if (!isAgentProviderId(body.provider)) return json(res, 400, { error: "invalid provider" });
|
|
2779
|
+
const slideId = typeof body.slideId === "string" && SLIDE_ID_RE.test(body.slideId) ? body.slideId : null;
|
|
2780
|
+
return json(res, 200, store.create(body.provider, slideId));
|
|
2781
|
+
}
|
|
2782
|
+
if (segments[0] === "sessions" && segments[1]) {
|
|
2783
|
+
const id = segments[1];
|
|
2784
|
+
const action = segments[2];
|
|
2785
|
+
const session = store.get(id);
|
|
2786
|
+
if (!session) return json(res, 404, { error: "session not found" });
|
|
2787
|
+
if (method === "GET" && !action) {
|
|
2788
|
+
res.setHeader("cache-control", "no-store");
|
|
2789
|
+
return json(res, 200, session);
|
|
2790
|
+
}
|
|
2791
|
+
if (method === "DELETE" && !action) {
|
|
2792
|
+
const guard = validateMutationRequest(req);
|
|
2793
|
+
if (!guard.ok) return json(res, guard.status, { error: guard.error });
|
|
2794
|
+
runner.stop(id);
|
|
2795
|
+
store.remove(id);
|
|
2796
|
+
return json(res, 200, { ok: true });
|
|
2797
|
+
}
|
|
2798
|
+
if (method === "POST" && action === "messages") {
|
|
2799
|
+
const guard = validateMutationRequest(req, { requireJsonBody: true });
|
|
2800
|
+
if (!guard.ok) return json(res, guard.status, { error: guard.error });
|
|
2801
|
+
const body = await readBody(req, AGENT_BODY_LIMIT);
|
|
2802
|
+
if (typeof body.text !== "string" || !body.text.trim()) return json(res, 400, { error: "missing text" });
|
|
2803
|
+
if (runner.isRunning(id)) return json(res, 409, { error: "session is already running" });
|
|
2804
|
+
if (body.edit !== void 0 && !session.items.some((i) => i.id === body.edit && i.kind === "user")) return json(res, 400, { error: "unknown message" });
|
|
2805
|
+
await runner.send(id, {
|
|
2806
|
+
text: body.text,
|
|
2807
|
+
context: parseContext(body.context),
|
|
2808
|
+
autoApprove: body.autoApprove === true,
|
|
2809
|
+
model: parseModel(body.model),
|
|
2810
|
+
effort: isAgentEffort(body.effort) ? body.effort : null,
|
|
2811
|
+
edit: typeof body.edit === "string" ? body.edit : void 0
|
|
2812
|
+
});
|
|
2813
|
+
return json(res, 202, { ok: true });
|
|
2814
|
+
}
|
|
2815
|
+
if (method === "POST" && action === "stop") {
|
|
2816
|
+
const guard = validateMutationRequest(req);
|
|
2817
|
+
if (!guard.ok) return json(res, guard.status, { error: guard.error });
|
|
2818
|
+
return json(res, 200, { ok: runner.stop(id) });
|
|
2819
|
+
}
|
|
2820
|
+
if (method === "POST" && action === "respond") {
|
|
2821
|
+
const guard = validateMutationRequest(req, { requireJsonBody: true });
|
|
2822
|
+
if (!guard.ok) return json(res, guard.status, { error: guard.error });
|
|
2823
|
+
const body = await readBody(req, AGENT_BODY_LIMIT);
|
|
2824
|
+
const payload = parseRespond(body);
|
|
2825
|
+
if (typeof body.itemId !== "string" || !payload) return json(res, 400, { error: "invalid response" });
|
|
2826
|
+
const ok = runner.respond(id, body.itemId, payload, parseTurnSettings(body));
|
|
2827
|
+
return json(res, ok ? 200 : 409, ok ? { ok } : { error: "nothing pending" });
|
|
2828
|
+
}
|
|
2829
|
+
}
|
|
2830
|
+
next();
|
|
2831
|
+
} catch (err) {
|
|
2832
|
+
if (err instanceof BodyTooLargeError) return json(res, 413, { error: err.message });
|
|
2833
|
+
json(res, 500, { error: String(err.message ?? err) });
|
|
2834
|
+
}
|
|
2835
|
+
});
|
|
2836
|
+
}
|
|
2837
|
+
//#endregion
|
|
16
2838
|
//#region src/editing/babel-walk.ts
|
|
17
2839
|
const SKIP_KEYS = /* @__PURE__ */ new Set([
|
|
18
2840
|
"loc",
|
|
@@ -1424,164 +4246,64 @@ function registerAssetRoutes(server, ctx) {
|
|
|
1424
4246
|
oversized = true;
|
|
1425
4247
|
req.destroy();
|
|
1426
4248
|
return;
|
|
1427
|
-
}
|
|
1428
|
-
chunks.push(c);
|
|
1429
|
-
});
|
|
1430
|
-
req.on("end", () => resolve());
|
|
1431
|
-
req.on("error", reject);
|
|
1432
|
-
});
|
|
1433
|
-
if (oversized) return json(res, 413, { error: "file too large" });
|
|
1434
|
-
await fs.writeFile(file, Buffer.concat(chunks));
|
|
1435
|
-
const stat = await fs.stat(file);
|
|
1436
|
-
return json(res, 200, {
|
|
1437
|
-
ok: true,
|
|
1438
|
-
name: filename,
|
|
1439
|
-
size: stat.size,
|
|
1440
|
-
createdAt: assetCreatedAt(stat.birthtimeMs, stat.mtimeMs),
|
|
1441
|
-
mtime: stat.mtimeMs,
|
|
1442
|
-
mime: mimeForFilename(filename),
|
|
1443
|
-
url: `/__assets/${slideId}/${encodeURIComponent(filename)}`
|
|
1444
|
-
});
|
|
1445
|
-
}
|
|
1446
|
-
if (method === "PATCH") {
|
|
1447
|
-
const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
|
|
1448
|
-
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
1449
|
-
const target = validateAssetName((await readBody(req)).name);
|
|
1450
|
-
if (!target) return json(res, 400, { error: "invalid name" });
|
|
1451
|
-
if (target === filename) return json(res, 200, {
|
|
1452
|
-
ok: true,
|
|
1453
|
-
name: filename
|
|
1454
|
-
});
|
|
1455
|
-
const dest = resolveScopedAssetFile(ctx.slidesRoot, ctx.globalAssetsRoot, slideId, target);
|
|
1456
|
-
if (!dest) return json(res, 400, { error: "invalid name" });
|
|
1457
|
-
try {
|
|
1458
|
-
await fs.access(dest);
|
|
1459
|
-
return json(res, 409, { error: "target exists" });
|
|
1460
|
-
} catch {}
|
|
1461
|
-
try {
|
|
1462
|
-
await fs.rename(file, dest);
|
|
1463
|
-
} catch (err) {
|
|
1464
|
-
if (err.code === "ENOENT") return json(res, 404, { error: "asset not found" });
|
|
1465
|
-
throw err;
|
|
1466
|
-
}
|
|
1467
|
-
return json(res, 200, {
|
|
1468
|
-
ok: true,
|
|
1469
|
-
name: target
|
|
1470
|
-
});
|
|
1471
|
-
}
|
|
1472
|
-
if (method === "DELETE") {
|
|
1473
|
-
const requestCheck = validateMutationRequest(req);
|
|
1474
|
-
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
1475
|
-
try {
|
|
1476
|
-
await fs.unlink(file);
|
|
1477
|
-
} catch (err) {
|
|
1478
|
-
if (err.code === "ENOENT") return json(res, 404, { error: "asset not found" });
|
|
1479
|
-
throw err;
|
|
1480
|
-
}
|
|
1481
|
-
return json(res, 200, { ok: true });
|
|
1482
|
-
}
|
|
1483
|
-
}
|
|
1484
|
-
return next();
|
|
1485
|
-
} catch (err) {
|
|
1486
|
-
json(res, 500, { error: String(err.message ?? err) });
|
|
1487
|
-
}
|
|
1488
|
-
});
|
|
1489
|
-
}
|
|
1490
|
-
//#endregion
|
|
1491
|
-
//#region src/files/board-structure.ts
|
|
1492
|
-
function sanitizeStructure(parsed) {
|
|
1493
|
-
if (!parsed || typeof parsed !== "object") return null;
|
|
1494
|
-
const columns = parsed.columns;
|
|
1495
|
-
if (!Array.isArray(columns)) return null;
|
|
1496
|
-
const cleaned = columns.flatMap((column) => {
|
|
1497
|
-
if (!column || typeof column !== "object") return [];
|
|
1498
|
-
const { title, size } = column;
|
|
1499
|
-
if (typeof size !== "number" || !Number.isInteger(size) || size < 0) return [];
|
|
1500
|
-
return [{
|
|
1501
|
-
title: typeof title === "string" ? title : "",
|
|
1502
|
-
size
|
|
1503
|
-
}];
|
|
1504
|
-
});
|
|
1505
|
-
return cleaned.length > 0 ? { columns: cleaned } : null;
|
|
1506
|
-
}
|
|
1507
|
-
/**
|
|
1508
|
-
* Keeps a stored structure usable after the deck changed behind the board's
|
|
1509
|
-
* back: pages added outside the board join the last column, and pages deleted
|
|
1510
|
-
* outside it come off the end.
|
|
1511
|
-
*/
|
|
1512
|
-
function reconcileColumns(columns, pageCount) {
|
|
1513
|
-
if (pageCount <= 0) return [];
|
|
1514
|
-
const kept = columns.map((column) => ({ ...column }));
|
|
1515
|
-
if (kept.length === 0) return [{
|
|
1516
|
-
title: "",
|
|
1517
|
-
size: pageCount
|
|
1518
|
-
}];
|
|
1519
|
-
let total = kept.reduce((sum, column) => sum + column.size, 0);
|
|
1520
|
-
if (total === pageCount) return kept;
|
|
1521
|
-
if (total < pageCount) {
|
|
1522
|
-
kept[kept.length - 1].size += pageCount - total;
|
|
1523
|
-
return kept;
|
|
1524
|
-
}
|
|
1525
|
-
for (let i = kept.length - 1; i >= 0 && total > pageCount; i--) {
|
|
1526
|
-
const drop = Math.min(kept[i].size, total - pageCount);
|
|
1527
|
-
kept[i].size -= drop;
|
|
1528
|
-
total -= drop;
|
|
1529
|
-
}
|
|
1530
|
-
while (kept.length > 1 && kept[kept.length - 1].size === 0) kept.pop();
|
|
1531
|
-
return kept;
|
|
1532
|
-
}
|
|
1533
|
-
//#endregion
|
|
1534
|
-
//#region src/files/board.ts
|
|
1535
|
-
function boardStructurePath(userCwd, slideId) {
|
|
1536
|
-
return path.join(userCwd, ".open-slide", "board", `${slideId}.json`);
|
|
1537
|
-
}
|
|
1538
|
-
async function readBoardStructure(file) {
|
|
1539
|
-
try {
|
|
1540
|
-
return sanitizeStructure(JSON.parse(await fs.readFile(file, "utf8")));
|
|
1541
|
-
} catch {
|
|
1542
|
-
return null;
|
|
1543
|
-
}
|
|
1544
|
-
}
|
|
1545
|
-
async function writeBoardStructure(file, structure) {
|
|
1546
|
-
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
1547
|
-
await fs.writeFile(file, `${JSON.stringify(structure, null, 2)}\n`, "utf8");
|
|
1548
|
-
}
|
|
1549
|
-
//#endregion
|
|
1550
|
-
//#region src/vite/routes/board.ts
|
|
1551
|
-
function registerBoardRoutes(server, ctx) {
|
|
1552
|
-
server.middlewares.use("/__board", async (req, res, next) => {
|
|
1553
|
-
const url = new URL(req.url ?? "/", "http://local");
|
|
1554
|
-
const method = req.method ?? "GET";
|
|
1555
|
-
try {
|
|
1556
|
-
if (method === "GET" && url.pathname === "/") {
|
|
1557
|
-
const slideId = url.searchParams.get("slideId") ?? "";
|
|
1558
|
-
if (!resolveSlideEntryPath(ctx, slideId)) return json(res, 400, { error: "invalid slideId" });
|
|
1559
|
-
const stored = await readBoardStructure(boardStructurePath(ctx.userCwd, slideId));
|
|
1560
|
-
if (!stored) return json(res, 200, { columns: null });
|
|
1561
|
-
const pages = Number(url.searchParams.get("pages") ?? "0");
|
|
1562
|
-
const columns = pages > 0 ? reconcileColumns(stored.columns, pages) : stored.columns;
|
|
1563
|
-
return json(res, 200, { columns });
|
|
1564
|
-
}
|
|
1565
|
-
if (method === "PUT" && url.pathname === "/") {
|
|
1566
|
-
const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
|
|
1567
|
-
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
1568
|
-
const body = await readBody(req);
|
|
1569
|
-
const slideId = body.slideId ?? "";
|
|
1570
|
-
if (!resolveSlideEntryPath(ctx, slideId)) return json(res, 400, { error: "invalid slideId" });
|
|
1571
|
-
if (!Array.isArray(body.columns)) return json(res, 400, { error: "missing columns" });
|
|
1572
|
-
const structure = { columns: body.columns.flatMap((column) => {
|
|
1573
|
-
const { title, size } = column ?? {};
|
|
1574
|
-
if (typeof size !== "number" || !Number.isInteger(size) || size < 0) return [];
|
|
1575
|
-
return [{
|
|
1576
|
-
title: typeof title === "string" ? title : "",
|
|
1577
|
-
size
|
|
1578
|
-
}];
|
|
1579
|
-
}) };
|
|
1580
|
-
if (structure.columns.length === 0) return json(res, 400, { error: "no usable columns" });
|
|
1581
|
-
await writeBoardStructure(boardStructurePath(ctx.userCwd, slideId), structure);
|
|
1582
|
-
return json(res, 200, { ok: true });
|
|
4249
|
+
}
|
|
4250
|
+
chunks.push(c);
|
|
4251
|
+
});
|
|
4252
|
+
req.on("end", () => resolve());
|
|
4253
|
+
req.on("error", reject);
|
|
4254
|
+
});
|
|
4255
|
+
if (oversized) return json(res, 413, { error: "file too large" });
|
|
4256
|
+
await fs.writeFile(file, Buffer.concat(chunks));
|
|
4257
|
+
const stat = await fs.stat(file);
|
|
4258
|
+
return json(res, 200, {
|
|
4259
|
+
ok: true,
|
|
4260
|
+
name: filename,
|
|
4261
|
+
size: stat.size,
|
|
4262
|
+
createdAt: assetCreatedAt(stat.birthtimeMs, stat.mtimeMs),
|
|
4263
|
+
mtime: stat.mtimeMs,
|
|
4264
|
+
mime: mimeForFilename(filename),
|
|
4265
|
+
url: `/__assets/${slideId}/${encodeURIComponent(filename)}`
|
|
4266
|
+
});
|
|
4267
|
+
}
|
|
4268
|
+
if (method === "PATCH") {
|
|
4269
|
+
const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
|
|
4270
|
+
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
4271
|
+
const target = validateAssetName((await readBody(req)).name);
|
|
4272
|
+
if (!target) return json(res, 400, { error: "invalid name" });
|
|
4273
|
+
if (target === filename) return json(res, 200, {
|
|
4274
|
+
ok: true,
|
|
4275
|
+
name: filename
|
|
4276
|
+
});
|
|
4277
|
+
const dest = resolveScopedAssetFile(ctx.slidesRoot, ctx.globalAssetsRoot, slideId, target);
|
|
4278
|
+
if (!dest) return json(res, 400, { error: "invalid name" });
|
|
4279
|
+
try {
|
|
4280
|
+
await fs.access(dest);
|
|
4281
|
+
return json(res, 409, { error: "target exists" });
|
|
4282
|
+
} catch {}
|
|
4283
|
+
try {
|
|
4284
|
+
await fs.rename(file, dest);
|
|
4285
|
+
} catch (err) {
|
|
4286
|
+
if (err.code === "ENOENT") return json(res, 404, { error: "asset not found" });
|
|
4287
|
+
throw err;
|
|
4288
|
+
}
|
|
4289
|
+
return json(res, 200, {
|
|
4290
|
+
ok: true,
|
|
4291
|
+
name: target
|
|
4292
|
+
});
|
|
4293
|
+
}
|
|
4294
|
+
if (method === "DELETE") {
|
|
4295
|
+
const requestCheck = validateMutationRequest(req);
|
|
4296
|
+
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
4297
|
+
try {
|
|
4298
|
+
await fs.unlink(file);
|
|
4299
|
+
} catch (err) {
|
|
4300
|
+
if (err.code === "ENOENT") return json(res, 404, { error: "asset not found" });
|
|
4301
|
+
throw err;
|
|
4302
|
+
}
|
|
4303
|
+
return json(res, 200, { ok: true });
|
|
4304
|
+
}
|
|
1583
4305
|
}
|
|
1584
|
-
next();
|
|
4306
|
+
return next();
|
|
1585
4307
|
} catch (err) {
|
|
1586
4308
|
json(res, 500, { error: String(err.message ?? err) });
|
|
1587
4309
|
}
|
|
@@ -1597,6 +4319,24 @@ function b64urlDecode(s) {
|
|
|
1597
4319
|
const pad = s.length % 4 === 0 ? "" : "=".repeat(4 - s.length % 4);
|
|
1598
4320
|
return Buffer.from(s.replace(/-/g, "+").replace(/_/g, "/") + pad, "base64").toString("utf8");
|
|
1599
4321
|
}
|
|
4322
|
+
function isFiniteNumber(value) {
|
|
4323
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
4324
|
+
}
|
|
4325
|
+
function parseCommentRect(value) {
|
|
4326
|
+
if (!value || typeof value !== "object") return void 0;
|
|
4327
|
+
const { x, y, w, h } = value;
|
|
4328
|
+
if (!isFiniteNumber(x) || !isFiniteNumber(y) || !isFiniteNumber(w) || !isFiniteNumber(h)) return void 0;
|
|
4329
|
+
if (w <= 0 || h <= 0) return void 0;
|
|
4330
|
+
return {
|
|
4331
|
+
x: Math.round(x),
|
|
4332
|
+
y: Math.round(y),
|
|
4333
|
+
w: Math.round(w),
|
|
4334
|
+
h: Math.round(h)
|
|
4335
|
+
};
|
|
4336
|
+
}
|
|
4337
|
+
function parseCommentPage(value) {
|
|
4338
|
+
return isFiniteNumber(value) && value >= 0 ? Math.floor(value) : void 0;
|
|
4339
|
+
}
|
|
1600
4340
|
function parseMarkers(source) {
|
|
1601
4341
|
const comments = [];
|
|
1602
4342
|
const lines = source.split("\n");
|
|
@@ -1611,12 +4351,36 @@ function parseMarkers(source) {
|
|
|
1611
4351
|
line: i + 1,
|
|
1612
4352
|
ts,
|
|
1613
4353
|
note: payload.note,
|
|
1614
|
-
hint: payload.hint
|
|
4354
|
+
hint: payload.hint,
|
|
4355
|
+
rect: parseCommentRect(payload.rect),
|
|
4356
|
+
page: parseCommentPage(payload.page)
|
|
1615
4357
|
});
|
|
1616
4358
|
} catch {}
|
|
1617
4359
|
}
|
|
1618
4360
|
return comments;
|
|
1619
4361
|
}
|
|
4362
|
+
function markerColumn(source, line) {
|
|
4363
|
+
const index = (source.split("\n")[line - 1] ?? "").search(/\{\/\*\s*@slide-comment/);
|
|
4364
|
+
return index === -1 ? 0 : index;
|
|
4365
|
+
}
|
|
4366
|
+
function resolveTargets(source, comments) {
|
|
4367
|
+
const ast = parseSource(source);
|
|
4368
|
+
return comments.map((comment) => {
|
|
4369
|
+
if (!ast) return {
|
|
4370
|
+
...comment,
|
|
4371
|
+
target: null
|
|
4372
|
+
};
|
|
4373
|
+
const column = markerColumn(source, comment.line);
|
|
4374
|
+
const start = findJsxAncestors(ast, comment.line, column).find((node) => t.isJSXElement(node))?.loc?.start;
|
|
4375
|
+
return {
|
|
4376
|
+
...comment,
|
|
4377
|
+
target: start ? {
|
|
4378
|
+
line: start.line,
|
|
4379
|
+
column: start.column
|
|
4380
|
+
} : null
|
|
4381
|
+
};
|
|
4382
|
+
});
|
|
4383
|
+
}
|
|
1620
4384
|
function newCommentId() {
|
|
1621
4385
|
return shortId("c");
|
|
1622
4386
|
}
|
|
@@ -1638,11 +4402,43 @@ function lineIndent(source, lineNumber) {
|
|
|
1638
4402
|
}
|
|
1639
4403
|
function planInsertion(source, target) {
|
|
1640
4404
|
if (t.isJSXElement(target) && target.openingElement.selfClosing) return null;
|
|
4405
|
+
const offset = (t.isJSXFragment(target) ? target.openingFragment : target.openingElement).end ?? 0;
|
|
1641
4406
|
return {
|
|
1642
|
-
offset
|
|
1643
|
-
indent: `${lineIndent(source, target.loc?.start.line ?? 1)}
|
|
4407
|
+
offset,
|
|
4408
|
+
indent: `${lineIndent(source, target.loc?.start.line ?? 1)} `,
|
|
4409
|
+
breakAfter: !/^[ \t]*\r?\n/.test(source.slice(offset))
|
|
1644
4410
|
};
|
|
1645
4411
|
}
|
|
4412
|
+
function buildMarker(plan, id, ts, encodedText) {
|
|
4413
|
+
const marker = `\n${plan.indent}{/* @slide-comment id="${id}" ts="${ts}" text="${encodedText}" */}`;
|
|
4414
|
+
return plan.breakAfter ? `${marker}\n${plan.indent}` : marker;
|
|
4415
|
+
}
|
|
4416
|
+
function updateMarkerNote(source, id, note) {
|
|
4417
|
+
const re = new RegExp(`(\\{\\/\\*\\s*@slide-comment\\s+id="${id}"\\s+ts="[^"]+"\\s+text=")([A-Za-z0-9_\\-]+={0,2})("\\s*\\*\\/\\})`);
|
|
4418
|
+
const m = source.match(re);
|
|
4419
|
+
if (!m) return null;
|
|
4420
|
+
let payload;
|
|
4421
|
+
try {
|
|
4422
|
+
payload = JSON.parse(b64urlDecode(m[2]));
|
|
4423
|
+
} catch {
|
|
4424
|
+
return null;
|
|
4425
|
+
}
|
|
4426
|
+
const encoded = b64urlEncode(JSON.stringify({
|
|
4427
|
+
...payload,
|
|
4428
|
+
note
|
|
4429
|
+
}));
|
|
4430
|
+
return source.replace(re, `$1${encoded}$3`);
|
|
4431
|
+
}
|
|
4432
|
+
function removeMarker(source, id) {
|
|
4433
|
+
const lines = source.split("\n");
|
|
4434
|
+
const idRe = markerDeleteRegex(id);
|
|
4435
|
+
const hit = lines.findIndex((line) => idRe.test(line));
|
|
4436
|
+
if (hit === -1) return null;
|
|
4437
|
+
const stripped = lines[hit].replace(idRe, "");
|
|
4438
|
+
if (stripped.trim() === "") lines.splice(hit, 1);
|
|
4439
|
+
else lines[hit] = stripped;
|
|
4440
|
+
return lines.join("\n");
|
|
4441
|
+
}
|
|
1646
4442
|
function findInsertion(source, line, column) {
|
|
1647
4443
|
const ast = parseSource(source);
|
|
1648
4444
|
if (!ast) return null;
|
|
@@ -1669,7 +4465,7 @@ function registerCommentRoutes(server, ctx) {
|
|
|
1669
4465
|
if (!file) return json(res, 400, { error: "invalid slideId" });
|
|
1670
4466
|
const source = await readSlideSource(file);
|
|
1671
4467
|
if (source === null) return json(res, 404, { error: "slide not found" });
|
|
1672
|
-
return json(res, 200, { comments: parseMarkers(source) });
|
|
4468
|
+
return json(res, 200, { comments: resolveTargets(source, parseMarkers(source)) });
|
|
1673
4469
|
}
|
|
1674
4470
|
if (method === "POST" && url.pathname === "/add") {
|
|
1675
4471
|
const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
|
|
@@ -1686,11 +4482,13 @@ function registerCommentRoutes(server, ctx) {
|
|
|
1686
4482
|
if (!plan) return json(res, 422, { error: `could not find a JSX container around line ${body.line}. Try clicking a different element.` });
|
|
1687
4483
|
const id = newCommentId();
|
|
1688
4484
|
const ts = (/* @__PURE__ */ new Date()).toISOString();
|
|
1689
|
-
const payload =
|
|
4485
|
+
const payload = {
|
|
1690
4486
|
note: body.text,
|
|
1691
|
-
hint: body.hint
|
|
1692
|
-
|
|
1693
|
-
|
|
4487
|
+
hint: body.hint,
|
|
4488
|
+
rect: parseCommentRect(body.rect),
|
|
4489
|
+
page: parseCommentPage(body.page)
|
|
4490
|
+
};
|
|
4491
|
+
const marker = buildMarker(plan, id, ts, b64urlEncode(JSON.stringify(payload)));
|
|
1694
4492
|
const next = source.slice(0, plan.offset) + marker + source.slice(plan.offset);
|
|
1695
4493
|
await fs.writeFile(file, next, "utf8");
|
|
1696
4494
|
const markerLine = offsetToLine(next, plan.offset + 1);
|
|
@@ -1699,6 +4497,22 @@ function registerCommentRoutes(server, ctx) {
|
|
|
1699
4497
|
line: markerLine
|
|
1700
4498
|
});
|
|
1701
4499
|
}
|
|
4500
|
+
if (method === "PUT" && url.pathname.startsWith("/")) {
|
|
4501
|
+
const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
|
|
4502
|
+
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
4503
|
+
const id = url.pathname.slice(1);
|
|
4504
|
+
if (!/^c-[a-f0-9]+$/.test(id)) return json(res, 400, { error: "invalid id" });
|
|
4505
|
+
const body = await readBody(req);
|
|
4506
|
+
const file = resolveSlideEntryPath(ctx, body.slideId ?? "");
|
|
4507
|
+
if (!file) return json(res, 400, { error: "invalid slideId" });
|
|
4508
|
+
if (!body.text || typeof body.text !== "string") return json(res, 400, { error: "missing text" });
|
|
4509
|
+
const source = await readSlideSource(file);
|
|
4510
|
+
if (source === null) return json(res, 404, { error: "slide not found" });
|
|
4511
|
+
const next = updateMarkerNote(source, id, body.text);
|
|
4512
|
+
if (next === null) return json(res, 404, { error: "marker not found" });
|
|
4513
|
+
await fs.writeFile(file, next, "utf8");
|
|
4514
|
+
return json(res, 200, { ok: true });
|
|
4515
|
+
}
|
|
1702
4516
|
if (method === "DELETE" && url.pathname.startsWith("/")) {
|
|
1703
4517
|
const requestCheck = validateMutationRequest(req);
|
|
1704
4518
|
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
@@ -1709,12 +4523,9 @@ function registerCommentRoutes(server, ctx) {
|
|
|
1709
4523
|
if (!file) return json(res, 400, { error: "invalid slideId" });
|
|
1710
4524
|
const source = await readSlideSource(file);
|
|
1711
4525
|
if (source === null) return json(res, 404, { error: "slide not found" });
|
|
1712
|
-
const
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
if (hit === -1) return json(res, 404, { error: "marker not found" });
|
|
1716
|
-
lines.splice(hit, 1);
|
|
1717
|
-
await fs.writeFile(file, lines.join("\n"), "utf8");
|
|
4526
|
+
const next = removeMarker(source, id);
|
|
4527
|
+
if (next === null) return json(res, 404, { error: "marker not found" });
|
|
4528
|
+
await fs.writeFile(file, next, "utf8");
|
|
1718
4529
|
return json(res, 200, { ok: true });
|
|
1719
4530
|
}
|
|
1720
4531
|
next();
|
|
@@ -2133,6 +4944,18 @@ function registerSlideRoutes(server, ctx) {
|
|
|
2133
4944
|
const url = new URL(req.url ?? "/", "http://local");
|
|
2134
4945
|
const method = req.method ?? "GET";
|
|
2135
4946
|
try {
|
|
4947
|
+
if (url.pathname === "/" && method === "POST") {
|
|
4948
|
+
const requestCheck = validateMutationRequest(req);
|
|
4949
|
+
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
4950
|
+
const created = await createBlankSlideDir(ctx.slidesRoot, ctx.frameworkSpecifier);
|
|
4951
|
+
if (!created.ok) return json(res, created.status, { error: created.error });
|
|
4952
|
+
recordWrite(created.file);
|
|
4953
|
+
invalidateSlidesModule(server);
|
|
4954
|
+
return json(res, 200, {
|
|
4955
|
+
ok: true,
|
|
4956
|
+
slideId: created.slideId
|
|
4957
|
+
});
|
|
4958
|
+
}
|
|
2136
4959
|
const reorderMatch = url.pathname.match(/^\/([^/]+)\/reorder$/);
|
|
2137
4960
|
if (reorderMatch && method === "PUT") {
|
|
2138
4961
|
const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
|
|
@@ -2173,9 +4996,7 @@ function registerSlideRoutes(server, ctx) {
|
|
|
2173
4996
|
if (!SLIDE_ID_RE.test(slideId)) return json(res, 400, { error: "invalid slideId" });
|
|
2174
4997
|
if (!Number.isInteger(pageIndex) || pageIndex < 0) return json(res, 400, { error: "invalid page index" });
|
|
2175
4998
|
const isDelete = method === "DELETE" && !op;
|
|
2176
|
-
|
|
2177
|
-
const isInsert = method === "POST" && op === "insert";
|
|
2178
|
-
if (!isDelete && !isDuplicate && !isInsert) return next();
|
|
4999
|
+
if (!isDelete && !(method === "POST" && op === "duplicate")) return next();
|
|
2179
5000
|
const requestCheck = validateMutationRequest(req);
|
|
2180
5001
|
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
2181
5002
|
const entry = resolveSlideEntry(ctx.slidesRoot, slideId);
|
|
@@ -2186,10 +5007,10 @@ function registerSlideRoutes(server, ctx) {
|
|
|
2186
5007
|
} catch {
|
|
2187
5008
|
return json(res, 404, { error: "slide not found" });
|
|
2188
5009
|
}
|
|
2189
|
-
const updated = isDelete ? removePageFromDefaultExportInSource(source, pageIndex) :
|
|
2190
|
-
if (updated === null) return json(res, 422, { error: isDelete ? "could not delete page — index out of range or default export is not an array" :
|
|
2191
|
-
const withNotes = isDelete ? removeNotesElementInSource(updated, pageIndex) :
|
|
2192
|
-
if (withNotes === null) return json(res, 422, { error: isDelete ? "could not delete page — `notes` export has an unexpected shape" :
|
|
5010
|
+
const updated = isDelete ? removePageFromDefaultExportInSource(source, pageIndex) : duplicatePageInDefaultExportInSource(source, pageIndex);
|
|
5011
|
+
if (updated === null) return json(res, 422, { error: isDelete ? "could not delete page — index out of range or default export is not an array" : "could not duplicate page — index out of range or default export is not an array" });
|
|
5012
|
+
const withNotes = isDelete ? removeNotesElementInSource(updated, pageIndex) : duplicateNotesElementInSource(updated, pageIndex);
|
|
5013
|
+
if (withNotes === null) return json(res, 422, { error: isDelete ? "could not delete page — `notes` export has an unexpected shape" : "could not duplicate page — `notes` export has an unexpected shape" });
|
|
2193
5014
|
if (withNotes !== source) await fs.writeFile(entry, withNotes, "utf8");
|
|
2194
5015
|
return json(res, 200, {
|
|
2195
5016
|
ok: true,
|
|
@@ -2350,13 +5171,14 @@ function apiPlugin(opts) {
|
|
|
2350
5171
|
registerEditRoutes(server, ctx);
|
|
2351
5172
|
registerCommentRoutes(server, ctx);
|
|
2352
5173
|
registerSlideRoutes(server, ctx);
|
|
2353
|
-
|
|
5174
|
+
registerLemonRiverRoutes(server, ctx);
|
|
2354
5175
|
registerAssetRoutes(server, ctx);
|
|
2355
5176
|
registerSvglRoutes(server);
|
|
2356
5177
|
registerGfontsRoutes(server);
|
|
2357
5178
|
registerFolderRoutes(server, ctx);
|
|
2358
5179
|
registerUpdateRoutes(server, ctx);
|
|
2359
5180
|
registerRestartRoutes(server);
|
|
5181
|
+
registerAgentRoutes(server, ctx);
|
|
2360
5182
|
}
|
|
2361
5183
|
};
|
|
2362
5184
|
}
|
|
@@ -2868,24 +5690,6 @@ function locTagsPlugin(opts) {
|
|
|
2868
5690
|
};
|
|
2869
5691
|
}
|
|
2870
5692
|
//#endregion
|
|
2871
|
-
//#region src/vite/recent-writes.ts
|
|
2872
|
-
const recentWrites = /* @__PURE__ */ new Map();
|
|
2873
|
-
/** Record that `file` was just written by us. */
|
|
2874
|
-
function recordWrite(file, now = Date.now()) {
|
|
2875
|
-
recentWrites.set(file, now);
|
|
2876
|
-
}
|
|
2877
|
-
/**
|
|
2878
|
-
* True if `file` was recorded within the recent-write window. Expired entries
|
|
2879
|
-
* are pruned so a stale path can no longer suppress a later genuine edit.
|
|
2880
|
-
*/
|
|
2881
|
-
function hasRecentWrite(file, now = Date.now()) {
|
|
2882
|
-
const ts = recentWrites.get(file);
|
|
2883
|
-
if (ts == null) return false;
|
|
2884
|
-
if (now - ts < 1500) return true;
|
|
2885
|
-
recentWrites.delete(file);
|
|
2886
|
-
return false;
|
|
2887
|
-
}
|
|
2888
|
-
//#endregion
|
|
2889
5693
|
//#region src/vite/notes-plugin.ts
|
|
2890
5694
|
function findNotesExport(ast) {
|
|
2891
5695
|
for (const stmt of ast.program.body) {
|
|
@@ -2945,343 +5749,136 @@ function applyNotesEdit(source, index, text) {
|
|
|
2945
5749
|
if (text === "") return {
|
|
2946
5750
|
ok: true,
|
|
2947
5751
|
source
|
|
2948
|
-
};
|
|
2949
|
-
const block = [
|
|
2950
|
-
"",
|
|
2951
|
-
"",
|
|
2952
|
-
"export const notes: (string | undefined)[] = [",
|
|
2953
|
-
...[...Array.from({ length: index }, () => "undefined"), literal].map((s) => ` ${s},`),
|
|
2954
|
-
"];",
|
|
2955
|
-
""
|
|
2956
|
-
].join("\n");
|
|
2957
|
-
const offset = findInsertionOffset(ast, source);
|
|
2958
|
-
return {
|
|
2959
|
-
ok: true,
|
|
2960
|
-
source: source.slice(0, offset) + block + source.slice(offset)
|
|
2961
|
-
};
|
|
2962
|
-
}
|
|
2963
|
-
const elementTexts = [];
|
|
2964
|
-
for (const el of found.elements) {
|
|
2965
|
-
if (el === null) {
|
|
2966
|
-
elementTexts.push("undefined");
|
|
2967
|
-
continue;
|
|
2968
|
-
}
|
|
2969
|
-
if (typeof el.start !== "number" || typeof el.end !== "number") return {
|
|
2970
|
-
ok: false,
|
|
2971
|
-
status: 422,
|
|
2972
|
-
error: "`notes` element missing source range"
|
|
2973
|
-
};
|
|
2974
|
-
elementTexts.push(source.slice(el.start, el.end));
|
|
2975
|
-
}
|
|
2976
|
-
while (elementTexts.length <= index) elementTexts.push("undefined");
|
|
2977
|
-
elementTexts[index] = literal;
|
|
2978
|
-
while (elementTexts.length > 0 && elementTexts[elementTexts.length - 1] === "undefined") elementTexts.pop();
|
|
2979
|
-
const replacement = elementTexts.length === 0 ? "[]" : `[\n${elementTexts.map((s) => ` ${s},`).join("\n")}\n]`;
|
|
2980
|
-
return {
|
|
2981
|
-
ok: true,
|
|
2982
|
-
source: source.slice(0, found.arrayStart) + replacement + source.slice(found.arrayEnd)
|
|
2983
|
-
};
|
|
2984
|
-
}
|
|
2985
|
-
function notesPlugin(opts) {
|
|
2986
|
-
const slidesRoot = path.resolve(opts.userCwd, opts.slidesDir ?? "slides");
|
|
2987
|
-
return {
|
|
2988
|
-
name: "lemonriver:notes",
|
|
2989
|
-
apply: "serve",
|
|
2990
|
-
handleHotUpdate(ctx) {
|
|
2991
|
-
if (hasRecentWrite(ctx.file)) return [];
|
|
2992
|
-
},
|
|
2993
|
-
configureServer(server) {
|
|
2994
|
-
server.middlewares.use("/__notes", async (req, res, next) => {
|
|
2995
|
-
const url = new URL(req.url ?? "/", "http://local");
|
|
2996
|
-
if ((req.method ?? "GET") !== "PUT" || url.pathname !== "/") return next();
|
|
2997
|
-
const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
|
|
2998
|
-
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
2999
|
-
try {
|
|
3000
|
-
const body = await readBody(req);
|
|
3001
|
-
const slideId = body.slideId ?? "";
|
|
3002
|
-
const file = resolveSlideEntry(slidesRoot, slideId);
|
|
3003
|
-
if (!file) return json(res, 400, { error: "invalid slideId" });
|
|
3004
|
-
if (typeof body.index !== "number") return json(res, 400, { error: "missing index" });
|
|
3005
|
-
if (typeof body.text !== "string") return json(res, 400, { error: "missing text" });
|
|
3006
|
-
const source = await readSlideSource(file);
|
|
3007
|
-
if (source === null) return json(res, 404, { error: "slide not found" });
|
|
3008
|
-
const result = applyNotesEdit(source, body.index, body.text);
|
|
3009
|
-
if (!result.ok) return json(res, result.status, { error: result.error });
|
|
3010
|
-
const changed = result.source !== source;
|
|
3011
|
-
if (changed) {
|
|
3012
|
-
recordWrite(file);
|
|
3013
|
-
await fs.writeFile(file, result.source, "utf8");
|
|
3014
|
-
}
|
|
3015
|
-
return json(res, 200, {
|
|
3016
|
-
ok: true,
|
|
3017
|
-
changed
|
|
3018
|
-
});
|
|
3019
|
-
} catch (err) {
|
|
3020
|
-
json(res, 500, { error: String(err.message ?? err) });
|
|
3021
|
-
}
|
|
3022
|
-
});
|
|
3023
|
-
}
|
|
3024
|
-
};
|
|
3025
|
-
}
|
|
3026
|
-
//#endregion
|
|
3027
|
-
//#region src/vite/open-slide-plugin.ts
|
|
3028
|
-
const SLIDES_VMOD = "virtual:open-slide/slides";
|
|
3029
|
-
const CONFIG_VMOD = "virtual:open-slide/config";
|
|
3030
|
-
const FOLDERS_VMOD = "virtual:open-slide/folders";
|
|
3031
|
-
function resolved$1(id) {
|
|
3032
|
-
return `\0${id}`;
|
|
3033
|
-
}
|
|
3034
|
-
async function findSlides(userCwd, slidesDir) {
|
|
3035
|
-
const abs = path.resolve(userCwd, slidesDir);
|
|
3036
|
-
if (!existsSync(abs)) return [];
|
|
3037
|
-
return (await fg("*/index.{tsx,jsx,ts,js}", {
|
|
3038
|
-
cwd: abs,
|
|
3039
|
-
absolute: true,
|
|
3040
|
-
onlyFiles: true
|
|
3041
|
-
})).sort();
|
|
3042
|
-
}
|
|
3043
|
-
function toId(absFile, slidesRoot) {
|
|
3044
|
-
return path.relative(slidesRoot, absFile).split(path.sep)[0];
|
|
3045
|
-
}
|
|
3046
|
-
const META_THEME_RE = /(?:^|[\s,{])theme\s*:\s*['"]([^'"]+)['"]/;
|
|
3047
|
-
const META_CREATED_AT_RE = /(?:^|[\s,{])createdAt\s*:\s*['"]([^'"]+)['"]/;
|
|
3048
|
-
function extractMeta(src) {
|
|
3049
|
-
const empty = {
|
|
3050
|
-
theme: null,
|
|
3051
|
-
createdAt: null
|
|
3052
|
-
};
|
|
3053
|
-
const metaStart = src.search(/export\s+const\s+meta\b/);
|
|
3054
|
-
if (metaStart === -1) return empty;
|
|
3055
|
-
const eqIdx = src.indexOf("=", metaStart);
|
|
3056
|
-
if (eqIdx === -1) return empty;
|
|
3057
|
-
const openBrace = src.indexOf("{", eqIdx);
|
|
3058
|
-
if (openBrace === -1) return empty;
|
|
3059
|
-
let depth = 0;
|
|
3060
|
-
let closeBrace = -1;
|
|
3061
|
-
for (let i = openBrace; i < src.length; i++) {
|
|
3062
|
-
const ch = src[i];
|
|
3063
|
-
if (ch === "{") depth++;
|
|
3064
|
-
else if (ch === "}") {
|
|
3065
|
-
depth--;
|
|
3066
|
-
if (depth === 0) {
|
|
3067
|
-
closeBrace = i;
|
|
3068
|
-
break;
|
|
3069
|
-
}
|
|
3070
|
-
}
|
|
3071
|
-
}
|
|
3072
|
-
if (closeBrace === -1) return empty;
|
|
3073
|
-
const body = src.slice(openBrace + 1, closeBrace);
|
|
3074
|
-
const themeMatch = body.match(META_THEME_RE);
|
|
3075
|
-
const createdAtMatch = body.match(META_CREATED_AT_RE);
|
|
3076
|
-
return {
|
|
3077
|
-
theme: themeMatch ? themeMatch[1] : null,
|
|
3078
|
-
createdAt: createdAtMatch ? createdAtMatch[1] : null
|
|
3079
|
-
};
|
|
3080
|
-
}
|
|
3081
|
-
async function readSlideMeta(abs) {
|
|
3082
|
-
try {
|
|
3083
|
-
return extractMeta(await fs.readFile(abs, "utf8"));
|
|
3084
|
-
} catch {
|
|
5752
|
+
};
|
|
5753
|
+
const block = [
|
|
5754
|
+
"",
|
|
5755
|
+
"",
|
|
5756
|
+
"export const notes: (string | undefined)[] = [",
|
|
5757
|
+
...[...Array.from({ length: index }, () => "undefined"), literal].map((s) => ` ${s},`),
|
|
5758
|
+
"];",
|
|
5759
|
+
""
|
|
5760
|
+
].join("\n");
|
|
5761
|
+
const offset = findInsertionOffset(ast, source);
|
|
3085
5762
|
return {
|
|
3086
|
-
|
|
3087
|
-
|
|
5763
|
+
ok: true,
|
|
5764
|
+
source: source.slice(0, offset) + block + source.slice(offset)
|
|
3088
5765
|
};
|
|
3089
5766
|
}
|
|
3090
|
-
|
|
3091
|
-
|
|
3092
|
-
|
|
3093
|
-
|
|
3094
|
-
|
|
3095
|
-
}
|
|
3096
|
-
|
|
3097
|
-
|
|
3098
|
-
|
|
3099
|
-
|
|
3100
|
-
const importPath = isDev ? `@fs/${normalizePath(abs).replace(/^\/+/, "")}` : abs;
|
|
3101
|
-
const meta = await readSlideMeta(abs);
|
|
3102
|
-
return {
|
|
3103
|
-
id,
|
|
3104
|
-
importPath,
|
|
3105
|
-
theme: meta.theme,
|
|
3106
|
-
createdAt: parseCreatedAtMs(meta.createdAt)
|
|
5767
|
+
const elementTexts = [];
|
|
5768
|
+
for (const el of found.elements) {
|
|
5769
|
+
if (el === null) {
|
|
5770
|
+
elementTexts.push("undefined");
|
|
5771
|
+
continue;
|
|
5772
|
+
}
|
|
5773
|
+
if (typeof el.start !== "number" || typeof el.end !== "number") return {
|
|
5774
|
+
ok: false,
|
|
5775
|
+
status: 422,
|
|
5776
|
+
error: "`notes` element missing source range"
|
|
3107
5777
|
};
|
|
3108
|
-
|
|
3109
|
-
const entries = scanned.filter((e) => SLIDE_ID_RE.test(e.id));
|
|
3110
|
-
const ignored = scanned.filter((e) => !SLIDE_ID_RE.test(e.id)).map((e) => e.id);
|
|
3111
|
-
const ids = JSON.stringify(entries.map((e) => e.id).sort());
|
|
3112
|
-
const themesMap = {};
|
|
3113
|
-
const createdAtMap = {};
|
|
3114
|
-
for (const e of entries) {
|
|
3115
|
-
if (e.theme) themesMap[e.id] = e.theme;
|
|
3116
|
-
if (e.createdAt !== null) createdAtMap[e.id] = e.createdAt;
|
|
5778
|
+
elementTexts.push(source.slice(el.start, el.end));
|
|
3117
5779
|
}
|
|
3118
|
-
|
|
3119
|
-
|
|
3120
|
-
|
|
5780
|
+
while (elementTexts.length <= index) elementTexts.push("undefined");
|
|
5781
|
+
elementTexts[index] = literal;
|
|
5782
|
+
while (elementTexts.length > 0 && elementTexts[elementTexts.length - 1] === "undefined") elementTexts.pop();
|
|
5783
|
+
const replacement = elementTexts.length === 0 ? "[]" : `[\n${elementTexts.map((s) => ` ${s},`).join("\n")}\n]`;
|
|
3121
5784
|
return {
|
|
3122
|
-
|
|
3123
|
-
|
|
3124
|
-
export const slideThemes = ${themesJson};
|
|
3125
|
-
export const slideCreatedAt = ${createdAtJson};
|
|
3126
|
-
${isDev ? `
|
|
3127
|
-
const slideImportTokens = ${importTokens};
|
|
3128
|
-
if (import.meta.hot) {
|
|
3129
|
-
import.meta.hot.on('open-slide:slide-changed', (data) => {
|
|
3130
|
-
const ids = Array.isArray(data?.slideIds) ? data.slideIds : [];
|
|
3131
|
-
const token = Date.now();
|
|
3132
|
-
for (const id of ids) {
|
|
3133
|
-
if (Object.prototype.hasOwnProperty.call(slideImportTokens, id)) slideImportTokens[id] = token;
|
|
3134
|
-
}
|
|
3135
|
-
});
|
|
3136
|
-
}
|
|
3137
|
-
` : ""}
|
|
3138
|
-
|
|
3139
|
-
export async function loadSlide(id) {
|
|
3140
|
-
switch (id) {
|
|
3141
|
-
${entries.map((e) => {
|
|
3142
|
-
const importExpr = isDev ? `import(/* @vite-ignore */ import.meta.env.BASE_URL + ${JSON.stringify(`${e.importPath}?t=`)} + slideImportTokens[${JSON.stringify(e.id)}])` : `import(${JSON.stringify(e.importPath)})`;
|
|
3143
|
-
return ` case ${JSON.stringify(e.id)}: return ${importExpr};`;
|
|
3144
|
-
}).join("\n")}
|
|
3145
|
-
default: throw new Error('Slide not found: ' + id);
|
|
3146
|
-
}
|
|
3147
|
-
}
|
|
3148
|
-
`,
|
|
3149
|
-
ignored
|
|
5785
|
+
ok: true,
|
|
5786
|
+
source: source.slice(0, found.arrayStart) + replacement + source.slice(found.arrayEnd)
|
|
3150
5787
|
};
|
|
3151
5788
|
}
|
|
3152
|
-
function
|
|
3153
|
-
const
|
|
3154
|
-
const slidesDir = config.slidesDir ?? "slides";
|
|
3155
|
-
const slidesRoot = path.resolve(userCwd, slidesDir);
|
|
3156
|
-
const manifestPath = foldersManifestPath(slidesRoot);
|
|
3157
|
-
let isDev = false;
|
|
3158
|
-
const slideIdForEntry = (p) => {
|
|
3159
|
-
const rel = path.relative(slidesRoot, p);
|
|
3160
|
-
if (rel.startsWith("..") || path.isAbsolute(rel)) return null;
|
|
3161
|
-
const parts = rel.split(path.sep);
|
|
3162
|
-
if (parts.length !== 2) return null;
|
|
3163
|
-
if (!/^index\.(tsx|jsx|ts|js)$/.test(parts[1])) return null;
|
|
3164
|
-
return parts[0];
|
|
3165
|
-
};
|
|
3166
|
-
let slideChangeTimer = null;
|
|
3167
|
-
const pendingSlideChanges = /* @__PURE__ */ new Set();
|
|
3168
|
-
const queueSlideChanged = (server, id) => {
|
|
3169
|
-
pendingSlideChanges.add(id);
|
|
3170
|
-
if (slideChangeTimer) clearTimeout(slideChangeTimer);
|
|
3171
|
-
slideChangeTimer = setTimeout(() => {
|
|
3172
|
-
slideChangeTimer = null;
|
|
3173
|
-
const mod = server.moduleGraph.getModuleById(resolved$1(SLIDES_VMOD));
|
|
3174
|
-
if (mod) server.moduleGraph.invalidateModule(mod);
|
|
3175
|
-
const slideIds = Array.from(pendingSlideChanges);
|
|
3176
|
-
pendingSlideChanges.clear();
|
|
3177
|
-
server.ws.send({
|
|
3178
|
-
type: "custom",
|
|
3179
|
-
event: "open-slide:slide-changed",
|
|
3180
|
-
data: { slideIds }
|
|
3181
|
-
});
|
|
3182
|
-
}, 100);
|
|
3183
|
-
};
|
|
5789
|
+
function notesPlugin(opts) {
|
|
5790
|
+
const slidesRoot = path.resolve(opts.userCwd, opts.slidesDir ?? "slides");
|
|
3184
5791
|
return {
|
|
3185
|
-
name: "lemonriver",
|
|
3186
|
-
|
|
3187
|
-
isDev = env.command === "serve";
|
|
3188
|
-
},
|
|
3189
|
-
resolveId(id) {
|
|
3190
|
-
if (id === SLIDES_VMOD) return resolved$1(SLIDES_VMOD);
|
|
3191
|
-
if (id === CONFIG_VMOD) return resolved$1(CONFIG_VMOD);
|
|
3192
|
-
if (id === FOLDERS_VMOD) return resolved$1(FOLDERS_VMOD);
|
|
3193
|
-
return null;
|
|
3194
|
-
},
|
|
3195
|
-
async load(id) {
|
|
3196
|
-
if (id === resolved$1(SLIDES_VMOD)) {
|
|
3197
|
-
const { code, ignored } = await generateSlidesModule(await findSlides(userCwd, slidesDir), slidesRoot, isDev);
|
|
3198
|
-
for (const slideId of ignored) {
|
|
3199
|
-
if (warnedInvalidSlideIds.has(slideId)) continue;
|
|
3200
|
-
warnedInvalidSlideIds.add(slideId);
|
|
3201
|
-
this.warn(`Ignoring slide folder "${slideId}": slide ids must match ${SLIDE_ID_RE} (lowercase/uppercase letters, digits, "-", "_"). Rename the folder under "${slidesDir}/" to a kebab-case id so it appears in the browser and can be moved into folders.`);
|
|
3202
|
-
}
|
|
3203
|
-
return code;
|
|
3204
|
-
}
|
|
3205
|
-
if (id === resolved$1(CONFIG_VMOD)) {
|
|
3206
|
-
const userBuild = config.build ?? {};
|
|
3207
|
-
const buildResolved = isDev ? {
|
|
3208
|
-
showSlideBrowser: true,
|
|
3209
|
-
showSlideUi: true,
|
|
3210
|
-
allowHtmlDownload: true
|
|
3211
|
-
} : {
|
|
3212
|
-
showSlideBrowser: userBuild.showSlideBrowser ?? true,
|
|
3213
|
-
showSlideUi: userBuild.showSlideUi ?? true,
|
|
3214
|
-
allowHtmlDownload: userBuild.allowHtmlDownload ?? true
|
|
3215
|
-
};
|
|
3216
|
-
const resolvedConfig = {
|
|
3217
|
-
...config,
|
|
3218
|
-
build: buildResolved,
|
|
3219
|
-
version: coreVersion
|
|
3220
|
-
};
|
|
3221
|
-
return `export default ${JSON.stringify(resolvedConfig)};\n`;
|
|
3222
|
-
}
|
|
3223
|
-
if (id === resolved$1(FOLDERS_VMOD)) {
|
|
3224
|
-
const manifest = await readManifest(manifestPath);
|
|
3225
|
-
return `export default ${JSON.stringify(manifest)};\n`;
|
|
3226
|
-
}
|
|
3227
|
-
return null;
|
|
3228
|
-
},
|
|
5792
|
+
name: "lemonriver:notes",
|
|
5793
|
+
apply: "serve",
|
|
3229
5794
|
handleHotUpdate(ctx) {
|
|
3230
|
-
const slideId = slideIdForEntry(ctx.file);
|
|
3231
|
-
if (!slideId) return;
|
|
3232
5795
|
if (hasRecentWrite(ctx.file)) return [];
|
|
3233
|
-
queueSlideChanged(ctx.server, slideId);
|
|
3234
|
-
return [];
|
|
3235
5796
|
},
|
|
3236
5797
|
configureServer(server) {
|
|
3237
|
-
|
|
3238
|
-
|
|
3239
|
-
|
|
3240
|
-
|
|
3241
|
-
|
|
3242
|
-
|
|
3243
|
-
const
|
|
3244
|
-
|
|
3245
|
-
|
|
3246
|
-
|
|
3247
|
-
|
|
3248
|
-
|
|
3249
|
-
|
|
3250
|
-
|
|
3251
|
-
|
|
3252
|
-
|
|
3253
|
-
|
|
3254
|
-
|
|
3255
|
-
|
|
3256
|
-
|
|
3257
|
-
|
|
3258
|
-
|
|
3259
|
-
|
|
3260
|
-
|
|
3261
|
-
|
|
3262
|
-
}
|
|
3263
|
-
|
|
3264
|
-
|
|
3265
|
-
server.watcher.on("change", (p) => {
|
|
3266
|
-
if (p === manifestPath) invalidateFolders();
|
|
5798
|
+
server.middlewares.use("/__notes", async (req, res, next) => {
|
|
5799
|
+
const url = new URL(req.url ?? "/", "http://local");
|
|
5800
|
+
if ((req.method ?? "GET") !== "PUT" || url.pathname !== "/") return next();
|
|
5801
|
+
const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
|
|
5802
|
+
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
5803
|
+
try {
|
|
5804
|
+
const body = await readBody(req);
|
|
5805
|
+
const slideId = body.slideId ?? "";
|
|
5806
|
+
const file = resolveSlideEntry(slidesRoot, slideId);
|
|
5807
|
+
if (!file) return json(res, 400, { error: "invalid slideId" });
|
|
5808
|
+
if (typeof body.index !== "number") return json(res, 400, { error: "missing index" });
|
|
5809
|
+
if (typeof body.text !== "string") return json(res, 400, { error: "missing text" });
|
|
5810
|
+
const source = await readSlideSource(file);
|
|
5811
|
+
if (source === null) return json(res, 404, { error: "slide not found" });
|
|
5812
|
+
const result = applyNotesEdit(source, body.index, body.text);
|
|
5813
|
+
if (!result.ok) return json(res, result.status, { error: result.error });
|
|
5814
|
+
const changed = result.source !== source;
|
|
5815
|
+
if (changed) {
|
|
5816
|
+
recordWrite(file);
|
|
5817
|
+
await fs.writeFile(file, result.source, "utf8");
|
|
5818
|
+
}
|
|
5819
|
+
return json(res, 200, {
|
|
5820
|
+
ok: true,
|
|
5821
|
+
changed
|
|
5822
|
+
});
|
|
5823
|
+
} catch (err) {
|
|
5824
|
+
json(res, 500, { error: String(err.message ?? err) });
|
|
5825
|
+
}
|
|
3267
5826
|
});
|
|
3268
|
-
|
|
3269
|
-
|
|
5827
|
+
}
|
|
5828
|
+
};
|
|
5829
|
+
}
|
|
5830
|
+
//#endregion
|
|
5831
|
+
//#region src/vite/server-info-plugin.ts
|
|
5832
|
+
function serverInfoUrl(address, https, base) {
|
|
5833
|
+
let host = address.address === "::" || address.address === "0.0.0.0" ? "localhost" : address.address;
|
|
5834
|
+
if (host.includes(":")) host = `[${host}]`;
|
|
5835
|
+
const pathname = base.startsWith("/") ? base : "/";
|
|
5836
|
+
return `${https ? "https" : "http"}://${host}:${address.port}${pathname}`;
|
|
5837
|
+
}
|
|
5838
|
+
function serverInfoPlugin(opts) {
|
|
5839
|
+
const outDir = path.join(opts.userCwd, "node_modules", ".open-slide");
|
|
5840
|
+
const outFile = path.join(outDir, "server.json");
|
|
5841
|
+
return {
|
|
5842
|
+
name: "open-slide:server-info",
|
|
5843
|
+
apply: "serve",
|
|
5844
|
+
configureServer(server) {
|
|
5845
|
+
const httpServer = server.httpServer;
|
|
5846
|
+
if (!httpServer) return;
|
|
5847
|
+
let publication = Promise.resolve(null);
|
|
5848
|
+
httpServer.on("listening", () => {
|
|
5849
|
+
const address = httpServer.address();
|
|
5850
|
+
if (!address || typeof address === "string") return;
|
|
5851
|
+
const token = randomUUID();
|
|
5852
|
+
const body = {
|
|
5853
|
+
url: serverInfoUrl(address, Boolean(server.config.server.https), server.config.base),
|
|
5854
|
+
port: address.port,
|
|
5855
|
+
pid: process.pid,
|
|
5856
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
5857
|
+
token
|
|
5858
|
+
};
|
|
5859
|
+
const tmpFile = `${outFile}.${token}.tmp`;
|
|
5860
|
+
publication = (async () => {
|
|
5861
|
+
try {
|
|
5862
|
+
await fs.mkdir(outDir, { recursive: true });
|
|
5863
|
+
await fs.writeFile(tmpFile, `${JSON.stringify(body, null, 2)}\n`, "utf8");
|
|
5864
|
+
await fs.rename(tmpFile, outFile);
|
|
5865
|
+
return token;
|
|
5866
|
+
} catch {
|
|
5867
|
+
await fs.rm(tmpFile, { force: true }).catch(() => {});
|
|
5868
|
+
return null;
|
|
5869
|
+
}
|
|
5870
|
+
})();
|
|
3270
5871
|
});
|
|
3271
|
-
|
|
3272
|
-
|
|
5872
|
+
httpServer.on("close", async () => {
|
|
5873
|
+
const token = await publication;
|
|
5874
|
+
if (!token) return;
|
|
5875
|
+
try {
|
|
5876
|
+
if (JSON.parse(readFileSync(outFile, "utf8")).token === token) rmSync(outFile, { force: true });
|
|
5877
|
+
} catch {}
|
|
3273
5878
|
});
|
|
3274
5879
|
}
|
|
3275
5880
|
};
|
|
3276
5881
|
}
|
|
3277
|
-
async function loadUserConfig(userCwd) {
|
|
3278
|
-
const file = CONFIG_FILES.map((name) => path.join(userCwd, name)).find((p) => existsSync(p));
|
|
3279
|
-
if (!file) return {};
|
|
3280
|
-
return (await loadConfigFromFile({
|
|
3281
|
-
command: "serve",
|
|
3282
|
-
mode: "development"
|
|
3283
|
-
}, file, userCwd, "silent"))?.config ?? {};
|
|
3284
|
-
}
|
|
3285
5882
|
//#endregion
|
|
3286
5883
|
//#region src/vite/themes-plugin.ts
|
|
3287
5884
|
const THEMES_VMOD = "virtual:open-slide/themes";
|
|
@@ -3482,7 +6079,8 @@ async function createViteConfig(opts) {
|
|
|
3482
6079
|
userCwd,
|
|
3483
6080
|
slidesDir,
|
|
3484
6081
|
assetsDir,
|
|
3485
|
-
coreVersion: CORE_VERSION
|
|
6082
|
+
coreVersion: CORE_VERSION,
|
|
6083
|
+
agentEnabled: config.agent?.enabled ?? true
|
|
3486
6084
|
}),
|
|
3487
6085
|
notesPlugin({
|
|
3488
6086
|
userCwd,
|
|
@@ -3491,7 +6089,9 @@ async function createViteConfig(opts) {
|
|
|
3491
6089
|
currentPlugin({
|
|
3492
6090
|
userCwd,
|
|
3493
6091
|
slidesDir
|
|
3494
|
-
})
|
|
6092
|
+
}),
|
|
6093
|
+
serverInfoPlugin({ userCwd }),
|
|
6094
|
+
lemonRiverAppPlugin()
|
|
3495
6095
|
],
|
|
3496
6096
|
resolve: {
|
|
3497
6097
|
alias: {
|