moi-computer 0.0.3 → 0.1.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/bunfig.toml +4 -0
- package/client/api/workspaces.ts +277 -6
- package/client/assets/mcp/agentation.png +0 -0
- package/client/assets/mcp/airtable.png +0 -0
- package/client/assets/mcp/apollo.png +0 -0
- package/client/assets/mcp/asana.png +0 -0
- package/client/assets/mcp/box.png +0 -0
- package/client/assets/mcp/chrome.svg +33 -0
- package/client/assets/mcp/clickup.png +0 -0
- package/client/assets/mcp/cloudflare.png +0 -0
- package/client/assets/mcp/context7.png +0 -0
- package/client/assets/mcp/datadog.png +0 -0
- package/client/assets/mcp/dropbox.png +0 -0
- package/client/assets/mcp/elevenlabs.png +0 -0
- package/client/assets/mcp/exa.png +0 -0
- package/client/assets/mcp/firecrawl.png +0 -0
- package/client/assets/mcp/gmail.png +0 -0
- package/client/assets/mcp/googlecalendar.png +0 -0
- package/client/assets/mcp/googledrive.png +0 -0
- package/client/assets/mcp/grafana.png +0 -0
- package/client/assets/mcp/huggingface.png +0 -0
- package/client/assets/mcp/intercom.png +0 -0
- package/client/assets/mcp/monday.png +0 -0
- package/client/assets/mcp/mongodb.png +0 -0
- package/client/assets/mcp/paper.png +0 -0
- package/client/assets/mcp/paypal.png +0 -0
- package/client/assets/mcp/perplexity.png +0 -0
- package/client/assets/mcp/postgresql.png +0 -0
- package/client/assets/mcp/posthog.png +0 -0
- package/client/assets/mcp/puppeteer.png +0 -0
- package/client/assets/mcp/railway.png +0 -0
- package/client/assets/mcp/redis.png +0 -0
- package/client/assets/mcp/salesforce.png +0 -0
- package/client/assets/mcp/shopify.png +0 -0
- package/client/assets/mcp/snowflake.png +0 -0
- package/client/assets/mcp/telegram.png +0 -0
- package/client/assets/mcp/twilio.png +0 -0
- package/client/assets/mcp/zapier.png +0 -0
- package/client/components/App.tsx +7 -1
- package/client/components/ChatInput.tsx +194 -13
- package/client/components/ChatPanel.tsx +116 -47
- package/client/components/ChatPopup.tsx +1 -1
- package/client/components/IconMcp.tsx +21 -0
- package/client/components/McpMenu.tsx +125 -0
- package/client/components/ModelPicker.tsx +147 -0
- package/client/components/Scratchpad.tsx +775 -0
- package/client/components/ShimmerText.tsx +20 -0
- package/client/components/ThreadSelector.tsx +2 -2
- package/client/components/TurnView.tsx +111 -531
- package/client/components/WidgetShell.tsx +1 -1
- package/client/components/WorkspacesPage.tsx +12 -4
- package/client/components/layout/SidebarLayout.tsx +18 -9
- package/client/components/playground/ToolCallsPage.tsx +81 -0
- package/client/components/routes/workspace/[id].tsx +534 -141
- package/client/components/routes/workspace/create.tsx +155 -0
- package/client/components/settings/IconPicker.tsx +590 -0
- package/client/components/settings/SettingsPages.tsx +307 -0
- package/client/components/settings/WorkspaceSettings.tsx +92 -0
- package/client/components/tool-group/CodeBlock.tsx +41 -0
- package/client/components/tool-group/Collapse.tsx +28 -0
- package/client/components/tool-group/ReadImagePreview.tsx +46 -0
- package/client/components/tool-group/SubagentCard.tsx +135 -0
- package/client/components/tool-group/TimelineRow.tsx +147 -0
- package/client/components/tool-group/ToolCallGroup.tsx +231 -0
- package/client/components/tool-group/ToolOutput.tsx +139 -0
- package/client/components/tool-group/detect.ts +93 -0
- package/client/components/tool-group/fixtures.ts +315 -0
- package/client/components/tool-group/format.ts +211 -0
- package/client/components/tool-group/index.ts +9 -0
- package/client/components/ui/dialog.tsx +58 -0
- package/client/components/ui/hover-card.tsx +44 -0
- package/client/components/ui/switch.tsx +23 -0
- package/client/components/ui/tooltip.tsx +54 -0
- package/client/externalize-react.ts +6 -0
- package/client/hooks/useApplet.ts +117 -0
- package/client/hooks/useChat.ts +162 -62
- package/client/hooks/useMeiEvents.ts +9 -2
- package/client/hooks/useStickToBottom.ts +86 -0
- package/client/hooks/useWorkspaceTheme.ts +8 -2
- package/client/index.css +48 -2
- package/client/index.html +9 -5
- package/client/index.tsx +29 -2
- package/client/lib/WorkspaceContext.tsx +5 -8
- package/client/lib/WorkspaceLayoutContext.tsx +30 -10
- package/client/lib/applet-cache.ts +54 -0
- package/client/lib/connection.ts +237 -0
- package/client/lib/flags.ts +10 -0
- package/client/lib/mcp-icons.ts +142 -10
- package/client/lib/preview-turn.ts +37 -0
- package/client/lib/render-icon.ts +173 -0
- package/client/lib/scratch-executor.ts +20 -0
- package/client/lib/uploads.ts +18 -0
- package/client/main.tsx +5 -0
- package/client/store/live.ts +282 -0
- package/client/structured-clone-shim.ts +14 -0
- package/client/theme.css +2 -2
- package/client/vendor/emojibase/en/data.json +1 -0
- package/client/vendor/emojibase/en/messages.json +1 -0
- package/client/vendor/react/development/_impl/react-dom-client.js +15871 -0
- package/client/vendor/react/development/_impl/react-dom.js +223 -0
- package/client/vendor/react/development/_impl/react-jsx-dev-runtime.js +256 -0
- package/client/vendor/react/development/_impl/react-jsx-runtime.js +260 -0
- package/client/vendor/react/development/_impl/react.js +863 -0
- package/client/vendor/react/development/react-dom-client.js +6 -0
- package/client/vendor/react/development/react-dom.js +17 -0
- package/client/vendor/react/development/react-jsx-dev-runtime.js +5 -0
- package/client/vendor/react/development/react-jsx-runtime.js +6 -0
- package/client/vendor/react/development/react.js +47 -0
- package/client/vendor/react/production/_impl/react-dom-client.js +10361 -0
- package/client/vendor/react/production/_impl/react-dom.js +184 -0
- package/client/vendor/react/production/_impl/react-jsx-dev-runtime.js +37 -0
- package/client/vendor/react/production/_impl/react-jsx-runtime.js +60 -0
- package/client/vendor/react/production/_impl/react.js +428 -0
- package/client/vendor/react/production/react-dom-client.js +6 -0
- package/client/vendor/react/production/react-dom.js +17 -0
- package/client/vendor/react/production/react-jsx-dev-runtime.js +5 -0
- package/client/vendor/react/production/react-jsx-runtime.js +6 -0
- package/client/vendor/react/production/react.js +47 -0
- package/dist/agentation-4s0nn45p.png +0 -0
- package/dist/airtable-hsa66v6q.png +0 -0
- package/dist/apollo-2ed5dy2d.png +0 -0
- package/dist/asana-tvgtwbx2.png +0 -0
- package/dist/box-w3n36t5g.png +0 -0
- package/dist/chrome-tspm94rw.svg +33 -0
- package/dist/chunk-kc6e9nd4.css +1 -0
- package/dist/chunk-yf3p7qg7.js +673 -0
- package/dist/clickup-qqrqqvqb.png +0 -0
- package/dist/cloudflare-j9p931v6.png +0 -0
- package/dist/context7-8ht0xjfy.png +0 -0
- package/dist/datadog-70ne3yzt.png +0 -0
- package/dist/dropbox-4m5s9mgr.png +0 -0
- package/dist/elevenlabs-2nzzej1t.png +0 -0
- package/dist/exa-qqj3vr0x.png +0 -0
- package/dist/firecrawl-w2t8nehx.png +0 -0
- package/dist/gmail-sg6a5v3x.png +0 -0
- package/dist/googlecalendar-nqhh2v7r.png +0 -0
- package/dist/googledrive-6s8xyab7.png +0 -0
- package/dist/grafana-1yfsnwr6.png +0 -0
- package/dist/huggingface-kxzaxj83.png +0 -0
- package/dist/index.html +10 -6
- package/dist/intercom-td763jt8.png +0 -0
- package/dist/monday-jdbs4wwf.png +0 -0
- package/dist/mongodb-emzxvhd5.png +0 -0
- package/dist/paper-zbt34fab.png +0 -0
- package/dist/paypal-kwwf7xsc.png +0 -0
- package/dist/perplexity-4y63rxvj.png +0 -0
- package/dist/postgresql-qsspbsr1.png +0 -0
- package/dist/posthog-sphppc4w.png +0 -0
- package/dist/puppeteer-2xjt1a9b.png +0 -0
- package/dist/railway-834de8d2.png +0 -0
- package/dist/redis-spm6w2m1.png +0 -0
- package/dist/salesforce-1mk56v4z.png +0 -0
- package/dist/shopify-90dadaav.png +0 -0
- package/dist/snowflake-hfpykpgy.png +0 -0
- package/dist/telegram-v6tjyrs7.png +0 -0
- package/dist/twilio-dpyjdwpj.png +0 -0
- package/dist/zapier-p67qfch0.png +0 -0
- package/lib/attachment-note.ts +48 -0
- package/lib/claude-adapter.ts +219 -29
- package/lib/format.ts +32 -0
- package/lib/types.ts +314 -6
- package/package.json +10 -5
- package/server/CLAUDE.md +3 -0
- package/server/agent.ts +25 -118
- package/server/api.ts +593 -0
- package/server/applets.ts +396 -0
- package/server/build-applet.ts +580 -0
- package/server/cc-session.ts +611 -0
- package/server/cli-colors.ts +17 -0
- package/server/cli-ui.ts +52 -0
- package/server/cli.ts +964 -72
- package/server/control.ts +166 -19
- package/server/debug.ts +10 -0
- package/server/events.ts +24 -0
- package/server/functions-worker.ts +18 -2
- package/server/functions.ts +59 -12
- package/server/icon.ts +13 -0
- package/server/layout.ts +25 -3
- package/server/mcp.ts +125 -0
- package/server/moi-scaffold.ts +85 -0
- package/server/openclaw-session.ts +41 -10
- package/server/openclaw.ts +22 -0
- package/server/preview.ts +70 -0
- package/server/registry.ts +32 -2
- package/server/scratchpad-executor.ts +380 -0
- package/server/scratchpad-relay.ts +45 -0
- package/server/scratchpad.ts +171 -0
- package/server/skill-version.ts +146 -0
- package/server/skills-template.ts +6 -1
- package/server/state.ts +22 -36
- package/server/static.ts +23 -0
- package/server/status.ts +94 -0
- package/server/thread-config.ts +125 -0
- package/server/uploads.ts +0 -0
- package/server/vendor.ts +63 -0
- package/server/views.ts +0 -0
- package/server/web.ts +108 -253
- package/server/widgets.ts +52 -142
- package/server/workspace-config.ts +37 -0
- package/server/workspace-env.ts +407 -0
- package/server/workspace-init.ts +66 -0
- package/workspace/.claude/skills/moi-workspace/DESIGN.md +109 -0
- package/workspace/.claude/skills/moi-workspace/SCRATCHPAD.md +57 -0
- package/workspace/.claude/skills/moi-workspace/SKILL.md +252 -0
- package/workspace/.claude/skills/moi-workspace/VIEW-DESIGN.md +22 -0
- package/client/hooks/useWidget.ts +0 -72
- package/client/hooks/useWidgetList.ts +0 -30
- package/client/lib/ws.ts +0 -129
- package/client/store/chat.tsx +0 -162
- package/dist/chunk-4615fa69.js +0 -67
- package/dist/chunk-582xmy05.css +0 -1
- package/server/build-widget.ts +0 -343
- package/workspace/.claude/skills/widgets/DESIGN.md +0 -630
- package/workspace/.claude/skills/widgets/SKILL.md +0 -176
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
// Shared machinery for the kinds of **applet** — agent-authored UI units
|
|
2
|
+
// embedded in a workspace: grid **widgets** (`.moi/widgets/`) and full-screen
|
|
3
|
+
// **views** (`.moi/views/`). Both compile through `buildApplet` and are served
|
|
4
|
+
// as ESM. This module holds the kind-agnostic mechanics (paths, scan,
|
|
5
|
+
// staleness, prune, serve, build loop); the per-kind manifest shape, config
|
|
6
|
+
// schema, and MEI events live in `widgets.ts` / `views.ts`.
|
|
7
|
+
//
|
|
8
|
+
// Each applet builds into its OWN directory `.build/<kind>/<name>/`, holding a
|
|
9
|
+
// fixed `index.js` entry plus any code chunks and bundled assets (hashed
|
|
10
|
+
// images/fonts). The client dynamic-imports `<name>/index.js`; assets and
|
|
11
|
+
// chunks resolve module-relative from there. `.js` files carry the
|
|
12
|
+
// `%%MOI_APPLET_API_BASE%%` sentinel (for RPC + `fileUrl`), swapped to the real
|
|
13
|
+
// `/api/workspaces/<id>` base when served — so the on-disk bundle is
|
|
14
|
+
// workspace-agnostic.
|
|
15
|
+
import { realpathSync } from 'node:fs'
|
|
16
|
+
import { mkdir, readdir, rm } from 'node:fs/promises'
|
|
17
|
+
import { dirname, join, resolve, sep } from 'path'
|
|
18
|
+
|
|
19
|
+
import {
|
|
20
|
+
APPLET_API_BASE_SENTINEL,
|
|
21
|
+
type AppletKind,
|
|
22
|
+
buildApplet,
|
|
23
|
+
scanAssetImports,
|
|
24
|
+
scanServerImports
|
|
25
|
+
} from './build-applet'
|
|
26
|
+
|
|
27
|
+
export type AppletPaths = {
|
|
28
|
+
moiRoot: string
|
|
29
|
+
sourceDir: string
|
|
30
|
+
buildDir: string
|
|
31
|
+
manifestPath: string
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function getAppletPaths(workspacePath: string, kind: AppletKind): AppletPaths {
|
|
35
|
+
const moiRoot = join(workspacePath, '.moi')
|
|
36
|
+
const dir = kind === 'widget' ? 'widgets' : 'views'
|
|
37
|
+
const sourceDir = join(moiRoot, dir)
|
|
38
|
+
const buildDir = join(moiRoot, '.build', dir)
|
|
39
|
+
const manifestPath = join(buildDir, 'manifest.json')
|
|
40
|
+
return { moiRoot, sourceDir, buildDir, manifestPath }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Source module names in a kind's directory: `*.tsx`/`*.ts` minus `.server.ts`.
|
|
44
|
+
export async function scanSources(sourceDir: string): Promise<string[]> {
|
|
45
|
+
try {
|
|
46
|
+
const entries = await readdir(sourceDir)
|
|
47
|
+
return entries
|
|
48
|
+
.filter(f => /\.(tsx|ts)$/.test(f) && !f.endsWith('.server.ts'))
|
|
49
|
+
.map(f => f.replace(/\.tsx?$/, ''))
|
|
50
|
+
} catch {
|
|
51
|
+
return []
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function resolveSource(sourceDir: string, name: string): Promise<string | null> {
|
|
56
|
+
for (const ext of ['.tsx', '.ts']) {
|
|
57
|
+
const path = join(sourceDir, `${name}${ext}`)
|
|
58
|
+
if (await Bun.file(path).exists()) return path
|
|
59
|
+
}
|
|
60
|
+
return null
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// A bundle is stale if its entry `index.js` is missing, or the source — or any
|
|
64
|
+
// `.server.ts` it imports (RPC stubs are inlined) or asset it imports (emitted
|
|
65
|
+
// into the bundle dir) — is newer than the built entry.
|
|
66
|
+
async function needsRebuild(buildDir: string, name: string, srcPath: string): Promise<boolean> {
|
|
67
|
+
const built = Bun.file(join(buildDir, name, 'index.js'))
|
|
68
|
+
if (!(await built.exists())) return true
|
|
69
|
+
let sourceMtime = Bun.file(srcPath).lastModified
|
|
70
|
+
const source = await Bun.file(srcPath).text()
|
|
71
|
+
const dir = dirname(srcPath)
|
|
72
|
+
for (const specifier of scanServerImports(source)) {
|
|
73
|
+
const serverFile = Bun.file(join(dir, `${specifier}.server.ts`))
|
|
74
|
+
if (await serverFile.exists()) {
|
|
75
|
+
sourceMtime = Math.max(sourceMtime, serverFile.lastModified)
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
for (const specifier of scanAssetImports(source)) {
|
|
79
|
+
const assetFile = Bun.file(join(dir, specifier))
|
|
80
|
+
if (await assetFile.exists()) {
|
|
81
|
+
sourceMtime = Math.max(sourceMtime, assetFile.lastModified)
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return sourceMtime >= built.lastModified
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Built applet names: subdirectories of `buildDir` that hold an `index.js`
|
|
88
|
+
// entry. (`manifest.json` and any stray files are ignored.)
|
|
89
|
+
export async function listBuilt(buildDir: string): Promise<string[]> {
|
|
90
|
+
try {
|
|
91
|
+
const entries = await readdir(buildDir, { withFileTypes: true })
|
|
92
|
+
const names: string[] = []
|
|
93
|
+
for (const e of entries) {
|
|
94
|
+
if (!e.isDirectory()) continue
|
|
95
|
+
if (await Bun.file(join(buildDir, e.name, 'index.js')).exists()) names.push(e.name)
|
|
96
|
+
}
|
|
97
|
+
return names
|
|
98
|
+
} catch {
|
|
99
|
+
return []
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function pruneStaleBuilds(buildDir: string, sourceNames: Set<string>): Promise<void> {
|
|
104
|
+
let entries
|
|
105
|
+
try {
|
|
106
|
+
entries = await readdir(buildDir, { withFileTypes: true })
|
|
107
|
+
} catch {
|
|
108
|
+
return
|
|
109
|
+
}
|
|
110
|
+
for (const e of entries) {
|
|
111
|
+
// Drop build dirs whose source is gone…
|
|
112
|
+
if (e.isDirectory()) {
|
|
113
|
+
if (!sourceNames.has(e.name)) {
|
|
114
|
+
await rm(join(buildDir, e.name), { recursive: true, force: true }).catch(() => {})
|
|
115
|
+
}
|
|
116
|
+
continue
|
|
117
|
+
}
|
|
118
|
+
// …and sweep leftover flat `<name>.js` from the pre-directory layout (the
|
|
119
|
+
// new layout never writes `.js` directly under buildDir — entries live in
|
|
120
|
+
// `<name>/index.js`). manifest.json and other files are left alone.
|
|
121
|
+
if (e.isFile() && e.name.endsWith('.js')) {
|
|
122
|
+
await rm(join(buildDir, e.name), { force: true }).catch(() => {})
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// Files an applet may serve from its build dir, by extension. JS is swapped +
|
|
128
|
+
// served as code; everything else streams raw (Bun infers content-type and
|
|
129
|
+
// supports range requests).
|
|
130
|
+
const CODE_FILE_RE = /\.js$/
|
|
131
|
+
// A single flat filename in the bundle dir: index.js, chunk-<hash>.js, or a
|
|
132
|
+
// hashed asset. First char may be `_`/`-` (asset stems derive from the source
|
|
133
|
+
// basename, e.g. `_icon.png` → `_icon-<hash>.png`) but never `.`, so no dotfile
|
|
134
|
+
// can be requested; `..` is rejected separately.
|
|
135
|
+
const ALLOWED_FILE_RE = /^[a-zA-Z0-9_-][a-zA-Z0-9._-]*$/
|
|
136
|
+
|
|
137
|
+
// Serve one file from a compiled applet directory: the `index.js` entry, a code
|
|
138
|
+
// chunk, or a bundled asset. `apiBase` is the workspace's `/api/workspaces/<id>`
|
|
139
|
+
// prefix — substituted for the build-time sentinel in every `.js` so RPC and
|
|
140
|
+
// `fileUrl` calls hit the right workspace. Assets stream untouched.
|
|
141
|
+
export async function serveApplet(
|
|
142
|
+
kind: AppletKind,
|
|
143
|
+
name: string,
|
|
144
|
+
file: string,
|
|
145
|
+
workspacePath: string,
|
|
146
|
+
apiBase: string
|
|
147
|
+
): Promise<Response> {
|
|
148
|
+
if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
|
|
149
|
+
return new Response('Invalid name', { status: 400 })
|
|
150
|
+
}
|
|
151
|
+
// Single path segment, no traversal — the bundle dir is flat.
|
|
152
|
+
if (!ALLOWED_FILE_RE.test(file) || file.includes('..')) {
|
|
153
|
+
return new Response('Invalid file', { status: 400 })
|
|
154
|
+
}
|
|
155
|
+
const { buildDir } = getAppletPaths(workspacePath, kind)
|
|
156
|
+
const path = join(buildDir, name, file)
|
|
157
|
+
const bunFile = Bun.file(path)
|
|
158
|
+
if (!(await bunFile.exists())) {
|
|
159
|
+
return new Response(`"${name}" not built. Run: moi bundle`, { status: 404 })
|
|
160
|
+
}
|
|
161
|
+
if (CODE_FILE_RE.test(file)) {
|
|
162
|
+
const swapped = (await bunFile.text()).replaceAll(APPLET_API_BASE_SENTINEL, apiBase)
|
|
163
|
+
return new Response(swapped, { headers: { 'Content-Type': 'text/javascript; charset=utf-8' } })
|
|
164
|
+
}
|
|
165
|
+
return new Response(bunFile)
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// ---- route helpers ----------------------------------------------------------
|
|
169
|
+
// Pure helpers behind the applet/fs/rpc HTTP routes, kept here (not web.ts) so
|
|
170
|
+
// they're unit-testable without importing web.ts — which binds ports on load.
|
|
171
|
+
|
|
172
|
+
// The API base a served bundle's sentinel is rewritten to. RPC + `fileUrl`
|
|
173
|
+
// hang off it, matching what the compiled `rpc()` / `fileUrl()` prepend.
|
|
174
|
+
export function apiBaseFor(id: string): string {
|
|
175
|
+
return `/api/workspaces/${id}`
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// Split an applet file request `…/<segment>/<name>/<file>` into name + file. A
|
|
179
|
+
// bare `…/<segment>/<name>` (or legacy `…/<name>.js`) targets the entry.
|
|
180
|
+
export function parseAppletTail(
|
|
181
|
+
url: string,
|
|
182
|
+
id: string,
|
|
183
|
+
segment: 'widgets' | 'views'
|
|
184
|
+
): { name: string; file: string } {
|
|
185
|
+
const tail = new URL(url).pathname.split(`/api/workspaces/${id}/${segment}/`)[1] ?? ''
|
|
186
|
+
const slash = tail.indexOf('/')
|
|
187
|
+
if (slash === -1) return { name: tail.replace(/\.js$/, ''), file: 'index.js' }
|
|
188
|
+
return { name: tail.slice(0, slash), file: tail.slice(slash + 1) }
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// Extensions `fileUrl()` may stream from the workspace. Media + image/doc
|
|
192
|
+
// assets only — deliberately excludes text/data (`.json`, `.env`, `.md`,
|
|
193
|
+
// source) so the route can't be used to exfiltrate arbitrary workspace data.
|
|
194
|
+
const FS_MEDIA_RE =
|
|
195
|
+
/\.(mp4|webm|mov|m4v|mkv|mp3|wav|ogg|oga|m4a|flac|aac|opus|png|jpe?g|gif|webp|avif|svg|ico|pdf|vtt|srt)$/i
|
|
196
|
+
|
|
197
|
+
// Resolve a `/fs/`-style tail to a real on-disk path inside the workspace root,
|
|
198
|
+
// or an error Response. Hard guards (defense in depth): reject empty/`.`/`..`/
|
|
199
|
+
// dotfile segments and anything resolving outside the root, and require a media
|
|
200
|
+
// extension. The workspace holds secrets (`.env`, `.moi/`) and the routes built
|
|
201
|
+
// on this are unauthenticated — these guards are the protection, not the
|
|
202
|
+
// localhost bind. Shared by the raw stream (`serveWorkspaceFile`) and the image
|
|
203
|
+
// preview route (server/preview.ts).
|
|
204
|
+
export function resolveWorkspaceMediaFile(workspaceRoot: string, tail: string): string | Response {
|
|
205
|
+
let rel: string
|
|
206
|
+
try {
|
|
207
|
+
rel = decodeURIComponent(tail)
|
|
208
|
+
} catch {
|
|
209
|
+
return new Response('Bad path', { status: 400 })
|
|
210
|
+
}
|
|
211
|
+
if (!rel || rel.includes('\0')) return new Response('Bad path', { status: 400 })
|
|
212
|
+
|
|
213
|
+
const segments = rel.split('/')
|
|
214
|
+
if (segments.some(s => s === '' || s === '.' || s === '..' || s.startsWith('.'))) {
|
|
215
|
+
return new Response('Forbidden', { status: 403 })
|
|
216
|
+
}
|
|
217
|
+
if (!FS_MEDIA_RE.test(rel)) return new Response('Unsupported file type', { status: 415 })
|
|
218
|
+
|
|
219
|
+
const root = resolve(workspaceRoot)
|
|
220
|
+
const target = resolve(workspaceRoot, rel)
|
|
221
|
+
if (target !== root && !target.startsWith(root + sep)) {
|
|
222
|
+
return new Response('Forbidden', { status: 403 })
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// The lexical check above is not enough: a symlink that lives inside the root
|
|
226
|
+
// but points outside it would pass. Canonicalize both sides and re-check on
|
|
227
|
+
// the real paths — this blocks symlink escape while still allowing symlinks
|
|
228
|
+
// that stay within the workspace. realpathSync throws ENOENT for a missing
|
|
229
|
+
// file, which doubles as the existence check (→ 404). Both sides are
|
|
230
|
+
// canonicalized so a symlinked root (e.g. macOS /tmp → /private/tmp) isn't a
|
|
231
|
+
// false escape.
|
|
232
|
+
let realTarget: string
|
|
233
|
+
try {
|
|
234
|
+
realTarget = realpathSync(target)
|
|
235
|
+
} catch {
|
|
236
|
+
return new Response('Not found', { status: 404 })
|
|
237
|
+
}
|
|
238
|
+
let realRoot: string
|
|
239
|
+
try {
|
|
240
|
+
realRoot = realpathSync(root)
|
|
241
|
+
} catch {
|
|
242
|
+
return new Response('Forbidden', { status: 403 })
|
|
243
|
+
}
|
|
244
|
+
if (realTarget !== realRoot && !realTarget.startsWith(realRoot + sep)) {
|
|
245
|
+
return new Response('Forbidden', { status: 403 })
|
|
246
|
+
}
|
|
247
|
+
return realTarget
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// Stream a media file from the workspace root (guards: see
|
|
251
|
+
// `resolveWorkspaceMediaFile`).
|
|
252
|
+
//
|
|
253
|
+
// Range is handled explicitly (slice the BunFile, 206 + Content-Range): Bun's
|
|
254
|
+
// implicit range handling for `new Response(Bun.file())` doesn't fire once any
|
|
255
|
+
// headers object is attached, and <video>/<audio> seeking needs byte ranges.
|
|
256
|
+
export async function serveWorkspaceFile(
|
|
257
|
+
workspaceRoot: string,
|
|
258
|
+
tail: string,
|
|
259
|
+
range?: string | null
|
|
260
|
+
): Promise<Response> {
|
|
261
|
+
const realTarget = resolveWorkspaceMediaFile(workspaceRoot, tail)
|
|
262
|
+
if (realTarget instanceof Response) return realTarget
|
|
263
|
+
const file = Bun.file(realTarget)
|
|
264
|
+
|
|
265
|
+
const size = file.size
|
|
266
|
+
const type = file.type || 'application/octet-stream'
|
|
267
|
+
const parsed = range ? parseByteRange(range, size) : null
|
|
268
|
+
|
|
269
|
+
if (parsed === 'invalid') {
|
|
270
|
+
return new Response('Range Not Satisfiable', {
|
|
271
|
+
status: 416,
|
|
272
|
+
headers: { 'Content-Range': `bytes */${size}`, 'Accept-Ranges': 'bytes' }
|
|
273
|
+
})
|
|
274
|
+
}
|
|
275
|
+
if (parsed) {
|
|
276
|
+
const { start, end } = parsed
|
|
277
|
+
return new Response(file.slice(start, end + 1), {
|
|
278
|
+
status: 206,
|
|
279
|
+
headers: {
|
|
280
|
+
'Content-Type': type,
|
|
281
|
+
'Content-Length': String(end - start + 1),
|
|
282
|
+
'Content-Range': `bytes ${start}-${end}/${size}`,
|
|
283
|
+
'Accept-Ranges': 'bytes'
|
|
284
|
+
}
|
|
285
|
+
})
|
|
286
|
+
}
|
|
287
|
+
return new Response(file, {
|
|
288
|
+
headers: { 'Content-Type': type, 'Content-Length': String(size), 'Accept-Ranges': 'bytes' }
|
|
289
|
+
})
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// Parse a single `bytes=start-end` (or suffix `bytes=-N`) range against a known
|
|
293
|
+
// size. Returns the inclusive [start, end], null when there's no usable range
|
|
294
|
+
// header, or 'invalid' for an unsatisfiable range (→ 416). Multi-range requests
|
|
295
|
+
// are not supported (we serve the whole file instead — null).
|
|
296
|
+
function parseByteRange(
|
|
297
|
+
header: string,
|
|
298
|
+
size: number
|
|
299
|
+
): { start: number; end: number } | null | 'invalid' {
|
|
300
|
+
const m = /^bytes=(\d*)-(\d*)$/.exec(header.trim())
|
|
301
|
+
if (!m) return null
|
|
302
|
+
const hasStart = m[1] !== ''
|
|
303
|
+
const hasEnd = m[2] !== ''
|
|
304
|
+
if (!hasStart && !hasEnd) return null
|
|
305
|
+
if (size === 0) return 'invalid'
|
|
306
|
+
|
|
307
|
+
let start: number
|
|
308
|
+
let end: number
|
|
309
|
+
if (!hasStart) {
|
|
310
|
+
// Suffix range: the last N bytes.
|
|
311
|
+
const n = parseInt(m[2], 10)
|
|
312
|
+
start = Math.max(0, size - n)
|
|
313
|
+
end = size - 1
|
|
314
|
+
} else {
|
|
315
|
+
start = parseInt(m[1], 10)
|
|
316
|
+
end = hasEnd ? Math.min(parseInt(m[2], 10), size - 1) : size - 1
|
|
317
|
+
}
|
|
318
|
+
if (start > end || start >= size || start < 0) return 'invalid'
|
|
319
|
+
return { start, end }
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
export type AppletBuildResult<C> = {
|
|
323
|
+
name: string
|
|
324
|
+
status: 'built' | 'skipped' | 'failed'
|
|
325
|
+
error?: string
|
|
326
|
+
serverModules?: string[]
|
|
327
|
+
config?: C | null
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// Build every stale (or all, when `force`) source for one kind: prunes orphaned
|
|
331
|
+
// build dirs, writes fresh `<name>/` directories (entry + chunks + assets), and
|
|
332
|
+
// returns per-entry results with the parsed config and server-module names.
|
|
333
|
+
// Manifest persistence and MEI broadcasting are the caller's responsibility —
|
|
334
|
+
// they differ per kind.
|
|
335
|
+
export async function buildApplets<C>(
|
|
336
|
+
workspacePath: string,
|
|
337
|
+
kind: AppletKind,
|
|
338
|
+
force: boolean
|
|
339
|
+
): Promise<{ names: string[]; results: AppletBuildResult<C>[]; ms: number }> {
|
|
340
|
+
const t0 = performance.now()
|
|
341
|
+
const { sourceDir, buildDir, moiRoot } = getAppletPaths(workspacePath, kind)
|
|
342
|
+
const names = await scanSources(sourceDir)
|
|
343
|
+
|
|
344
|
+
// Only scaffold the build dir once there's something to build — never
|
|
345
|
+
// fabricate a `.build/` (and the phantom nested `.moi/.moi/` it implies) for a
|
|
346
|
+
// directory with no sources. When sources have all been deleted we skip the
|
|
347
|
+
// mkdir but still prune so orphaned build dirs are swept (pruneStaleBuilds
|
|
348
|
+
// no-ops if buildDir doesn't exist).
|
|
349
|
+
if (names.length > 0) {
|
|
350
|
+
await mkdir(buildDir, { recursive: true })
|
|
351
|
+
}
|
|
352
|
+
await pruneStaleBuilds(buildDir, new Set(names))
|
|
353
|
+
|
|
354
|
+
const jobs = await Promise.all(
|
|
355
|
+
names.map(async name => {
|
|
356
|
+
const srcPath = await resolveSource(sourceDir, name)
|
|
357
|
+
if (!srcPath) return { name, status: 'failed' as const, error: 'Source file not found' }
|
|
358
|
+
if (!force && !(await needsRebuild(buildDir, name, srcPath))) {
|
|
359
|
+
return { name, status: 'skipped' as const }
|
|
360
|
+
}
|
|
361
|
+
return { name, srcPath, status: 'pending' as const }
|
|
362
|
+
})
|
|
363
|
+
)
|
|
364
|
+
|
|
365
|
+
const results = await Promise.all(
|
|
366
|
+
jobs.map(async (job): Promise<AppletBuildResult<C>> => {
|
|
367
|
+
if (job.status === 'failed') return { name: job.name, status: 'failed', error: job.error }
|
|
368
|
+
if (job.status === 'skipped') return { name: job.name, status: 'skipped' }
|
|
369
|
+
try {
|
|
370
|
+
const artifact = await buildApplet(job.srcPath!, moiRoot, kind)
|
|
371
|
+
// Clear the dir first so stale hashed assets from a prior build don't
|
|
372
|
+
// accumulate, then write the fresh entry + chunks + assets.
|
|
373
|
+
const dir = join(buildDir, job.name)
|
|
374
|
+
await rm(dir, { recursive: true, force: true })
|
|
375
|
+
await mkdir(dir, { recursive: true })
|
|
376
|
+
for (const f of artifact.files) {
|
|
377
|
+
await Bun.write(join(dir, f.name), f.data)
|
|
378
|
+
}
|
|
379
|
+
return {
|
|
380
|
+
name: job.name,
|
|
381
|
+
status: 'built',
|
|
382
|
+
serverModules: artifact.serverModules.map(m => m.name),
|
|
383
|
+
config: (artifact.config as C | null) ?? null
|
|
384
|
+
}
|
|
385
|
+
} catch (err) {
|
|
386
|
+
return {
|
|
387
|
+
name: job.name,
|
|
388
|
+
status: 'failed',
|
|
389
|
+
error: err instanceof Error ? err.message : 'Unknown error'
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
})
|
|
393
|
+
)
|
|
394
|
+
|
|
395
|
+
return { names, results, ms: Math.round(performance.now() - t0) }
|
|
396
|
+
}
|