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.
Files changed (214) hide show
  1. package/bunfig.toml +4 -0
  2. package/client/api/workspaces.ts +277 -6
  3. package/client/assets/mcp/agentation.png +0 -0
  4. package/client/assets/mcp/airtable.png +0 -0
  5. package/client/assets/mcp/apollo.png +0 -0
  6. package/client/assets/mcp/asana.png +0 -0
  7. package/client/assets/mcp/box.png +0 -0
  8. package/client/assets/mcp/chrome.svg +33 -0
  9. package/client/assets/mcp/clickup.png +0 -0
  10. package/client/assets/mcp/cloudflare.png +0 -0
  11. package/client/assets/mcp/context7.png +0 -0
  12. package/client/assets/mcp/datadog.png +0 -0
  13. package/client/assets/mcp/dropbox.png +0 -0
  14. package/client/assets/mcp/elevenlabs.png +0 -0
  15. package/client/assets/mcp/exa.png +0 -0
  16. package/client/assets/mcp/firecrawl.png +0 -0
  17. package/client/assets/mcp/gmail.png +0 -0
  18. package/client/assets/mcp/googlecalendar.png +0 -0
  19. package/client/assets/mcp/googledrive.png +0 -0
  20. package/client/assets/mcp/grafana.png +0 -0
  21. package/client/assets/mcp/huggingface.png +0 -0
  22. package/client/assets/mcp/intercom.png +0 -0
  23. package/client/assets/mcp/monday.png +0 -0
  24. package/client/assets/mcp/mongodb.png +0 -0
  25. package/client/assets/mcp/paper.png +0 -0
  26. package/client/assets/mcp/paypal.png +0 -0
  27. package/client/assets/mcp/perplexity.png +0 -0
  28. package/client/assets/mcp/postgresql.png +0 -0
  29. package/client/assets/mcp/posthog.png +0 -0
  30. package/client/assets/mcp/puppeteer.png +0 -0
  31. package/client/assets/mcp/railway.png +0 -0
  32. package/client/assets/mcp/redis.png +0 -0
  33. package/client/assets/mcp/salesforce.png +0 -0
  34. package/client/assets/mcp/shopify.png +0 -0
  35. package/client/assets/mcp/snowflake.png +0 -0
  36. package/client/assets/mcp/telegram.png +0 -0
  37. package/client/assets/mcp/twilio.png +0 -0
  38. package/client/assets/mcp/zapier.png +0 -0
  39. package/client/components/App.tsx +7 -1
  40. package/client/components/ChatInput.tsx +194 -13
  41. package/client/components/ChatPanel.tsx +116 -47
  42. package/client/components/ChatPopup.tsx +1 -1
  43. package/client/components/IconMcp.tsx +21 -0
  44. package/client/components/McpMenu.tsx +125 -0
  45. package/client/components/ModelPicker.tsx +147 -0
  46. package/client/components/Scratchpad.tsx +775 -0
  47. package/client/components/ShimmerText.tsx +20 -0
  48. package/client/components/ThreadSelector.tsx +2 -2
  49. package/client/components/TurnView.tsx +111 -531
  50. package/client/components/WidgetShell.tsx +1 -1
  51. package/client/components/WorkspacesPage.tsx +12 -4
  52. package/client/components/layout/SidebarLayout.tsx +18 -9
  53. package/client/components/playground/ToolCallsPage.tsx +81 -0
  54. package/client/components/routes/workspace/[id].tsx +534 -141
  55. package/client/components/routes/workspace/create.tsx +155 -0
  56. package/client/components/settings/IconPicker.tsx +590 -0
  57. package/client/components/settings/SettingsPages.tsx +307 -0
  58. package/client/components/settings/WorkspaceSettings.tsx +92 -0
  59. package/client/components/tool-group/CodeBlock.tsx +41 -0
  60. package/client/components/tool-group/Collapse.tsx +28 -0
  61. package/client/components/tool-group/ReadImagePreview.tsx +46 -0
  62. package/client/components/tool-group/SubagentCard.tsx +135 -0
  63. package/client/components/tool-group/TimelineRow.tsx +147 -0
  64. package/client/components/tool-group/ToolCallGroup.tsx +231 -0
  65. package/client/components/tool-group/ToolOutput.tsx +139 -0
  66. package/client/components/tool-group/detect.ts +93 -0
  67. package/client/components/tool-group/fixtures.ts +315 -0
  68. package/client/components/tool-group/format.ts +211 -0
  69. package/client/components/tool-group/index.ts +9 -0
  70. package/client/components/ui/dialog.tsx +58 -0
  71. package/client/components/ui/hover-card.tsx +44 -0
  72. package/client/components/ui/switch.tsx +23 -0
  73. package/client/components/ui/tooltip.tsx +54 -0
  74. package/client/externalize-react.ts +6 -0
  75. package/client/hooks/useApplet.ts +117 -0
  76. package/client/hooks/useChat.ts +162 -62
  77. package/client/hooks/useMeiEvents.ts +9 -2
  78. package/client/hooks/useStickToBottom.ts +86 -0
  79. package/client/hooks/useWorkspaceTheme.ts +8 -2
  80. package/client/index.css +48 -2
  81. package/client/index.html +9 -5
  82. package/client/index.tsx +29 -2
  83. package/client/lib/WorkspaceContext.tsx +5 -8
  84. package/client/lib/WorkspaceLayoutContext.tsx +30 -10
  85. package/client/lib/applet-cache.ts +54 -0
  86. package/client/lib/connection.ts +237 -0
  87. package/client/lib/flags.ts +10 -0
  88. package/client/lib/mcp-icons.ts +142 -10
  89. package/client/lib/preview-turn.ts +37 -0
  90. package/client/lib/render-icon.ts +173 -0
  91. package/client/lib/scratch-executor.ts +20 -0
  92. package/client/lib/uploads.ts +18 -0
  93. package/client/main.tsx +5 -0
  94. package/client/store/live.ts +282 -0
  95. package/client/structured-clone-shim.ts +14 -0
  96. package/client/theme.css +2 -2
  97. package/client/vendor/emojibase/en/data.json +1 -0
  98. package/client/vendor/emojibase/en/messages.json +1 -0
  99. package/client/vendor/react/development/_impl/react-dom-client.js +15871 -0
  100. package/client/vendor/react/development/_impl/react-dom.js +223 -0
  101. package/client/vendor/react/development/_impl/react-jsx-dev-runtime.js +256 -0
  102. package/client/vendor/react/development/_impl/react-jsx-runtime.js +260 -0
  103. package/client/vendor/react/development/_impl/react.js +863 -0
  104. package/client/vendor/react/development/react-dom-client.js +6 -0
  105. package/client/vendor/react/development/react-dom.js +17 -0
  106. package/client/vendor/react/development/react-jsx-dev-runtime.js +5 -0
  107. package/client/vendor/react/development/react-jsx-runtime.js +6 -0
  108. package/client/vendor/react/development/react.js +47 -0
  109. package/client/vendor/react/production/_impl/react-dom-client.js +10361 -0
  110. package/client/vendor/react/production/_impl/react-dom.js +184 -0
  111. package/client/vendor/react/production/_impl/react-jsx-dev-runtime.js +37 -0
  112. package/client/vendor/react/production/_impl/react-jsx-runtime.js +60 -0
  113. package/client/vendor/react/production/_impl/react.js +428 -0
  114. package/client/vendor/react/production/react-dom-client.js +6 -0
  115. package/client/vendor/react/production/react-dom.js +17 -0
  116. package/client/vendor/react/production/react-jsx-dev-runtime.js +5 -0
  117. package/client/vendor/react/production/react-jsx-runtime.js +6 -0
  118. package/client/vendor/react/production/react.js +47 -0
  119. package/dist/agentation-4s0nn45p.png +0 -0
  120. package/dist/airtable-hsa66v6q.png +0 -0
  121. package/dist/apollo-2ed5dy2d.png +0 -0
  122. package/dist/asana-tvgtwbx2.png +0 -0
  123. package/dist/box-w3n36t5g.png +0 -0
  124. package/dist/chrome-tspm94rw.svg +33 -0
  125. package/dist/chunk-kc6e9nd4.css +1 -0
  126. package/dist/chunk-yf3p7qg7.js +673 -0
  127. package/dist/clickup-qqrqqvqb.png +0 -0
  128. package/dist/cloudflare-j9p931v6.png +0 -0
  129. package/dist/context7-8ht0xjfy.png +0 -0
  130. package/dist/datadog-70ne3yzt.png +0 -0
  131. package/dist/dropbox-4m5s9mgr.png +0 -0
  132. package/dist/elevenlabs-2nzzej1t.png +0 -0
  133. package/dist/exa-qqj3vr0x.png +0 -0
  134. package/dist/firecrawl-w2t8nehx.png +0 -0
  135. package/dist/gmail-sg6a5v3x.png +0 -0
  136. package/dist/googlecalendar-nqhh2v7r.png +0 -0
  137. package/dist/googledrive-6s8xyab7.png +0 -0
  138. package/dist/grafana-1yfsnwr6.png +0 -0
  139. package/dist/huggingface-kxzaxj83.png +0 -0
  140. package/dist/index.html +10 -6
  141. package/dist/intercom-td763jt8.png +0 -0
  142. package/dist/monday-jdbs4wwf.png +0 -0
  143. package/dist/mongodb-emzxvhd5.png +0 -0
  144. package/dist/paper-zbt34fab.png +0 -0
  145. package/dist/paypal-kwwf7xsc.png +0 -0
  146. package/dist/perplexity-4y63rxvj.png +0 -0
  147. package/dist/postgresql-qsspbsr1.png +0 -0
  148. package/dist/posthog-sphppc4w.png +0 -0
  149. package/dist/puppeteer-2xjt1a9b.png +0 -0
  150. package/dist/railway-834de8d2.png +0 -0
  151. package/dist/redis-spm6w2m1.png +0 -0
  152. package/dist/salesforce-1mk56v4z.png +0 -0
  153. package/dist/shopify-90dadaav.png +0 -0
  154. package/dist/snowflake-hfpykpgy.png +0 -0
  155. package/dist/telegram-v6tjyrs7.png +0 -0
  156. package/dist/twilio-dpyjdwpj.png +0 -0
  157. package/dist/zapier-p67qfch0.png +0 -0
  158. package/lib/attachment-note.ts +48 -0
  159. package/lib/claude-adapter.ts +219 -29
  160. package/lib/format.ts +32 -0
  161. package/lib/types.ts +314 -6
  162. package/package.json +10 -5
  163. package/server/CLAUDE.md +3 -0
  164. package/server/agent.ts +25 -118
  165. package/server/api.ts +593 -0
  166. package/server/applets.ts +396 -0
  167. package/server/build-applet.ts +580 -0
  168. package/server/cc-session.ts +611 -0
  169. package/server/cli-colors.ts +17 -0
  170. package/server/cli-ui.ts +52 -0
  171. package/server/cli.ts +964 -72
  172. package/server/control.ts +166 -19
  173. package/server/debug.ts +10 -0
  174. package/server/events.ts +24 -0
  175. package/server/functions-worker.ts +18 -2
  176. package/server/functions.ts +59 -12
  177. package/server/icon.ts +13 -0
  178. package/server/layout.ts +25 -3
  179. package/server/mcp.ts +125 -0
  180. package/server/moi-scaffold.ts +85 -0
  181. package/server/openclaw-session.ts +41 -10
  182. package/server/openclaw.ts +22 -0
  183. package/server/preview.ts +70 -0
  184. package/server/registry.ts +32 -2
  185. package/server/scratchpad-executor.ts +380 -0
  186. package/server/scratchpad-relay.ts +45 -0
  187. package/server/scratchpad.ts +171 -0
  188. package/server/skill-version.ts +146 -0
  189. package/server/skills-template.ts +6 -1
  190. package/server/state.ts +22 -36
  191. package/server/static.ts +23 -0
  192. package/server/status.ts +94 -0
  193. package/server/thread-config.ts +125 -0
  194. package/server/uploads.ts +0 -0
  195. package/server/vendor.ts +63 -0
  196. package/server/views.ts +0 -0
  197. package/server/web.ts +108 -253
  198. package/server/widgets.ts +52 -142
  199. package/server/workspace-config.ts +37 -0
  200. package/server/workspace-env.ts +407 -0
  201. package/server/workspace-init.ts +66 -0
  202. package/workspace/.claude/skills/moi-workspace/DESIGN.md +109 -0
  203. package/workspace/.claude/skills/moi-workspace/SCRATCHPAD.md +57 -0
  204. package/workspace/.claude/skills/moi-workspace/SKILL.md +252 -0
  205. package/workspace/.claude/skills/moi-workspace/VIEW-DESIGN.md +22 -0
  206. package/client/hooks/useWidget.ts +0 -72
  207. package/client/hooks/useWidgetList.ts +0 -30
  208. package/client/lib/ws.ts +0 -129
  209. package/client/store/chat.tsx +0 -162
  210. package/dist/chunk-4615fa69.js +0 -67
  211. package/dist/chunk-582xmy05.css +0 -1
  212. package/server/build-widget.ts +0 -343
  213. package/workspace/.claude/skills/widgets/DESIGN.md +0 -630
  214. package/workspace/.claude/skills/widgets/SKILL.md +0 -176
@@ -0,0 +1,580 @@
1
+ import type {
2
+ ExportNamedDeclaration,
3
+ VariableDeclarator
4
+ } from '@typescript-eslint/types/dist/generated/ast-spec'
5
+ import { parse } from '@typescript-eslint/typescript-estree'
6
+ import type { BunPlugin } from 'bun'
7
+ import tailwind from 'bun-plugin-tailwind'
8
+ import { realpathSync } from 'node:fs'
9
+ import { basename, dirname, join, relative, sep } from 'path'
10
+
11
+ import type { ViewConfig, WidgetConfig } from '@/lib/types'
12
+
13
+ // An **applet** is any custom UI unit embedded in a workspace; `widget` and
14
+ // `view` are its kinds (more may follow). All compile through this pipeline —
15
+ // `kind` only diverges at the edges: which `config` schema is parsed, the
16
+ // synthetic-CSS filename, and the injected `<style>` id namespace.
17
+ export type AppletKind = 'widget' | 'view'
18
+
19
+ // Baked into the bundle wherever a runtime URL needs the workspace's API base
20
+ // (RPC + workspace files). The serve route string-replaces it with the real
21
+ // `/api/workspaces/<id>` in every `.js` it returns, so the on-disk bundle stays
22
+ // workspace-agnostic. Survives the build because we never minify — it lives as
23
+ // a plain string literal. Assets don't use it: they self-locate via
24
+ // `import.meta.url` (see the asset loader below).
25
+ export const APPLET_API_BASE_SENTINEL = '%%MOI_APPLET_API_BASE%%'
26
+
27
+ // Extensions an applet may `import` as a bundled asset. Each is emitted as a
28
+ // content-hashed sibling of `index.js` and the import resolves to its URL via
29
+ // `import.meta.url`. Deliberately images + fonts only: large media (video/audio)
30
+ // belongs in the workspace and should stream via `fileUrl()`, not bloat the
31
+ // bundle dir.
32
+ const ASSET_EXTENSIONS = /\.(png|jpe?g|gif|svg|webp|avif|ico|woff2?|ttf|otf)$/i
33
+
34
+ const EXTERNAL_MODULES = [
35
+ 'react',
36
+ 'react/jsx-runtime',
37
+ 'react/jsx-dev-runtime',
38
+ 'react-dom',
39
+ 'react-dom/client'
40
+ ]
41
+
42
+ type ServerModule = {
43
+ name: string
44
+ exports: string[]
45
+ }
46
+
47
+ // One emitted file in an applet's served directory. `code` files (entry +
48
+ // chunks) are sentinel-swapped and served as JS; `asset` files (images/fonts)
49
+ // stream raw.
50
+ export type AppletFile = {
51
+ name: string
52
+ data: string | Uint8Array
53
+ kind: 'code' | 'asset'
54
+ }
55
+
56
+ export type AppletArtifact = {
57
+ // The entry (`index.js`) source, post CSS-injection — a convenience alias for
58
+ // the `code` file named `index.js` in `files`.
59
+ js: string
60
+ // Everything to write into `.build/<kind>/<name>/`: the entry, any code
61
+ // chunks, and bundled assets.
62
+ files: AppletFile[]
63
+ serverModules: ServerModule[]
64
+ config: WidgetConfig | ViewConfig | null
65
+ }
66
+
67
+ const DEFAULT_CONFIG: WidgetConfig = { rowSpan: 1, colSpan: 2 }
68
+ const VALID_SPANS = [1, 2, 3, 4] as const
69
+
70
+ // The properties of an exported `const config = { … }` object literal, or null
71
+ // when the file declares no such export. Shared by the widget and view config
72
+ // extractors — they each interpret the properties under their own schema.
73
+ function findConfigProperties(source: string) {
74
+ const ast = parse(source, { jsx: true, errorOnUnknownASTType: false })
75
+
76
+ const exportDecl = ast.body.find(
77
+ node =>
78
+ node.type === 'ExportNamedDeclaration' &&
79
+ node.declaration?.type === 'VariableDeclaration' &&
80
+ node.declaration.declarations.some(d => d.id.type === 'Identifier' && d.id.name === 'config')
81
+ ) as ExportNamedDeclaration | undefined
82
+ if (!exportDecl) return null
83
+
84
+ const varDecl = exportDecl.declaration
85
+ if (varDecl?.type !== 'VariableDeclaration') return null
86
+
87
+ const decl = varDecl.declarations.find(
88
+ (d): d is VariableDeclarator & { id: { type: 'Identifier'; name: string } } =>
89
+ d.id.type === 'Identifier' && d.id.name === 'config'
90
+ )
91
+ const rawInit = decl?.init
92
+ // Unwrap `as const` — AST wraps the object in TSAsExpression
93
+ const init = rawInit?.type === 'TSAsExpression' ? rawInit.expression : rawInit
94
+ if (init?.type !== 'ObjectExpression') return null
95
+
96
+ return init.properties
97
+ }
98
+
99
+ // `requiredEnv`: an array of string literals naming env vars the bundle needs.
100
+ // Advisory only — surfaced in the env UI, never enforced at build/load.
101
+ function readRequiredEnv(propValue: unknown): string[] | undefined {
102
+ const value = propValue as { type?: string; elements?: unknown[] }
103
+ if (value?.type !== 'ArrayExpression') return undefined
104
+ const names = (value.elements ?? [])
105
+ .filter(
106
+ (el): el is { type: 'Literal'; value: string } =>
107
+ (el as { type?: string })?.type === 'Literal' &&
108
+ typeof (el as { value?: unknown }).value === 'string'
109
+ )
110
+ .map(el => el.value)
111
+ return names.length ? names : undefined
112
+ }
113
+
114
+ export async function extractWidgetConfig(srcPath: string): Promise<WidgetConfig | null> {
115
+ const source = await Bun.file(srcPath).text()
116
+ const widgetName = basename(srcPath).replace(/\.tsx?$/, '')
117
+
118
+ const properties = findConfigProperties(source)
119
+ if (!properties) return null
120
+
121
+ const result: Partial<WidgetConfig> = {}
122
+
123
+ for (const prop of properties) {
124
+ if (prop.type !== 'Property' || prop.key?.type !== 'Identifier') continue
125
+ const key = prop.key.name as string
126
+
127
+ if (key === 'requiredEnv') {
128
+ const names = readRequiredEnv(prop.value)
129
+ if (names) result.requiredEnv = names
130
+ continue
131
+ }
132
+
133
+ if (key !== 'rowSpan' && key !== 'colSpan') continue
134
+ if (prop.value?.type !== 'Literal' || typeof prop.value.value !== 'number') continue
135
+
136
+ const val = prop.value.value
137
+ if (!(VALID_SPANS as readonly number[]).includes(val)) {
138
+ console.warn(`[mei] "${widgetName}": config.${key}=${val} is out of 1–4 range, using default`)
139
+ continue
140
+ }
141
+ result[key] = val as 1 | 2 | 3 | 4
142
+ }
143
+
144
+ return { ...DEFAULT_CONFIG, ...result }
145
+ }
146
+
147
+ // A view's config: just `title` (string) + advisory `requiredEnv`. No sizing —
148
+ // views are full-screen. Returns null when no `config` export is present.
149
+ export async function extractViewConfig(srcPath: string): Promise<ViewConfig | null> {
150
+ const source = await Bun.file(srcPath).text()
151
+
152
+ const properties = findConfigProperties(source)
153
+ if (!properties) return null
154
+
155
+ const result: ViewConfig = {}
156
+
157
+ for (const prop of properties) {
158
+ if (prop.type !== 'Property' || prop.key?.type !== 'Identifier') continue
159
+ const key = prop.key.name as string
160
+
161
+ if (key === 'title') {
162
+ if (prop.value?.type === 'Literal' && typeof prop.value.value === 'string') {
163
+ result.title = prop.value.value
164
+ }
165
+ continue
166
+ }
167
+ if (key === 'requiredEnv') {
168
+ const names = readRequiredEnv(prop.value)
169
+ if (names) result.requiredEnv = names
170
+ }
171
+ }
172
+
173
+ return result
174
+ }
175
+
176
+ function escapeRegex(s: string): string {
177
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
178
+ }
179
+
180
+ async function validateServerExports(filePath: string): Promise<string[]> {
181
+ const source = await Bun.file(filePath).text()
182
+ const transpiler = new Bun.Transpiler({ loader: 'ts' })
183
+ const { exports } = transpiler.scan(source)
184
+
185
+ const runtimeExports = exports.filter(name => {
186
+ const escaped = escapeRegex(name)
187
+ const typePattern = new RegExp(`export\\s+(type|interface)\\s+${escaped}\\b`)
188
+ return !typePattern.test(source)
189
+ })
190
+
191
+ for (const name of runtimeExports) {
192
+ const escaped = escapeRegex(name)
193
+ const asyncFnPattern = new RegExp(
194
+ `export\\s+async\\s+function\\*?\\s+${escaped}\\b` +
195
+ '|' +
196
+ `export\\s+const\\s+${escaped}\\s*=\\s*async\\s*[\\(]`
197
+ )
198
+ if (!asyncFnPattern.test(source)) {
199
+ throw new Error(
200
+ `"${name}" in ${basename(filePath)} is not an async function. ` +
201
+ `.server.ts files can only export async functions.`
202
+ )
203
+ }
204
+ }
205
+
206
+ return runtimeExports
207
+ }
208
+
209
+ // The mei:rpc virtual module — contains the RPC call logic with devalue
210
+ // serialization. Bundled into the applet output once, shared by all server
211
+ // function stubs. The base is the sentinel the serve route rewrites to
212
+ // `/api/workspaces/<id>`, so a bundle carries no workspace id of its own.
213
+ const RPC_MODULE_SOURCE = `
214
+ import { stringify, parse } from "devalue";
215
+
216
+ const BASE = ${JSON.stringify(APPLET_API_BASE_SENTINEL)};
217
+
218
+ export function rpc(module, name) {
219
+ return async (...args) => {
220
+ const res = await fetch(BASE + "/rpc/" + module + "/" + name, {
221
+ method: "POST",
222
+ headers: { "Content-Type": "application/json" },
223
+ body: stringify(args),
224
+ });
225
+ if (!res.ok) throw new Error(await res.text());
226
+ return parse(await res.text());
227
+ };
228
+ }
229
+ `
230
+
231
+ // The `moi` virtual module — the applet-facing runtime API. Today just
232
+ // `fileUrl(path)`, which maps a workspace-relative path to its streaming URL
233
+ // (`/api/workspaces/<id>/fs/<path>`). Same sentinel base as RPC; the path is
234
+ // per-segment URL-encoded so spaces / unicode in filenames survive. A leading
235
+ // slash is stripped so both `clips/a.mp4` and `/clips/a.mp4` work.
236
+ const MOI_MODULE_SOURCE = `
237
+ const BASE = ${JSON.stringify(APPLET_API_BASE_SENTINEL)};
238
+
239
+ export function fileUrl(path) {
240
+ const clean = String(path).replace(/^\\/+/, "");
241
+ return BASE + "/fs/" + clean.split("/").map(encodeURIComponent).join("/");
242
+ }
243
+ `
244
+
245
+ // Server modules are keyed by their path relative to the moi root
246
+ // (`.moi/widgets/hello.server.ts` → `"widgets/hello"`), posix-normalized so
247
+ // keys are stable across platforms. Throws when the file escapes the root.
248
+ // Both sides are canonicalized first: Bun's resolver returns realpaths
249
+ // (e.g. `/tmp` → `/private/tmp` on macOS), and a symlinked root must not
250
+ // look like an escape.
251
+ function realpathOr(path: string): string {
252
+ try {
253
+ return realpathSync(path)
254
+ } catch {
255
+ return path
256
+ }
257
+ }
258
+
259
+ function serverModuleKey(serverPath: string, moiRoot: string): string {
260
+ const key = relative(realpathOr(moiRoot), realpathOr(serverPath))
261
+ .replace(/\.server\.ts$/, '')
262
+ .split(sep)
263
+ .join('/')
264
+ if (key === '..' || key.startsWith('../')) {
265
+ throw new Error(`Server file "${serverPath}" escapes the moi root "${moiRoot}"`)
266
+ }
267
+ return key
268
+ }
269
+
270
+ // The applet runtime plugin wires the three I/O transports into the bundle:
271
+ // • `.server` imports → RPC stubs (via the `mei:rpc` virtual module)
272
+ // • `moi` import → the `fileUrl` runtime
273
+ // • asset imports → content-hashed sibling files, referenced by URL
274
+ // It returns the collected server modules (for hot-reload + env aggregation)
275
+ // and the asset files the caller must emit next to `index.js`.
276
+ function appletRuntimePlugin(
277
+ sourceDir: string,
278
+ moiRoot: string
279
+ ): {
280
+ plugin: BunPlugin
281
+ serverModules: ServerModule[]
282
+ assets: AppletFile[]
283
+ } {
284
+ const serverModules: ServerModule[] = []
285
+ const assets: AppletFile[] = []
286
+
287
+ const plugin: BunPlugin = {
288
+ name: 'applet-runtime',
289
+ setup(build) {
290
+ // Resolve mei:rpc virtual module
291
+ build.onResolve({ filter: /^mei:rpc$/ }, () => ({
292
+ path: 'mei:rpc',
293
+ namespace: 'mei-rpc'
294
+ }))
295
+
296
+ build.onLoad({ filter: /.*/, namespace: 'mei-rpc' }, () => ({
297
+ contents: RPC_MODULE_SOURCE,
298
+ loader: 'js'
299
+ }))
300
+
301
+ // The `moi` runtime module (fileUrl). A bare specifier, so match it exactly.
302
+ build.onResolve({ filter: /^moi$/ }, () => ({ path: 'moi', namespace: 'moi-runtime' }))
303
+ build.onLoad({ filter: /.*/, namespace: 'moi-runtime' }, () => ({
304
+ contents: MOI_MODULE_SOURCE,
305
+ loader: 'js'
306
+ }))
307
+
308
+ // Asset imports (images/fonts): emit a content-hashed sibling and resolve
309
+ // the import to its module-relative URL. Self-locating via import.meta.url,
310
+ // so it needs no API base — the asset sits next to the served entry.
311
+ build.onLoad({ filter: ASSET_EXTENSIONS }, async args => {
312
+ const bytes = new Uint8Array(await Bun.file(args.path).arrayBuffer())
313
+ const hash = Bun.hash(bytes).toString(16).slice(0, 8)
314
+ const dot = args.path.lastIndexOf('.')
315
+ const ext = args.path.slice(dot + 1).toLowerCase()
316
+ const stem = basename(args.path.slice(0, dot)).replace(/[^a-zA-Z0-9_-]/g, '-')
317
+ const name = `${stem}-${hash}.${ext}`
318
+ if (!assets.some(a => a.name === name)) assets.push({ name, data: bytes, kind: 'asset' })
319
+ return {
320
+ contents: `export default new URL(${JSON.stringify('./' + name)}, import.meta.url).href`,
321
+ loader: 'js'
322
+ }
323
+ })
324
+
325
+ // Intercept .server imports (relative only). Resolved against the
326
+ // importing file's directory — server files may live anywhere under
327
+ // the moi root, e.g. `../lib/db.server`.
328
+ build.onResolve({ filter: /\.server(\.ts)?$/ }, args => {
329
+ if (!args.path.startsWith('.')) return
330
+ const baseDir =
331
+ args.importer && args.importer.includes(sep) ? dirname(args.importer) : sourceDir
332
+ return {
333
+ path: join(baseDir, args.path.replace(/\.server(\.ts)?$/, '.server.ts')),
334
+ namespace: 'server-proxy'
335
+ }
336
+ })
337
+
338
+ // Generate proxy stubs using mei:rpc
339
+ build.onLoad({ filter: /.*/, namespace: 'server-proxy' }, async args => {
340
+ const exports = await validateServerExports(args.path)
341
+ const moduleName = serverModuleKey(args.path, moiRoot)
342
+
343
+ serverModules.push({ name: moduleName, exports })
344
+
345
+ const lines = [
346
+ `import { rpc } from "mei:rpc";`,
347
+ ...exports.map(
348
+ name =>
349
+ `export const ${name} = rpc(${JSON.stringify(moduleName)}, ${JSON.stringify(name)});`
350
+ )
351
+ ]
352
+
353
+ return { contents: lines.join('\n'), loader: 'js' }
354
+ })
355
+ }
356
+ }
357
+
358
+ return { plugin, serverModules, assets }
359
+ }
360
+
361
+ // Path to the host's `@theme inline` block — shared with `client/index.css`.
362
+ // Inlined into the widget's synthetic CSS at build time so Tailwind sees the
363
+ // theme tokens.
364
+ const HOST_THEME_PATH = join(import.meta.dir, '..', 'client', 'theme.css')
365
+
366
+ // Three things matter for widget styling:
367
+ // 1. The umbrella `@import 'tailwindcss'` brings in @layer theme + base +
368
+ // utilities — which is what spacing/color utilities like `left-2.5`,
369
+ // `gap-1.5`, `text-amber-500` need to resolve. The split
370
+ // `theme`/`utilities` imports skip the `@layer theme` wrapper and theme
371
+ // variables aren't in scope at compile time.
372
+ // 2. The host's `@theme inline` block (inlined from theme.css) teaches
373
+ // Tailwind about host-owned tokens (`--color-background`,
374
+ // `--color-foreground`, etc.) so widgets compile classes like
375
+ // `bg-foreground/20`, `text-muted`, `rounded-xl`. The `inline` keyword
376
+ // means the widget's CSS does NOT redefine the underlying
377
+ // `--background`/`--foreground` variables — those stay host-owned and
378
+ // the widget picks them up from `:root` at runtime.
379
+ // 3. Tailwind's auto-detection treats `.moi/` as a hidden directory
380
+ // and skips it. An explicit `@source` bypasses the dot-dir + gitignore
381
+ // filters.
382
+ //
383
+ // Important: the synthetic CSS must live on disk in the `file` namespace
384
+ // because `bun-plugin-tailwind`'s `onLoad` only matches that namespace —
385
+ // custom-namespace CSS is treated as raw text and our `@theme inline` block
386
+ // is left unprocessed. We materialize it inside `<moiRoot>/.build/` and
387
+ // have the entry import it by absolute path.
388
+ async function writeSyntheticTailwindCss(
389
+ widgetPath: string,
390
+ moiRoot: string,
391
+ kind: AppletKind
392
+ ): Promise<string> {
393
+ const sourceDir = dirname(widgetPath)
394
+ const buildDir = join(moiRoot, '.build')
395
+ // Per-kind filename: widgets (`@source .moi/widgets`) and views
396
+ // (`@source .moi/views`) build concurrently in one `moi bundle`; a shared
397
+ // file would race and point Tailwind at the wrong source dir.
398
+ const cssPath = join(buildDir, `${kind}-tailwind.css`)
399
+ const contents = [
400
+ `@import 'tailwindcss';`,
401
+ await Bun.file(HOST_THEME_PATH).text(),
402
+ `@source "${sourceDir}";`
403
+ ].join('\n')
404
+ await Bun.write(cssPath, contents)
405
+ return cssPath
406
+ }
407
+
408
+ function widgetEntryPlugin(widgetPath: string, syntheticCssPath: string): BunPlugin {
409
+ return {
410
+ name: 'widget-entry',
411
+ setup(build) {
412
+ build.onResolve({ filter: /^__widget-entry$/ }, () => ({
413
+ path: '__widget-entry',
414
+ namespace: 'widget-entry'
415
+ }))
416
+
417
+ build.onLoad({ filter: /.*/, namespace: 'widget-entry' }, () => ({
418
+ contents: [
419
+ `import ${JSON.stringify(syntheticCssPath)};`,
420
+ `export { default } from ${JSON.stringify(widgetPath)};`
421
+ ].join('\n'),
422
+ loader: 'js'
423
+ }))
424
+ }
425
+ }
426
+ }
427
+
428
+ function injectCss(js: string, css: string, widgetName: string): string {
429
+ if (!css.trim()) return js
430
+
431
+ // After `moi bundle` rebuilds the widget, the new JS module re-runs in the
432
+ // browser. Always replace any prior <style data-widget="<id>"> tag so the
433
+ // freshly-built CSS takes effect; the previous "skip if already present"
434
+ // guard left stale rules in place after edits.
435
+ const injection = [
436
+ `((css, id) => {`,
437
+ ` document.querySelector(\`style[data-widget="\${id}"]\`)?.remove();`,
438
+ ` const s = document.createElement("style");`,
439
+ ` s.dataset.widget = id;`,
440
+ ` s.textContent = css;`,
441
+ ` document.head.appendChild(s);`,
442
+ `})(${JSON.stringify(css)}, ${JSON.stringify(widgetName)});`
443
+ ].join('\n')
444
+
445
+ return injection + '\n' + js
446
+ }
447
+
448
+ function formatBuildLog(log: BuildMessage | ResolveMessage): string {
449
+ const prefix = log.level === 'error' ? 'error' : log.level
450
+ const loc = log.position
451
+ ? `${log.position.file}:${log.position.line}:${log.position.column}: `
452
+ : ''
453
+ const lineText = log.position?.lineText ? `\n ${log.position.lineText.trim()}` : ''
454
+ return `${loc}${prefix}: ${log.message}${lineText}`
455
+ }
456
+
457
+ // Relative `.server` import specifiers in a widget source, `.server` suffix
458
+ // stripped: `./hello`, `../lib/db`. Shared by prevalidation here and the
459
+ // rebuild staleness check in widgets.ts.
460
+ export function scanServerImports(source: string): string[] {
461
+ const importPattern = /from\s+['"](\.\.?\/[^'"]+?)\.server(?:\.ts)?['"]/g
462
+ const specifiers: string[] = []
463
+ let match
464
+ while ((match = importPattern.exec(source)) !== null) {
465
+ specifiers.push(match[1])
466
+ }
467
+ return specifiers
468
+ }
469
+
470
+ // Relative asset import specifiers in an applet source (`./logo.png`,
471
+ // `../shared/icon.svg`). Used by the rebuild staleness check so editing an
472
+ // imported image rebuilds the bundle even when the `.tsx` itself is untouched.
473
+ const ASSET_IMPORT_RE =
474
+ /from\s+['"](\.\.?\/[^'"]+?\.(?:png|jpe?g|gif|svg|webp|avif|ico|woff2?|ttf|otf))['"]/gi
475
+ export function scanAssetImports(source: string): string[] {
476
+ const specifiers: string[] = []
477
+ let match
478
+ while ((match = ASSET_IMPORT_RE.exec(source)) !== null) {
479
+ specifiers.push(match[1])
480
+ }
481
+ return specifiers
482
+ }
483
+
484
+ async function prevalidateServerFiles(entrypoint: string): Promise<void> {
485
+ const sourceDir = dirname(entrypoint)
486
+ const source = await Bun.file(entrypoint).text()
487
+
488
+ for (const specifier of scanServerImports(source)) {
489
+ const serverPath = join(sourceDir, `${specifier}.server.ts`)
490
+ if (await Bun.file(serverPath).exists()) {
491
+ await validateServerExports(serverPath)
492
+ }
493
+ }
494
+ }
495
+
496
+ // `moiRoot` is the directory server-module keys are relative to (the
497
+ // workspace's `.moi/`). Defaults to the entrypoint's own directory, which keeps
498
+ // basename keys for callers that build a file directly (tests, fixtures).
499
+ // `kind` selects the config schema, synthetic-CSS filename, and `<style>` id
500
+ // namespace; it defaults to 'widget' so existing callers are unaffected.
501
+ export async function buildApplet(
502
+ entrypoint: string,
503
+ moiRoot = dirname(entrypoint),
504
+ kind: AppletKind = 'widget'
505
+ ): Promise<AppletArtifact> {
506
+ const sourceDir = dirname(entrypoint)
507
+ const widgetName = basename(entrypoint).replace(/\.tsx?$/, '')
508
+
509
+ await prevalidateServerFiles(entrypoint)
510
+
511
+ const { plugin: runtime, serverModules, assets } = appletRuntimePlugin(sourceDir, moiRoot)
512
+ const syntheticCssPath = await writeSyntheticTailwindCss(entrypoint, moiRoot, kind)
513
+
514
+ let result: Awaited<ReturnType<typeof Bun.build>>
515
+ try {
516
+ result = await Bun.build({
517
+ entrypoints: ['__widget-entry'],
518
+ format: 'esm',
519
+ target: 'browser',
520
+ sourcemap: 'inline',
521
+ external: EXTERNAL_MODULES,
522
+ // The bundle is a directory: a fixed `index.js` entry (the client
523
+ // dynamic-imports it) plus content-hashed `chunk-*.js` for any dynamic
524
+ // imports. Assets are emitted by the runtime plugin, not here. `[ext]` is
525
+ // required — bun emits the entry's CSS sibling as an "entry" output too, so
526
+ // a literal `index.js` would collide with the `.css`; we inject that CSS
527
+ // into the JS and drop the file, keeping a clean `index.js`.
528
+ naming: { entry: 'index.[ext]', chunk: 'chunk-[hash].[ext]' },
529
+ // bun-plugin-tailwind uses `build.config.root` as the auto-detect
530
+ // project root (`projectRoot = build.config?.root ?? process.cwd()`).
531
+ // Without this, oxide scans `none-computer/` (the parent server's
532
+ // cwd) instead of the workspace's `.moi/widgets/`.
533
+ root: sourceDir,
534
+ plugins: [widgetEntryPlugin(entrypoint, syntheticCssPath), runtime, tailwind]
535
+ })
536
+ } catch (err) {
537
+ // Bun.build throws AggregateError on failure (default throw: true).
538
+ // The message is a generic "Bundle failed"; the real diagnostics live on `.errors`.
539
+ const logs = (err as { errors?: (BuildMessage | ResolveMessage)[] }).errors ?? []
540
+ const formatted = logs.length
541
+ ? logs.map(formatBuildLog).join('\n')
542
+ : err instanceof Error
543
+ ? err.message
544
+ : String(err)
545
+ throw new Error(`Build failed for "${widgetName}":\n${formatted}`)
546
+ }
547
+
548
+ if (!result.success) {
549
+ const errors = result.logs.map(formatBuildLog).join('\n')
550
+ throw new Error(`Build failed for "${widgetName}":\n${errors}`)
551
+ }
552
+
553
+ const entryOutput = result.outputs.find(o => o.kind === 'entry-point')
554
+ const chunkOutputs = result.outputs.filter(o => o.kind === 'chunk')
555
+ const cssOutput = result.outputs.find(o => o.kind === 'asset' && o.path.endsWith('.css'))
556
+
557
+ if (!entryOutput) {
558
+ throw new Error(`Build produced no JS output for "${widgetName}"`)
559
+ }
560
+
561
+ let js = await entryOutput.text()
562
+
563
+ if (cssOutput) {
564
+ const css = await cssOutput.text()
565
+ // Namespace the injected <style> id by kind so a widget and a view sharing
566
+ // a name don't overwrite each other's rules.
567
+ const styleId = kind === 'widget' ? widgetName : `${kind}:${widgetName}`
568
+ js = injectCss(js, css, styleId)
569
+ }
570
+
571
+ const files: AppletFile[] = [{ name: 'index.js', data: js, kind: 'code' }]
572
+ for (const chunk of chunkOutputs) {
573
+ files.push({ name: basename(chunk.path), data: await chunk.text(), kind: 'code' })
574
+ }
575
+ files.push(...assets)
576
+
577
+ const config =
578
+ kind === 'view' ? await extractViewConfig(entrypoint) : await extractWidgetConfig(entrypoint)
579
+ return { js, files, serverModules, config }
580
+ }