moi-computer 0.0.2 → 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 (246) hide show
  1. package/bin/moi.mjs +3 -1
  2. package/bunfig.toml +4 -0
  3. package/client/api/workspaces.ts +277 -6
  4. package/client/assets/mcp/agentation.png +0 -0
  5. package/client/assets/mcp/airtable.png +0 -0
  6. package/client/assets/mcp/apollo.png +0 -0
  7. package/client/assets/mcp/asana.png +0 -0
  8. package/client/assets/mcp/box.png +0 -0
  9. package/client/assets/mcp/chrome.svg +33 -0
  10. package/client/assets/mcp/clickup.png +0 -0
  11. package/client/assets/mcp/cloudflare.png +0 -0
  12. package/client/assets/mcp/context7.png +0 -0
  13. package/client/assets/mcp/datadog.png +0 -0
  14. package/client/assets/mcp/dropbox.png +0 -0
  15. package/client/assets/mcp/elevenlabs.png +0 -0
  16. package/client/assets/mcp/exa.png +0 -0
  17. package/client/assets/mcp/firecrawl.png +0 -0
  18. package/client/assets/mcp/gmail.png +0 -0
  19. package/client/assets/mcp/googlecalendar.png +0 -0
  20. package/client/assets/mcp/googledrive.png +0 -0
  21. package/client/assets/mcp/grafana.png +0 -0
  22. package/client/assets/mcp/huggingface.png +0 -0
  23. package/client/assets/mcp/intercom.png +0 -0
  24. package/client/assets/mcp/monday.png +0 -0
  25. package/client/assets/mcp/mongodb.png +0 -0
  26. package/client/assets/mcp/paper.png +0 -0
  27. package/client/assets/mcp/paypal.png +0 -0
  28. package/client/assets/mcp/perplexity.png +0 -0
  29. package/client/assets/mcp/postgresql.png +0 -0
  30. package/client/assets/mcp/posthog.png +0 -0
  31. package/client/assets/mcp/puppeteer.png +0 -0
  32. package/client/assets/mcp/railway.png +0 -0
  33. package/client/assets/mcp/redis.png +0 -0
  34. package/client/assets/mcp/salesforce.png +0 -0
  35. package/client/assets/mcp/shopify.png +0 -0
  36. package/client/assets/mcp/snowflake.png +0 -0
  37. package/client/assets/mcp/telegram.png +0 -0
  38. package/client/assets/mcp/twilio.png +0 -0
  39. package/client/assets/mcp/zapier.png +0 -0
  40. package/client/components/App.tsx +7 -1
  41. package/client/components/BottomPanel.tsx +2 -2
  42. package/client/components/ChatInput.tsx +195 -14
  43. package/client/components/ChatPanel.tsx +118 -49
  44. package/client/components/ChatPopup.tsx +2 -2
  45. package/client/components/CustomizePanel.tsx +8 -8
  46. package/client/components/HiddenPanel.tsx +1 -1
  47. package/client/components/HomePage.tsx +1 -1
  48. package/client/components/IconMcp.tsx +21 -0
  49. package/client/components/MarkdownContent.tsx +2 -2
  50. package/client/components/McpMenu.tsx +125 -0
  51. package/client/components/ModelPicker.tsx +147 -0
  52. package/client/components/Scratchpad.tsx +775 -0
  53. package/client/components/ShimmerText.tsx +20 -0
  54. package/client/components/ThreadSelector.tsx +2 -2
  55. package/client/components/TurnView.tsx +114 -534
  56. package/client/components/WidgetErrorBoundary.tsx +2 -2
  57. package/client/components/WidgetFrame.tsx +1 -1
  58. package/client/components/WidgetShell.tsx +2 -2
  59. package/client/components/Widgets.tsx +2 -2
  60. package/client/components/WorkspacePreview.tsx +3 -3
  61. package/client/components/WorkspacesPage.tsx +28 -20
  62. package/client/components/layout/SidebarLayout.tsx +24 -15
  63. package/client/components/playground/PixelPainter.tsx +2 -2
  64. package/client/components/playground/PlaygroundPage.tsx +1 -1
  65. package/client/components/playground/ToolCallsPage.tsx +81 -0
  66. package/client/components/routes/workspace/[id].tsx +534 -141
  67. package/client/components/routes/workspace/create.tsx +155 -0
  68. package/client/components/settings/IconPicker.tsx +590 -0
  69. package/client/components/settings/SettingsPages.tsx +307 -0
  70. package/client/components/settings/WorkspaceSettings.tsx +92 -0
  71. package/client/components/tool-group/CodeBlock.tsx +41 -0
  72. package/client/components/tool-group/Collapse.tsx +28 -0
  73. package/client/components/tool-group/ReadImagePreview.tsx +46 -0
  74. package/client/components/tool-group/SubagentCard.tsx +135 -0
  75. package/client/components/tool-group/TimelineRow.tsx +147 -0
  76. package/client/components/tool-group/ToolCallGroup.tsx +231 -0
  77. package/client/components/tool-group/ToolOutput.tsx +139 -0
  78. package/client/components/tool-group/detect.ts +93 -0
  79. package/client/components/tool-group/fixtures.ts +315 -0
  80. package/client/components/tool-group/format.ts +211 -0
  81. package/client/components/tool-group/index.ts +9 -0
  82. package/client/components/ui/button.tsx +4 -4
  83. package/client/components/ui/dialog.tsx +58 -0
  84. package/client/components/ui/dropdown-menu.tsx +9 -9
  85. package/client/components/ui/hover-card.tsx +44 -0
  86. package/client/components/ui/popover.tsx +1 -1
  87. package/client/components/ui/switch.tsx +23 -0
  88. package/client/components/ui/tooltip.tsx +54 -0
  89. package/client/externalize-react.ts +11 -5
  90. package/client/hooks/useApplet.ts +117 -0
  91. package/client/hooks/useChat.ts +162 -62
  92. package/client/hooks/useMeiEvents.ts +9 -2
  93. package/client/hooks/useStickToBottom.ts +86 -0
  94. package/client/hooks/useWorkspaceTheme.ts +8 -2
  95. package/client/index.css +49 -3
  96. package/client/index.html +22 -18
  97. package/client/index.tsx +29 -2
  98. package/client/lib/WorkspaceContext.tsx +5 -8
  99. package/client/lib/WorkspaceLayoutContext.tsx +30 -10
  100. package/client/lib/applet-cache.ts +54 -0
  101. package/client/lib/connection.ts +237 -0
  102. package/client/lib/flags.ts +10 -0
  103. package/client/lib/mcp-icons.ts +142 -10
  104. package/client/lib/preview-turn.ts +37 -0
  105. package/client/lib/render-icon.ts +173 -0
  106. package/client/lib/scratch-executor.ts +20 -0
  107. package/client/lib/uploads.ts +18 -0
  108. package/client/main.tsx +5 -0
  109. package/client/store/live.ts +282 -0
  110. package/client/structured-clone-shim.ts +14 -0
  111. package/client/theme.css +2 -2
  112. package/client/vendor/emojibase/en/data.json +1 -0
  113. package/client/vendor/emojibase/en/messages.json +1 -0
  114. package/client/vendor/react/development/_impl/react-dom-client.js +15871 -0
  115. package/client/vendor/react/development/_impl/react-dom.js +223 -0
  116. package/client/vendor/react/development/_impl/react-jsx-dev-runtime.js +256 -0
  117. package/client/vendor/react/development/_impl/react-jsx-runtime.js +260 -0
  118. package/client/vendor/react/development/_impl/react.js +863 -0
  119. package/client/vendor/react/development/react-dom-client.js +6 -0
  120. package/client/vendor/react/development/react-dom.js +17 -0
  121. package/client/vendor/react/development/react-jsx-dev-runtime.js +5 -0
  122. package/client/vendor/react/development/react-jsx-runtime.js +6 -0
  123. package/client/vendor/react/development/react.js +47 -0
  124. package/client/vendor/react/production/_impl/react-dom-client.js +10361 -0
  125. package/client/vendor/react/production/_impl/react-dom.js +184 -0
  126. package/client/vendor/react/production/_impl/react-jsx-dev-runtime.js +37 -0
  127. package/client/vendor/react/production/_impl/react-jsx-runtime.js +60 -0
  128. package/client/vendor/react/production/_impl/react.js +428 -0
  129. package/client/vendor/react/production/react-dom-client.js +6 -0
  130. package/client/vendor/react/production/react-dom.js +17 -0
  131. package/client/vendor/react/production/react-jsx-dev-runtime.js +5 -0
  132. package/client/vendor/react/production/react-jsx-runtime.js +6 -0
  133. package/client/vendor/react/production/react.js +47 -0
  134. package/dist/agentation-4s0nn45p.png +0 -0
  135. package/dist/airtable-hsa66v6q.png +0 -0
  136. package/dist/apollo-2ed5dy2d.png +0 -0
  137. package/dist/asana-tvgtwbx2.png +0 -0
  138. package/dist/atlassian-b3tq39hs.png +0 -0
  139. package/dist/box-w3n36t5g.png +0 -0
  140. package/dist/chrome-tspm94rw.svg +33 -0
  141. package/dist/chunk-kc6e9nd4.css +1 -0
  142. package/dist/chunk-yf3p7qg7.js +673 -0
  143. package/dist/claude-z2xnay0d.svg +3 -0
  144. package/dist/clickup-qqrqqvqb.png +0 -0
  145. package/dist/cloudflare-j9p931v6.png +0 -0
  146. package/dist/context7-8ht0xjfy.png +0 -0
  147. package/dist/datadog-70ne3yzt.png +0 -0
  148. package/dist/discord-vejhptwx.png +0 -0
  149. package/dist/dropbox-4m5s9mgr.png +0 -0
  150. package/dist/elevenlabs-2nzzej1t.png +0 -0
  151. package/dist/exa-qqj3vr0x.png +0 -0
  152. package/dist/favicon-nbmyjfjh.png +0 -0
  153. package/dist/figma-y9898rry.png +0 -0
  154. package/dist/firecrawl-w2t8nehx.png +0 -0
  155. package/dist/github-av5r5y3e.png +0 -0
  156. package/dist/gitlab-4pv5vm6b.png +0 -0
  157. package/dist/gmail-sg6a5v3x.png +0 -0
  158. package/dist/googlecalendar-nqhh2v7r.png +0 -0
  159. package/dist/googledrive-6s8xyab7.png +0 -0
  160. package/dist/grafana-1yfsnwr6.png +0 -0
  161. package/dist/granola-7j3b0nk2.png +0 -0
  162. package/dist/hermes-nous-pznd63x9.png +0 -0
  163. package/dist/hubspot-hghcmc2t.png +0 -0
  164. package/dist/huggingface-kxzaxj83.png +0 -0
  165. package/dist/index.html +47 -0
  166. package/dist/intercom-td763jt8.png +0 -0
  167. package/dist/linear-v9s3az2d.png +0 -0
  168. package/dist/monday-jdbs4wwf.png +0 -0
  169. package/dist/mongodb-emzxvhd5.png +0 -0
  170. package/dist/neon-zj4qar44.png +0 -0
  171. package/dist/notion-w034c0b8.png +0 -0
  172. package/dist/openclaw-a2pyfhpn.svg +22 -0
  173. package/dist/paper-zbt34fab.png +0 -0
  174. package/dist/paypal-kwwf7xsc.png +0 -0
  175. package/dist/perplexity-4y63rxvj.png +0 -0
  176. package/dist/postgresql-qsspbsr1.png +0 -0
  177. package/dist/posthog-sphppc4w.png +0 -0
  178. package/dist/puppeteer-2xjt1a9b.png +0 -0
  179. package/dist/railway-834de8d2.png +0 -0
  180. package/dist/redis-spm6w2m1.png +0 -0
  181. package/dist/salesforce-1mk56v4z.png +0 -0
  182. package/dist/sentry-hdwpmvek.png +0 -0
  183. package/dist/shopify-90dadaav.png +0 -0
  184. package/dist/slack-1c1wj62s.png +0 -0
  185. package/dist/snowflake-hfpykpgy.png +0 -0
  186. package/dist/stripe-zrfaqbj3.png +0 -0
  187. package/dist/supabase-4vg33zf2.png +0 -0
  188. package/dist/telegram-v6tjyrs7.png +0 -0
  189. package/dist/twilio-dpyjdwpj.png +0 -0
  190. package/dist/vercel-7d0ssw28.png +0 -0
  191. package/dist/zapier-p67qfch0.png +0 -0
  192. package/lib/attachment-note.ts +48 -0
  193. package/lib/claude-adapter.ts +219 -29
  194. package/lib/format.ts +32 -0
  195. package/lib/types.ts +314 -6
  196. package/package.json +21 -31
  197. package/server/CLAUDE.md +3 -0
  198. package/server/agent.ts +25 -118
  199. package/server/api.ts +593 -0
  200. package/server/applets.ts +396 -0
  201. package/server/build-applet.ts +580 -0
  202. package/server/cc-session.ts +611 -0
  203. package/server/cli-colors.ts +17 -0
  204. package/server/cli-ui.ts +52 -0
  205. package/server/cli.ts +970 -72
  206. package/server/control.ts +166 -19
  207. package/server/debug.ts +10 -0
  208. package/server/events.ts +24 -0
  209. package/server/functions-worker.ts +18 -2
  210. package/server/functions.ts +59 -12
  211. package/server/icon.ts +13 -0
  212. package/server/layout.ts +25 -3
  213. package/server/mcp.ts +125 -0
  214. package/server/moi-scaffold.ts +85 -0
  215. package/server/openclaw-session.ts +41 -10
  216. package/server/openclaw.ts +22 -0
  217. package/server/preview.ts +70 -0
  218. package/server/registry.ts +32 -2
  219. package/server/scratchpad-executor.ts +380 -0
  220. package/server/scratchpad-relay.ts +45 -0
  221. package/server/scratchpad.ts +171 -0
  222. package/server/skill-version.ts +146 -0
  223. package/server/skills-template.ts +6 -1
  224. package/server/state.ts +22 -36
  225. package/server/static.ts +23 -0
  226. package/server/status.ts +94 -0
  227. package/server/thread-config.ts +125 -0
  228. package/server/uploads.ts +0 -0
  229. package/server/vendor.ts +63 -0
  230. package/server/views.ts +0 -0
  231. package/server/web.ts +113 -223
  232. package/server/widgets.ts +52 -142
  233. package/server/workspace-config.ts +37 -0
  234. package/server/workspace-env.ts +407 -0
  235. package/server/workspace-init.ts +66 -0
  236. package/workspace/.claude/skills/moi-workspace/DESIGN.md +109 -0
  237. package/workspace/.claude/skills/moi-workspace/SCRATCHPAD.md +57 -0
  238. package/workspace/.claude/skills/moi-workspace/SKILL.md +252 -0
  239. package/workspace/.claude/skills/moi-workspace/VIEW-DESIGN.md +22 -0
  240. package/client/hooks/useWidget.ts +0 -72
  241. package/client/hooks/useWidgetList.ts +0 -30
  242. package/client/lib/ws.ts +0 -129
  243. package/client/store/chat.tsx +0 -162
  244. package/server/build-widget.ts +0 -343
  245. package/workspace/.claude/skills/widgets/DESIGN.md +0 -630
  246. package/workspace/.claude/skills/widgets/SKILL.md +0 -176
@@ -1,343 +0,0 @@
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 { basename, dirname, join } from 'path'
9
-
10
- import type { WidgetConfig } from '@/lib/types'
11
-
12
- const EXTERNAL_MODULES = [
13
- 'react',
14
- 'react/jsx-runtime',
15
- 'react/jsx-dev-runtime',
16
- 'react-dom',
17
- 'react-dom/client'
18
- ]
19
-
20
- type ServerModule = {
21
- name: string
22
- exports: string[]
23
- }
24
-
25
- export type WidgetArtifact = {
26
- js: string
27
- serverModules: ServerModule[]
28
- config: WidgetConfig | null
29
- }
30
-
31
- const DEFAULT_CONFIG: WidgetConfig = { rowSpan: 1, colSpan: 2 }
32
- const VALID_SPANS = [1, 2, 3, 4] as const
33
-
34
- export async function extractWidgetConfig(srcPath: string): Promise<WidgetConfig | null> {
35
- const source = await Bun.file(srcPath).text()
36
- const widgetName = basename(srcPath).replace(/\.tsx?$/, '')
37
-
38
- const ast = parse(source, { jsx: true, errorOnUnknownASTType: false })
39
-
40
- const exportDecl = ast.body.find(
41
- node =>
42
- node.type === 'ExportNamedDeclaration' &&
43
- node.declaration?.type === 'VariableDeclaration' &&
44
- node.declaration.declarations.some(d => d.id.type === 'Identifier' && d.id.name === 'config')
45
- ) as ExportNamedDeclaration | undefined
46
- if (!exportDecl) return null
47
-
48
- const varDecl = exportDecl.declaration
49
- if (varDecl?.type !== 'VariableDeclaration') return null
50
-
51
- const decl = varDecl.declarations.find(
52
- (d): d is VariableDeclarator & { id: { type: 'Identifier'; name: string } } =>
53
- d.id.type === 'Identifier' && d.id.name === 'config'
54
- )
55
- const rawInit = decl?.init
56
- // Unwrap `as const` — AST wraps the object in TSAsExpression
57
- const init = rawInit?.type === 'TSAsExpression' ? rawInit.expression : rawInit
58
- if (init?.type !== 'ObjectExpression') return null
59
-
60
- const result: Partial<WidgetConfig> = {}
61
-
62
- for (const prop of init.properties) {
63
- if (prop.type !== 'Property' || prop.key?.type !== 'Identifier') continue
64
- const key = prop.key.name as string
65
- if (key !== 'rowSpan' && key !== 'colSpan') continue
66
- if (prop.value?.type !== 'Literal' || typeof prop.value.value !== 'number') continue
67
-
68
- const val = prop.value.value
69
- if (!(VALID_SPANS as readonly number[]).includes(val)) {
70
- console.warn(`[mei] "${widgetName}": config.${key}=${val} is out of 1–4 range, using default`)
71
- continue
72
- }
73
- result[key] = val as 1 | 2 | 3 | 4
74
- }
75
-
76
- return { ...DEFAULT_CONFIG, ...result }
77
- }
78
-
79
- function escapeRegex(s: string): string {
80
- return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
81
- }
82
-
83
- async function validateServerExports(filePath: string): Promise<string[]> {
84
- const source = await Bun.file(filePath).text()
85
- const transpiler = new Bun.Transpiler({ loader: 'ts' })
86
- const { exports } = transpiler.scan(source)
87
-
88
- const runtimeExports = exports.filter(name => {
89
- const escaped = escapeRegex(name)
90
- const typePattern = new RegExp(`export\\s+(type|interface)\\s+${escaped}\\b`)
91
- return !typePattern.test(source)
92
- })
93
-
94
- for (const name of runtimeExports) {
95
- const escaped = escapeRegex(name)
96
- const asyncFnPattern = new RegExp(
97
- `export\\s+async\\s+function\\*?\\s+${escaped}\\b` +
98
- '|' +
99
- `export\\s+const\\s+${escaped}\\s*=\\s*async\\s*[\\(]`
100
- )
101
- if (!asyncFnPattern.test(source)) {
102
- throw new Error(
103
- `"${name}" in ${basename(filePath)} is not an async function. ` +
104
- `.server.ts files can only export async functions.`
105
- )
106
- }
107
- }
108
-
109
- return runtimeExports
110
- }
111
-
112
- // The mei:rpc virtual module — contains the RPC call logic with devalue serialization.
113
- // Bundled into the widget output once, shared by all server function stubs.
114
- const RPC_MODULE_SOURCE = `
115
- import { stringify, parse } from "devalue";
116
-
117
- export function rpc(module, name) {
118
- return async (...args) => {
119
- const ws = window.__MEI_WS__ || "default";
120
- const res = await fetch("/_rpc/" + ws + "/fn/" + module + "/" + name, {
121
- method: "POST",
122
- headers: { "Content-Type": "application/json" },
123
- body: stringify(args),
124
- });
125
- if (!res.ok) throw new Error(await res.text());
126
- return parse(await res.text());
127
- };
128
- }
129
- `
130
-
131
- function serverProxyPlugin(sourceDir: string): {
132
- plugin: BunPlugin
133
- serverModules: ServerModule[]
134
- } {
135
- const serverModules: ServerModule[] = []
136
-
137
- const plugin: BunPlugin = {
138
- name: 'server-proxy',
139
- setup(build) {
140
- // Resolve mei:rpc virtual module
141
- build.onResolve({ filter: /^mei:rpc$/ }, () => ({
142
- path: 'mei:rpc',
143
- namespace: 'mei-rpc'
144
- }))
145
-
146
- build.onLoad({ filter: /.*/, namespace: 'mei-rpc' }, () => ({
147
- contents: RPC_MODULE_SOURCE,
148
- loader: 'js'
149
- }))
150
-
151
- // Intercept .server imports
152
- build.onResolve({ filter: /\.server(\.ts)?$/ }, args => {
153
- if (!args.path.startsWith('.')) return
154
- return {
155
- path: join(sourceDir, args.path.replace(/\.server(\.ts)?$/, '.server.ts')),
156
- namespace: 'server-proxy'
157
- }
158
- })
159
-
160
- // Generate proxy stubs using mei:rpc
161
- build.onLoad({ filter: /.*/, namespace: 'server-proxy' }, async args => {
162
- const exports = await validateServerExports(args.path)
163
- const moduleName = basename(args.path, '.server.ts')
164
-
165
- serverModules.push({ name: moduleName, exports })
166
-
167
- const lines = [
168
- `import { rpc } from "mei:rpc";`,
169
- ...exports.map(
170
- name =>
171
- `export const ${name} = rpc(${JSON.stringify(moduleName)}, ${JSON.stringify(name)});`
172
- )
173
- ]
174
-
175
- return { contents: lines.join('\n'), loader: 'js' }
176
- })
177
- }
178
- }
179
-
180
- return { plugin, serverModules }
181
- }
182
-
183
- // Path to the host's `@theme inline` block — shared with `client/index.css`.
184
- // Inlined into the widget's synthetic CSS at build time so Tailwind sees the
185
- // theme tokens.
186
- const HOST_THEME_PATH = join(import.meta.dir, '..', 'client', 'theme.css')
187
-
188
- // Three things matter for widget styling:
189
- // 1. The umbrella `@import 'tailwindcss'` brings in @layer theme + base +
190
- // utilities — which is what spacing/color utilities like `left-2.5`,
191
- // `gap-1.5`, `text-amber-500` need to resolve. The split
192
- // `theme`/`utilities` imports skip the `@layer theme` wrapper and theme
193
- // variables aren't in scope at compile time.
194
- // 2. The host's `@theme inline` block (inlined from theme.css) teaches
195
- // Tailwind about host-owned tokens (`--color-background`,
196
- // `--color-foreground`, etc.) so widgets compile classes like
197
- // `bg-foreground/20`, `text-muted`, `rounded-xl`. The `inline` keyword
198
- // means the widget's CSS does NOT redefine the underlying
199
- // `--background`/`--foreground` variables — those stay host-owned and
200
- // the widget picks them up from `:root` at runtime.
201
- // 3. Tailwind's auto-detection treats `.widgets/` as a hidden directory
202
- // and skips it. An explicit `@source` bypasses the dot-dir + gitignore
203
- // filters.
204
- //
205
- // Important: the synthetic CSS must live on disk in the `file` namespace
206
- // because `bun-plugin-tailwind`'s `onLoad` only matches that namespace —
207
- // custom-namespace CSS is treated as raw text and our `@theme inline` block
208
- // is left unprocessed. We materialize it inside `<sourceDir>/.build/` and
209
- // have the entry import it by absolute path.
210
- async function writeSyntheticTailwindCss(widgetPath: string): Promise<string> {
211
- const sourceDir = dirname(widgetPath)
212
- const buildDir = join(sourceDir, '.build')
213
- const cssPath = join(buildDir, 'widget-tailwind.css')
214
- const contents = [
215
- `@import 'tailwindcss';`,
216
- await Bun.file(HOST_THEME_PATH).text(),
217
- `@source "${sourceDir}";`
218
- ].join('\n')
219
- await Bun.write(cssPath, contents)
220
- return cssPath
221
- }
222
-
223
- function widgetEntryPlugin(widgetPath: string, syntheticCssPath: string): BunPlugin {
224
- return {
225
- name: 'widget-entry',
226
- setup(build) {
227
- build.onResolve({ filter: /^__widget-entry$/ }, () => ({
228
- path: '__widget-entry',
229
- namespace: 'widget-entry'
230
- }))
231
-
232
- build.onLoad({ filter: /.*/, namespace: 'widget-entry' }, () => ({
233
- contents: [
234
- `import ${JSON.stringify(syntheticCssPath)};`,
235
- `export { default } from ${JSON.stringify(widgetPath)};`
236
- ].join('\n'),
237
- loader: 'js'
238
- }))
239
- }
240
- }
241
- }
242
-
243
- function injectCss(js: string, css: string, widgetName: string): string {
244
- if (!css.trim()) return js
245
-
246
- // After `moi bundle` rebuilds the widget, the new JS module re-runs in the
247
- // browser. Always replace any prior <style data-widget="<id>"> tag so the
248
- // freshly-built CSS takes effect; the previous "skip if already present"
249
- // guard left stale rules in place after edits.
250
- const injection = [
251
- `((css, id) => {`,
252
- ` document.querySelector(\`style[data-widget="\${id}"]\`)?.remove();`,
253
- ` const s = document.createElement("style");`,
254
- ` s.dataset.widget = id;`,
255
- ` s.textContent = css;`,
256
- ` document.head.appendChild(s);`,
257
- `})(${JSON.stringify(css)}, ${JSON.stringify(widgetName)});`
258
- ].join('\n')
259
-
260
- return injection + '\n' + js
261
- }
262
-
263
- function formatBuildLog(log: BuildMessage | ResolveMessage): string {
264
- const prefix = log.level === 'error' ? 'error' : log.level
265
- const loc = log.position
266
- ? `${log.position.file}:${log.position.line}:${log.position.column}: `
267
- : ''
268
- const lineText = log.position?.lineText ? `\n ${log.position.lineText.trim()}` : ''
269
- return `${loc}${prefix}: ${log.message}${lineText}`
270
- }
271
-
272
- async function prevalidateServerFiles(entrypoint: string): Promise<void> {
273
- const sourceDir = dirname(entrypoint)
274
- const source = await Bun.file(entrypoint).text()
275
-
276
- const importPattern = /from\s+['"]\.\/([^'"]+)\.server(?:\.ts)?['"]/g
277
- let match
278
- while ((match = importPattern.exec(source)) !== null) {
279
- const serverPath = join(sourceDir, `${match[1]}.server.ts`)
280
- if (await Bun.file(serverPath).exists()) {
281
- await validateServerExports(serverPath)
282
- }
283
- }
284
- }
285
-
286
- export async function buildWidget(entrypoint: string): Promise<WidgetArtifact> {
287
- const sourceDir = dirname(entrypoint)
288
- const widgetName = basename(entrypoint).replace(/\.tsx?$/, '')
289
-
290
- await prevalidateServerFiles(entrypoint)
291
-
292
- const { plugin: serverProxy, serverModules } = serverProxyPlugin(sourceDir)
293
- const syntheticCssPath = await writeSyntheticTailwindCss(entrypoint)
294
-
295
- let result: Awaited<ReturnType<typeof Bun.build>>
296
- try {
297
- result = await Bun.build({
298
- entrypoints: ['__widget-entry'],
299
- format: 'esm',
300
- target: 'browser',
301
- sourcemap: 'inline',
302
- external: EXTERNAL_MODULES,
303
- // bun-plugin-tailwind uses `build.config.root` as the auto-detect
304
- // project root (`projectRoot = build.config?.root ?? process.cwd()`).
305
- // Without this, oxide scans `none-computer/` (the parent server's
306
- // cwd) instead of the workspace's `.widgets/`.
307
- root: sourceDir,
308
- plugins: [widgetEntryPlugin(entrypoint, syntheticCssPath), serverProxy, tailwind]
309
- })
310
- } catch (err) {
311
- // Bun.build throws AggregateError on failure (default throw: true).
312
- // The message is a generic "Bundle failed"; the real diagnostics live on `.errors`.
313
- const logs = (err as { errors?: (BuildMessage | ResolveMessage)[] }).errors ?? []
314
- const formatted = logs.length
315
- ? logs.map(formatBuildLog).join('\n')
316
- : err instanceof Error
317
- ? err.message
318
- : String(err)
319
- throw new Error(`Build failed for "${widgetName}":\n${formatted}`)
320
- }
321
-
322
- if (!result.success) {
323
- const errors = result.logs.map(formatBuildLog).join('\n')
324
- throw new Error(`Build failed for "${widgetName}":\n${errors}`)
325
- }
326
-
327
- const jsOutput = result.outputs.find(o => o.path.endsWith('.js'))
328
- const cssOutput = result.outputs.find(o => o.path.endsWith('.css'))
329
-
330
- if (!jsOutput) {
331
- throw new Error(`Build produced no JS output for "${widgetName}"`)
332
- }
333
-
334
- let js = await jsOutput.text()
335
-
336
- if (cssOutput) {
337
- const css = await cssOutput.text()
338
- js = injectCss(js, css, widgetName)
339
- }
340
-
341
- const config = await extractWidgetConfig(entrypoint)
342
- return { js, serverModules, config }
343
- }