@dxos/plugin-script 0.7.5-labs.f5080a1 → 0.7.5-labs.ff2ff30

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 (79) hide show
  1. package/dist/lib/browser/{ScriptContainer-LGW52UAJ.mjs → ScriptContainer-33XAJPQZ.mjs} +33 -8
  2. package/dist/lib/browser/ScriptContainer-33XAJPQZ.mjs.map +7 -0
  3. package/dist/lib/browser/artifact-UOESRBEZ.mjs +243 -0
  4. package/dist/lib/browser/artifact-UOESRBEZ.mjs.map +7 -0
  5. package/dist/lib/browser/{chunk-2UXYECEH.mjs → chunk-BTZIBJJN.mjs} +4 -4
  6. package/dist/lib/browser/{chunk-2UXYECEH.mjs.map → chunk-BTZIBJJN.mjs.map} +2 -2
  7. package/dist/lib/browser/{compiler-K3FNRDDN.mjs → compiler-YY2XSKHQ.mjs} +2 -4
  8. package/dist/lib/browser/compiler-YY2XSKHQ.mjs.map +7 -0
  9. package/dist/lib/browser/index.mjs +9 -9
  10. package/dist/lib/browser/index.mjs.map +3 -3
  11. package/dist/lib/browser/meta.json +1 -1
  12. package/dist/lib/browser/{react-surface-XACNR5NR.mjs → react-surface-S5BSIXGB.mjs} +2 -2
  13. package/dist/lib/node/{ScriptContainer-UI2MDBYG.cjs → ScriptContainer-YR6TIDY3.cjs} +37 -10
  14. package/dist/lib/node/ScriptContainer-YR6TIDY3.cjs.map +7 -0
  15. package/dist/lib/node/artifact-PDTB4LV4.cjs +262 -0
  16. package/dist/lib/node/artifact-PDTB4LV4.cjs.map +7 -0
  17. package/dist/lib/node/{chunk-73345ZL6.cjs → chunk-2P7DKHIO.cjs} +6 -6
  18. package/dist/lib/node/{chunk-73345ZL6.cjs.map → chunk-2P7DKHIO.cjs.map} +2 -2
  19. package/dist/lib/node/{compiler-P2HQB22H.cjs → compiler-UIBLKJKG.cjs} +6 -6
  20. package/dist/lib/node/compiler-UIBLKJKG.cjs.map +7 -0
  21. package/dist/lib/node/index.cjs +13 -12
  22. package/dist/lib/node/index.cjs.map +3 -3
  23. package/dist/lib/node/meta.json +1 -1
  24. package/dist/lib/node/{react-surface-Y3RD5FW7.cjs → react-surface-YNPH5JPY.cjs} +9 -9
  25. package/dist/lib/node-esm/{ScriptContainer-F7SNP53Z.mjs → ScriptContainer-ZQRQSVJA.mjs} +33 -8
  26. package/dist/lib/node-esm/ScriptContainer-ZQRQSVJA.mjs.map +7 -0
  27. package/dist/lib/node-esm/artifact-IX4ZCTUF.mjs +245 -0
  28. package/dist/lib/node-esm/artifact-IX4ZCTUF.mjs.map +7 -0
  29. package/dist/lib/node-esm/{chunk-PRGBYF4B.mjs → chunk-YGA2AFHL.mjs} +4 -4
  30. package/dist/lib/node-esm/{chunk-PRGBYF4B.mjs.map → chunk-YGA2AFHL.mjs.map} +2 -2
  31. package/dist/lib/node-esm/{compiler-PDN46H4Y.mjs → compiler-XTXFGZJM.mjs} +2 -4
  32. package/dist/lib/node-esm/compiler-XTXFGZJM.mjs.map +7 -0
  33. package/dist/lib/node-esm/index.mjs +9 -9
  34. package/dist/lib/node-esm/index.mjs.map +3 -3
  35. package/dist/lib/node-esm/meta.json +1 -1
  36. package/dist/lib/node-esm/{react-surface-PKUVZH4S.mjs → react-surface-BNC2OM5X.mjs} +2 -2
  37. package/dist/types/src/ScriptPlugin.d.ts.map +1 -1
  38. package/dist/types/src/capabilities/artifact.d.ts +11 -0
  39. package/dist/types/src/capabilities/artifact.d.ts.map +1 -0
  40. package/dist/types/src/capabilities/index.d.ts +1 -0
  41. package/dist/types/src/capabilities/index.d.ts.map +1 -1
  42. package/dist/types/src/components/FrameContainer/FrameContainer.d.ts +2 -2
  43. package/dist/types/src/components/FrameContainer/FrameContainer.d.ts.map +1 -1
  44. package/dist/types/src/hooks/deploy.d.ts.map +1 -1
  45. package/dist/types/src/index.d.ts +0 -1
  46. package/dist/types/src/index.d.ts.map +1 -1
  47. package/package.json +41 -42
  48. package/src/ScriptPlugin.tsx +6 -1
  49. package/src/capabilities/artifact.ts +219 -0
  50. package/src/capabilities/compiler.ts +1 -1
  51. package/src/capabilities/index.ts +1 -0
  52. package/src/components/FrameContainer/FrameContainer.tsx +4 -3
  53. package/src/components/ScriptSettingsPanel.tsx +2 -2
  54. package/src/hooks/deploy.ts +14 -3
  55. package/src/index.ts +0 -1
  56. package/dist/lib/browser/ScriptContainer-LGW52UAJ.mjs.map +0 -7
  57. package/dist/lib/browser/chunk-SDHKTS6H.mjs +0 -237
  58. package/dist/lib/browser/chunk-SDHKTS6H.mjs.map +0 -7
  59. package/dist/lib/browser/compiler-K3FNRDDN.mjs.map +0 -7
  60. package/dist/lib/node/ScriptContainer-UI2MDBYG.cjs.map +0 -7
  61. package/dist/lib/node/chunk-T4TXCRN5.cjs +0 -260
  62. package/dist/lib/node/chunk-T4TXCRN5.cjs.map +0 -7
  63. package/dist/lib/node/compiler-P2HQB22H.cjs.map +0 -7
  64. package/dist/lib/node-esm/ScriptContainer-F7SNP53Z.mjs.map +0 -7
  65. package/dist/lib/node-esm/chunk-G76M6O46.mjs +0 -239
  66. package/dist/lib/node-esm/chunk-G76M6O46.mjs.map +0 -7
  67. package/dist/lib/node-esm/compiler-PDN46H4Y.mjs.map +0 -7
  68. package/dist/types/src/bundler/bundler.d.ts +0 -39
  69. package/dist/types/src/bundler/bundler.d.ts.map +0 -1
  70. package/dist/types/src/bundler/bundler.test.d.ts +0 -2
  71. package/dist/types/src/bundler/bundler.test.d.ts.map +0 -1
  72. package/dist/types/src/bundler/index.d.ts +0 -2
  73. package/dist/types/src/bundler/index.d.ts.map +0 -1
  74. package/src/bundler/bundler.test.ts +0 -55
  75. package/src/bundler/bundler.ts +0 -250
  76. package/src/bundler/index.ts +0 -5
  77. /package/dist/lib/browser/{react-surface-XACNR5NR.mjs.map → react-surface-S5BSIXGB.mjs.map} +0 -0
  78. /package/dist/lib/node/{react-surface-Y3RD5FW7.cjs.map → react-surface-YNPH5JPY.cjs.map} +0 -0
  79. /package/dist/lib/node-esm/{react-surface-PKUVZH4S.mjs.map → react-surface-BNC2OM5X.mjs.map} +0 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/components/ScriptContainer.tsx", "../../../src/components/ScriptToolbar/ScriptToolbar.tsx", "../../../src/hooks/deploy.ts", "../../../src/hooks/format.ts", "../../../src/hooks/template.ts", "../../../src/hooks/view.ts", "../../../src/hooks/useToolbarAction.ts", "../../../src/hooks/useToolbarState.ts", "../../../src/components/TypescriptEditor/TypescriptEditor.tsx"],
4
+ "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport React, { useMemo } from 'react';\n\nimport { type ScriptType } from '@dxos/functions';\nimport { createDocAccessor, getSpace } from '@dxos/react-client/echo';\nimport { useIdentity } from '@dxos/react-client/halo';\nimport { type ThemedClassName } from '@dxos/react-ui';\nimport { createDataExtensions, listener, stackItemContentEditorClassNames } from '@dxos/react-ui-editor';\nimport { StackItem } from '@dxos/react-ui-stack';\nimport { mx } from '@dxos/react-ui-theme';\n\nimport { DebugPanel } from './DebugPanel';\nimport { ScriptToolbar } from './ScriptToolbar';\nimport { TypescriptEditor, type TypescriptEditorProps } from './TypescriptEditor';\nimport { useDeployState, useToolbarState } from '../hooks';\nimport { type ScriptSettingsProps } from '../types';\n\nexport type ScriptEditorProps = ThemedClassName<{\n script: ScriptType;\n settings?: ScriptSettingsProps;\n role?: string;\n}> &\n Pick<TypescriptEditorProps, 'env'>;\n\nexport const ScriptContainer = ({\n role,\n classNames,\n script,\n settings = { editorInputMode: 'vscode' },\n env,\n}: ScriptEditorProps) => {\n const identity = useIdentity();\n const space = getSpace(script);\n\n const extensions = useMemo(\n () => [\n listener({\n onChange: (text) => {\n if (script.source.target && script.source.target.content !== text) {\n script.changed = true;\n }\n },\n }),\n createDataExtensions({\n id: script.id,\n text: script.source.target && createDocAccessor(script.source.target, ['content']),\n space,\n identity,\n }),\n ],\n [script, script.source.target, space, identity],\n );\n\n const state = useToolbarState({ view: 'editor' });\n useDeployState({ state, script });\n\n return (\n <StackItem.Content toolbar>\n <ScriptToolbar state={state} role={role} script={script} />\n <div role='none' className={mx('flex flex-col w-full overflow-hidden divide-y divide-separator', classNames)}>\n {state.view !== 'debug' && (\n <TypescriptEditor\n id={script.id}\n env={env}\n initialValue={script.source?.target?.content}\n extensions={extensions}\n className={stackItemContentEditorClassNames(role)}\n inputMode={settings.editorInputMode}\n toolbar\n />\n )}\n\n {state.view !== 'editor' && <DebugPanel functionUrl={state.functionUrl} />}\n </div>\n </StackItem.Content>\n );\n};\n\nexport default ScriptContainer;\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport React, { useCallback } from 'react';\n\nimport { type ScriptType } from '@dxos/functions';\nimport { fullyQualifiedId } from '@dxos/react-client/echo';\nimport { ElevationProvider, type ThemedClassName } from '@dxos/react-ui';\nimport { stackItemContentToolbarClassNames } from '@dxos/react-ui-editor';\nimport { createGapSeparator, MenuProvider, ToolbarMenu, useMenuActions } from '@dxos/react-ui-menu';\n\nimport {\n type ScriptToolbarState,\n createDeploy,\n createFormat,\n createTemplateSelect,\n createView,\n useToolbarAction,\n} from '../../hooks';\n\nexport type ScriptToolbarProps = ThemedClassName<{\n role?: string;\n script: ScriptType;\n state: ScriptToolbarState;\n}>;\n\nconst createToolbar = (state: ScriptToolbarState) => {\n const templateSelect = createTemplateSelect();\n const format = createFormat();\n const gap = createGapSeparator();\n const deploy = createDeploy(state);\n const view = createView(state);\n return {\n nodes: [...templateSelect.nodes, ...format.nodes, ...gap.nodes, ...deploy.nodes, ...view.nodes],\n edges: [...templateSelect.edges, ...format.edges, ...gap.edges, ...deploy.edges, ...view.edges],\n };\n};\n\nexport const ScriptToolbar = ({ script, role, state, classNames }: ScriptToolbarProps) => {\n const handleAction = useToolbarAction({ state, script });\n const toolbarCreator = useCallback(() => createToolbar(state), [state]);\n const menu = useMenuActions(toolbarCreator);\n return (\n <div role='none' className={stackItemContentToolbarClassNames(role)}>\n <ElevationProvider elevation={role === 'section' ? 'positioned' : 'base'}>\n <MenuProvider {...menu} onAction={handleAction} attendableId={fullyQualifiedId(script)}>\n <ToolbarMenu classNames={classNames} />\n </MenuProvider>\n </ElevationProvider>\n </div>\n );\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { useCallback, useEffect, useMemo } from 'react';\n\nimport {\n FunctionType,\n getInvocationUrl,\n getUserFunctionUrlInMetadata,\n incrementSemverPatch,\n type ScriptType,\n setUserFunctionUrlInMetadata,\n uploadWorkerFunction,\n} from '@dxos/functions';\nimport { Bundler } from '@dxos/functions/bundler';\nimport { log } from '@dxos/log';\nimport { useClient } from '@dxos/react-client';\nimport { Filter, create, getMeta, getSpace, makeRef, useQuery } from '@dxos/react-client/echo';\nimport { useTranslation } from '@dxos/react-ui';\nimport { createMenuAction } from '@dxos/react-ui-menu';\n\nimport { type ViewState } from './view';\nimport { SCRIPT_PLUGIN } from '../meta';\n\nexport type DeployActionProperties = { type: 'deploy' } | { type: 'copy' };\n\nexport type DeployState = ViewState & {\n deploying: boolean;\n deployed: boolean;\n functionUrl: string;\n error: string;\n};\n\nexport const createDeploy = (state: Partial<DeployState>) => {\n const errorItem = createMenuAction('error', {\n label: state.error ?? ['no error label', { ns: SCRIPT_PLUGIN }],\n icon: 'ph--warning-circle--regular',\n hidden: !state.error,\n });\n\n const deployAction = createMenuAction<DeployActionProperties>('deploy', {\n type: 'deploy',\n label: [state.deploying ? 'pending label' : 'deploy label', { ns: SCRIPT_PLUGIN }],\n icon: state.deploying ? 'ph--spinner-gap--regular' : 'ph--cloud-arrow-up--regular',\n disabled: state.deploying,\n classNames: state.deploying ? '[&_svg]:animate-spin' : '',\n });\n\n const copyAction = createMenuAction<DeployActionProperties>('copy', {\n type: 'copy',\n label: ['copy link label', { ns: SCRIPT_PLUGIN }],\n icon: 'ph--link--regular',\n disabled: !state.functionUrl,\n });\n\n return {\n nodes: [errorItem, deployAction, copyAction],\n edges: [\n { source: 'root', target: 'error' },\n { source: 'root', target: 'deploy' },\n { source: 'root', target: 'copy' },\n ],\n };\n};\n\nconst useDeployDeps = ({ state, script }: { state: Partial<DeployState>; script: ScriptType }) => {\n const space = getSpace(script);\n const [fn] = useQuery(space, Filter.schema(FunctionType, { source: script }));\n const client = useClient();\n const existingFunctionUrl = useMemo(() => fn && getUserFunctionUrlInMetadata(getMeta(fn)), [fn]);\n return { space, fn, client, existingFunctionUrl };\n};\n\nexport const useDeployState = ({ state, script }: { state: Partial<DeployState>; script: ScriptType }) => {\n const { space, client, existingFunctionUrl } = useDeployDeps({ state, script });\n useEffect(() => {\n if (!existingFunctionUrl) {\n return;\n }\n\n state.functionUrl = getInvocationUrl(existingFunctionUrl, client.config.values.runtime?.services?.edge?.url ?? '', {\n spaceId: space?.id,\n });\n }, [existingFunctionUrl, space]);\n\n useEffect(() => {\n state.deployed = Boolean(existingFunctionUrl) && !script.changed;\n }, [script.changed, existingFunctionUrl]);\n};\n\nexport const useDeployHandler = ({ state, script }: { state: Partial<DeployState>; script: ScriptType }) => {\n const { space, fn, client, existingFunctionUrl } = useDeployDeps({ state, script });\n const { t } = useTranslation(SCRIPT_PLUGIN);\n\n return useCallback(async () => {\n if (!script.source || !space) {\n return;\n }\n\n state.error = undefined;\n state.deploying = true;\n\n try {\n const existingFunctionId = existingFunctionUrl?.split('/').at(-1);\n\n const bundler = new Bundler({ platform: 'browser', sandboxedModules: [], remoteModules: {} });\n const buildResult = await bundler.bundle({ source: script.source.target!.content });\n if (buildResult.error || !buildResult.bundle) {\n throw buildResult.error;\n }\n\n const { functionId, version, meta } = await uploadWorkerFunction({\n client,\n spaceId: space.id,\n version: fn ? incrementSemverPatch(fn.version) : '0.0.1',\n functionId: existingFunctionId,\n source: buildResult.bundle,\n });\n if (functionId === undefined || version === undefined) {\n throw new Error(`Upload didn't return expected data: functionId=${functionId}, version=${version}`);\n }\n\n log.info('function uploaded', { functionId, version });\n if (fn) {\n fn.version = version;\n }\n\n const deployedFunction =\n fn ?? space.db.add(create(FunctionType, { name: functionId, version, source: makeRef(script) }));\n\n script.changed = false;\n if (script.description !== undefined && script.description.trim() !== '') {\n deployedFunction.description = script.description;\n } else if (meta.description) {\n deployedFunction.description = meta.description;\n } else {\n log.verbose('no description in function metadata', { functionId });\n }\n\n if (meta.inputSchema) {\n deployedFunction.inputSchema = meta.inputSchema;\n } else {\n log.verbose('no input schema in function metadata', { functionId });\n }\n if (meta.outputSchema) {\n deployedFunction.outputSchema = meta.outputSchema;\n } else {\n log.verbose('no output schema in function metadata', { functionId });\n }\n\n setUserFunctionUrlInMetadata(getMeta(deployedFunction), `/${space.id}/${functionId}`);\n\n state.view = 'split';\n } catch (err: any) {\n log.catch(err);\n state.error = t('upload failed label');\n }\n state.deploying = false;\n }, [fn, client, t, existingFunctionUrl, script, script.name, script.source, space?.id ?? null]);\n};\n\nexport const useCopyHandler = ({ state }: { state: Partial<DeployState> }) =>\n useCallback(async () => {\n if (!state.functionUrl) {\n return;\n }\n await navigator.clipboard.writeText(state.functionUrl);\n }, [state.functionUrl]);\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { format } from 'prettier';\nimport prettierPluginEstree from 'prettier/plugins/estree';\nimport prettierPluginTypescript from 'prettier/plugins/typescript';\nimport { useCallback } from 'react';\n\nimport { type ScriptType } from '@dxos/functions';\nimport { log } from '@dxos/log';\nimport { createMenuAction } from '@dxos/react-ui-menu';\n\nimport { SCRIPT_PLUGIN } from '../meta';\n\nexport type FormatActionProperties = { type: 'format' };\n\nexport const createFormat = () => {\n const formatAction = createMenuAction('format', {\n label: ['format label', { ns: SCRIPT_PLUGIN }],\n icon: 'ph--magic-wand--regular',\n });\n\n return {\n nodes: [formatAction],\n edges: [{ source: 'root', target: 'format' }],\n };\n};\n\nexport const useFormatHandler = ({ script }: { script: ScriptType }) =>\n useCallback(async () => {\n if (!script.source) {\n return;\n }\n\n try {\n script.source.target!.content = await format(script.source.target!.content, {\n parser: 'typescript',\n plugins: [prettierPluginEstree, prettierPluginTypescript],\n semi: true,\n singleQuote: true,\n });\n } catch (err: any) {\n // TODO(wittjosiah): Show error in UI.\n log.catch(err);\n }\n }, [script.source]);\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { useCallback } from 'react';\n\nimport { FUNCTIONS_PRESET_META_KEY, type ScriptType } from '@dxos/functions';\nimport { getMeta } from '@dxos/live-object';\nimport { createMenuItemGroup, createMenuAction } from '@dxos/react-ui-menu';\n\nimport { SCRIPT_PLUGIN } from '../meta';\nimport { templates } from '../templates';\n\nexport type TemplateActionProperties = { type: 'template'; value: string };\n\nconst createTemplateSelectGroup = () => {\n return createMenuItemGroup('template-select', {\n label: ['template select group label', { ns: SCRIPT_PLUGIN }],\n variant: 'dropdownMenu',\n });\n};\n\nconst createTemplateSelectActions = () => {\n return templates.map((template) => {\n return createMenuAction<TemplateActionProperties>(`template--${template.id}`, {\n label: template.name,\n value: template.id,\n type: 'template',\n });\n });\n};\n\nexport const createTemplateSelect = () => {\n const templateSelectGroup = createTemplateSelectGroup();\n const templateSelectActions = createTemplateSelectActions();\n return {\n nodes: [templateSelectGroup, ...templateSelectActions],\n edges: [\n { source: 'root', target: 'template-select' },\n ...templateSelectActions.map((action) => ({ source: 'template-select', target: action.id })),\n ],\n };\n};\n\nexport const useTemplateSelectHandler = ({ script }: { script: ScriptType }) => {\n return useCallback(\n (templateId: string) => {\n const template = templates.find((template) => template.id === templateId);\n if (template) {\n script.name = template.name;\n script.source!.target!.content = template.source;\n const metaKeys = getMeta(script).keys;\n const oldPresetIndex = metaKeys.findIndex((key) => key.source === FUNCTIONS_PRESET_META_KEY);\n if (oldPresetIndex >= 0) {\n metaKeys.splice(oldPresetIndex, 1);\n }\n if (template.presetId) {\n metaKeys.push({ source: FUNCTIONS_PRESET_META_KEY, id: template.presetId });\n }\n }\n },\n [script],\n );\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { createMenuAction, createMenuItemGroup } from '@dxos/react-ui-menu';\n\nimport { SCRIPT_PLUGIN } from '../meta';\n\nexport type ViewType = 'editor' | 'split' | 'debug';\n\nexport type ViewState = { view: ViewType };\n\nexport type ViewActionProperties = { type: 'view'; value: ViewType };\n\nconst views: Record<ViewType, string> = {\n editor: 'ph--code--regular',\n split: 'ph--square-split-vertical--regular',\n debug: 'ph--bug--regular',\n};\n\nconst createViewGroupItem = (state: Partial<ViewState>) => {\n return createMenuItemGroup('view', {\n label: ['view group label', { ns: SCRIPT_PLUGIN }],\n variant: 'dropdownMenu',\n applyActive: true,\n value: state.view,\n });\n};\n\nconst createViewActions = (state: Partial<ViewState>) => {\n return Object.entries(views).map(([viewType, icon]) => {\n return createMenuAction<ViewActionProperties>(`view--${viewType}`, {\n type: 'view',\n value: viewType as ViewType,\n label: [`view ${viewType} label`, { ns: SCRIPT_PLUGIN }],\n icon,\n checked: state.view === viewType,\n });\n });\n};\n\nexport const createView = (state: Partial<ViewState>) => {\n const viewGroupItem = createViewGroupItem(state);\n const viewActions = createViewActions(state);\n return {\n nodes: [viewGroupItem, ...viewActions],\n edges: [\n { source: 'root', target: 'view' },\n ...viewActions.map((action) => ({ source: 'view', target: action.id })),\n ],\n };\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { useCallback } from 'react';\n\nimport { type ScriptType } from '@dxos/functions';\nimport { log } from '@dxos/log';\nimport { type MenuAction, type MenuActionHandler } from '@dxos/react-ui-menu';\n\nimport { type DeployActionProperties, useDeployHandler, useCopyHandler } from './deploy';\nimport { type FormatActionProperties, useFormatHandler } from './format';\nimport { type TemplateActionProperties, useTemplateSelectHandler } from './template';\nimport { type ScriptToolbarState } from './useToolbarState';\nimport { type ViewActionProperties } from './view';\n\nexport type ScriptToolbarActionProperties =\n | TemplateActionProperties\n | ViewActionProperties\n | FormatActionProperties\n | DeployActionProperties;\n\nexport type ScriptToolbarAction = MenuAction<ScriptToolbarActionProperties>;\n\nexport const useToolbarAction = (props: { state: ScriptToolbarState; script: ScriptType }) => {\n const handleTemplateSelect = useTemplateSelectHandler(props);\n const handleFormat = useFormatHandler(props);\n const handleDeploy = useDeployHandler(props);\n const handleCopy = useCopyHandler(props);\n return useCallback(\n ((action: ScriptToolbarAction) => {\n switch (action.properties.type) {\n case 'template':\n handleTemplateSelect(action.properties.value);\n break;\n case 'view':\n props.state.view = action.properties.value;\n break;\n case 'format':\n void handleFormat();\n break;\n case 'deploy':\n void handleDeploy();\n break;\n case 'copy':\n void handleCopy();\n break;\n default:\n log.error('Unknown action type', action);\n }\n }) as MenuActionHandler,\n [handleTemplateSelect, handleFormat, handleDeploy, handleCopy],\n );\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { useMemo } from 'react';\n\nimport { create } from '@dxos/live-object';\n\nimport { type DeployState } from './deploy';\nimport { type ViewState } from './view';\n\nexport type ScriptToolbarState = Partial<DeployState & ViewState>;\n\nexport const useToolbarState = (initialState: ScriptToolbarState = {}) => {\n return useMemo(() => create<ScriptToolbarState>(initialState), []);\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { javascript } from '@codemirror/lang-javascript';\nimport { defaultHighlightStyle } from '@codemirror/language';\nimport { Prec } from '@codemirror/state';\nimport { oneDarkHighlightStyle } from '@codemirror/theme-one-dark';\nimport { keymap } from '@codemirror/view';\nimport { tags } from '@lezer/highlight';\nimport { type VirtualTypeScriptEnvironment } from '@typescript/vfs';\nimport { continueKeymap } from '@valtown/codemirror-continue';\nimport { tsSync, tsFacet, tsLinter, tsAutocomplete, tsHover, type HoverInfo } from '@valtown/codemirror-ts';\nimport React from 'react';\n\nimport { type ThemeMode, useThemeContext } from '@dxos/react-ui';\nimport {\n autocomplete,\n createBasicExtensions,\n createThemeExtensions,\n editorFullWidth,\n type EditorInputMode,\n editorMonospace,\n EditorView,\n folding,\n InputModeExtensions,\n useTextEditor,\n type UseTextEditorProps,\n} from '@dxos/react-ui-editor';\nimport { nonNullable } from '@dxos/util';\n\nexport type TypescriptEditorProps = {\n id: string;\n inputMode?: EditorInputMode;\n env?: VirtualTypeScriptEnvironment;\n toolbar?: boolean;\n} & Pick<UseTextEditorProps, 'className' | 'initialValue' | 'extensions' | 'scrollTo' | 'selection'>;\n\nexport const TypescriptEditor = ({\n id,\n env,\n className,\n initialValue,\n extensions,\n scrollTo,\n selection,\n toolbar,\n inputMode = 'vscode',\n}: TypescriptEditorProps) => {\n const { themeMode } = useThemeContext();\n const { parentRef, focusAttributes } = useTextEditor(\n () => ({\n id,\n initialValue,\n extensions: [\n extensions,\n createBasicExtensions({\n highlightActiveLine: true,\n indentWithTab: true,\n lineNumbers: true,\n lineWrapping: false,\n scrollPastEnd: true,\n }),\n createThemeExtensions({\n themeMode,\n syntaxHighlighting: true,\n slots: {\n content: { className: editorFullWidth },\n },\n }),\n // NOTE: Not using default editor gutter because folding for code works best right beside text.\n EditorView.theme({\n '.cm-gutters': {\n // Match margin from content.\n marginTop: '16px',\n },\n }),\n InputModeExtensions[inputMode],\n folding(),\n // Continues block comments when you hit Enter.\n Prec.high(keymap.of(continueKeymap)),\n // TODO(burdon): Factor out.\n [\n editorMonospace,\n javascript({ typescript: true }),\n // https://github.com/val-town/codemirror-ts\n autocomplete({ override: env ? [tsAutocomplete()] : [] }),\n env\n ? [\n tsFacet.of({ env, path: `/src/${id}.ts` }),\n tsSync(),\n tsLinter(),\n tsHover({ renderTooltip: createTooltipRenderer(themeMode) }),\n ]\n : [],\n ],\n ].filter(nonNullable),\n selection,\n scrollTo,\n }),\n [id, extensions, themeMode, inputMode, selection, scrollTo],\n );\n\n return (\n <div ref={parentRef} data-toolbar={toolbar ? 'enabled' : 'disabled'} className={className} {...focusAttributes} />\n );\n};\n\nconst createTooltipRenderer = (themeMode: ThemeMode) => {\n const theme = themeMode === 'dark' ? oneDarkHighlightStyle : defaultHighlightStyle;\n\n const classFromKind = (_kind: string) => {\n // E.g., localName, methodName, parameterName, etc.\n const kind = _kind.endsWith('Name') ? 'name' : _kind;\n const validTag = kind in tags;\n if (!validTag) {\n return '';\n }\n\n const tag = tags[kind as keyof typeof tags];\n if (typeof tag === 'function') {\n return '';\n }\n\n return theme.style([tag]) ?? '';\n };\n\n return (info: HoverInfo) => {\n const div = document.createElement('div');\n div.className = 'p-1 rounded border border-separator bg-baseSurface xs:max-w-80 max-w-lg';\n\n if (info.quickInfo?.displayParts) {\n for (const part of info.quickInfo.displayParts) {\n const span = div.appendChild(document.createElement('span'));\n span.className = classFromKind(part.kind);\n span.innerText = part.text;\n }\n }\n\n return { dom: div };\n };\n};\n\nexport default TypescriptEditor;\n"],
5
+ "mappings": ";;;;;;;;;;;;AAIA,OAAOA,UAASC,WAAAA,gBAAe;AAG/B,SAASC,mBAAmBC,YAAAA,iBAAgB;AAC5C,SAASC,mBAAmB;AAE5B,SAASC,sBAAsBC,UAAUC,wCAAwC;AACjF,SAASC,iBAAiB;AAC1B,SAASC,UAAU;;;ACRnB,OAAOC,SAASC,eAAAA,oBAAmB;AAGnC,SAASC,wBAAwB;AACjC,SAASC,yBAA+C;AACxD,SAASC,yCAAyC;AAClD,SAASC,oBAAoBC,cAAcC,aAAaC,sBAAsB;;;ACN9E,SAASC,aAAaC,WAAWC,eAAe;AAEhD,SACEC,cACAC,kBACAC,8BACAC,sBAEAC,8BACAC,4BACK;AACP,SAASC,eAAe;AACxB,SAASC,WAAW;AACpB,SAASC,iBAAiB;AAC1B,SAASC,QAAQC,QAAQC,SAASC,UAAUC,SAASC,gBAAgB;AACrE,SAASC,sBAAsB;AAC/B,SAASC,wBAAwB;;AAc1B,IAAMC,eAAe,CAACC,UAAAA;AAC3B,QAAMC,YAAYC,iBAAiB,SAAS;IAC1CC,OAAOH,MAAMI,SAAS;MAAC;MAAkB;QAAEC,IAAIC;MAAc;;IAC7DC,MAAM;IACNC,QAAQ,CAACR,MAAMI;EACjB,CAAA;AAEA,QAAMK,eAAeP,iBAAyC,UAAU;IACtEQ,MAAM;IACNP,OAAO;MAACH,MAAMW,YAAY,kBAAkB;MAAgB;QAAEN,IAAIC;MAAc;;IAChFC,MAAMP,MAAMW,YAAY,6BAA6B;IACrDC,UAAUZ,MAAMW;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OAAA,cAACC,UAAUC,SAAO;IAACC,SAAAA;KACjB,gBAAAH,OAAA,cAACI,eAAAA;IAAcR;IAActB;IAAYE;MACzC,gBAAAwB,OAAA,cAACK,OAAAA;IAAI/B,MAAK;IAAOgC,WAAWC,GAAG,kEAAkEhC,UAAAA;KAC9FqB,MAAME,SAAS,WACd,gBAAAE,OAAA,cAACQ,kBAAAA;IACCd,IAAIlB,OAAOkB;IACXf;IACA8B,cAAcjC,OAAOa,QAAQC,QAAQC;IACrCP;IACAsB,WAAWI,iCAAiCpC,IAAAA;IAC5CqC,WAAWlC,SAASC;IACpByB,SAAAA;MAIHP,MAAME,SAAS,YAAY,gBAAAE,OAAA,cAACY,YAAAA;IAAWC,aAAajB,MAAMiB;;AAInE;AAEA,IAAA,0BAAexC;",
6
+ "names": ["React", "useMemo", "createDocAccessor", "getSpace", "useIdentity", "createDataExtensions", "listener", "stackItemContentEditorClassNames", "StackItem", "mx", "React", "useCallback", "fullyQualifiedId", "ElevationProvider", "stackItemContentToolbarClassNames", "createGapSeparator", "MenuProvider", "ToolbarMenu", "useMenuActions", "useCallback", "useEffect", "useMemo", "FunctionType", "getInvocationUrl", "getUserFunctionUrlInMetadata", "incrementSemverPatch", "setUserFunctionUrlInMetadata", "uploadWorkerFunction", "Bundler", "log", "useClient", "Filter", "create", "getMeta", "getSpace", "makeRef", "useQuery", "useTranslation", "createMenuAction", "createDeploy", "state", "errorItem", "createMenuAction", "label", "error", "ns", "SCRIPT_PLUGIN", "icon", "hidden", "deployAction", "type", "deploying", "disabled", "classNames", "copyAction", "functionUrl", "nodes", "edges", "source", "target", "useDeployDeps", "script", "space", "getSpace", "fn", "useQuery", "Filter", "schema", "FunctionType", "client", "useClient", "existingFunctionUrl", "useMemo", "getUserFunctionUrlInMetadata", "getMeta", "useDeployState", "useEffect", "getInvocationUrl", "config", "values", "runtime", "services", "edge", "url", "spaceId", "id", "deployed", "Boolean", "changed", "useDeployHandler", "t", "useTranslation", "useCallback", "undefined", "existingFunctionId", "split", "at", "bundler", "Bundler", "platform", "sandboxedModules", "remoteModules", "buildResult", "bundle", "content", "functionId", "version", "meta", "uploadWorkerFunction", "incrementSemverPatch", "Error", "log", "info", "deployedFunction", "db", "add", "create", "name", "makeRef", "description", "trim", "verbose", "inputSchema", "outputSchema", "setUserFunctionUrlInMetadata", "view", "err", "catch", "useCopyHandler", "navigator", "clipboard", "writeText", "format", "prettierPluginEstree", "prettierPluginTypescript", "useCallback", "log", "createMenuAction", "createFormat", "formatAction", "createMenuAction", "label", "ns", "SCRIPT_PLUGIN", "icon", "nodes", "edges", "source", "target", "useFormatHandler", "script", "useCallback", "content", "format", "parser", "plugins", "prettierPluginEstree", "prettierPluginTypescript", "semi", "singleQuote", "err", "log", "catch", "useCallback", "FUNCTIONS_PRESET_META_KEY", "getMeta", "createMenuItemGroup", "createMenuAction", "createTemplateSelectGroup", "createMenuItemGroup", "label", "ns", "SCRIPT_PLUGIN", "variant", "createTemplateSelectActions", "templates", "map", "template", "createMenuAction", "id", "name", "value", "type", "createTemplateSelect", "templateSelectGroup", "templateSelectActions", "nodes", "edges", "source", "target", "action", "useTemplateSelectHandler", "script", "useCallback", "templateId", "find", "content", "metaKeys", "getMeta", "keys", "oldPresetIndex", "findIndex", "key", "FUNCTIONS_PRESET_META_KEY", "splice", "presetId", "push", "createMenuAction", "createMenuItemGroup", "views", "editor", "split", "debug", "createViewGroupItem", "state", "createMenuItemGroup", "label", "ns", "SCRIPT_PLUGIN", "variant", "applyActive", "value", "view", "createViewActions", "Object", "entries", "map", "viewType", "icon", "createMenuAction", "type", "checked", "createView", "viewGroupItem", "viewActions", "nodes", "edges", "source", "target", "action", "id", "useCallback", "log", "useToolbarAction", "props", "handleTemplateSelect", "useTemplateSelectHandler", "handleFormat", "useFormatHandler", "handleDeploy", "useDeployHandler", "handleCopy", "useCopyHandler", "useCallback", "action", "properties", "type", "value", "state", "view", "log", "error", "useMemo", "create", "useToolbarState", "initialState", "useMemo", "create", "createToolbar", "state", "templateSelect", "createTemplateSelect", "format", "createFormat", "gap", "createGapSeparator", "deploy", "createDeploy", "view", "createView", "nodes", "edges", "ScriptToolbar", "script", "role", "classNames", "handleAction", "useToolbarAction", "toolbarCreator", "useCallback", "menu", "useMenuActions", "div", "className", "stackItemContentToolbarClassNames", "ElevationProvider", "elevation", "MenuProvider", "onAction", "attendableId", "fullyQualifiedId", "ToolbarMenu", "javascript", "defaultHighlightStyle", "Prec", "oneDarkHighlightStyle", "keymap", "tags", "continueKeymap", "tsSync", "tsFacet", "tsLinter", "tsAutocomplete", "tsHover", "React", "useThemeContext", "autocomplete", "createBasicExtensions", "createThemeExtensions", "editorFullWidth", "editorMonospace", "EditorView", "folding", "InputModeExtensions", "useTextEditor", "nonNullable", "TypescriptEditor", "id", "env", "className", "initialValue", "extensions", "scrollTo", "selection", "toolbar", "inputMode", "themeMode", "useThemeContext", "parentRef", "focusAttributes", "useTextEditor", "createBasicExtensions", "highlightActiveLine", "indentWithTab", "lineNumbers", "lineWrapping", "scrollPastEnd", "createThemeExtensions", "syntaxHighlighting", "slots", "content", "editorFullWidth", "EditorView", "theme", "marginTop", "InputModeExtensions", "folding", "Prec", "high", "keymap", "of", "continueKeymap", "editorMonospace", "javascript", "typescript", "autocomplete", "override", "tsAutocomplete", "tsFacet", "path", "tsSync", "tsLinter", "tsHover", "renderTooltip", "createTooltipRenderer", "filter", "nonNullable", "React", "div", "ref", "data-toolbar", "oneDarkHighlightStyle", "defaultHighlightStyle", "classFromKind", "_kind", "kind", "endsWith", "validTag", "tags", "tag", "style", "info", "document", "createElement", "quickInfo", "displayParts", "part", "span", "appendChild", "innerText", "text", "dom", "ScriptContainer", "role", "classNames", "script", "settings", "editorInputMode", "env", "identity", "useIdentity", "space", "getSpace", "extensions", "useMemo", "listener", "onChange", "text", "source", "target", "content", "changed", "createDataExtensions", "id", "createDocAccessor", "state", "useToolbarState", "view", "useDeployState", "React", "StackItem", "Content", "toolbar", "ScriptToolbar", "div", "className", "mx", "TypescriptEditor", "initialValue", "stackItemContentEditorClassNames", "inputMode", "DebugPanel", "functionUrl"]
7
+ }
@@ -0,0 +1,245 @@
1
+ import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
+
3
+ // packages/plugins/experimental/plugin-script/src/capabilities/artifact.ts
4
+ import { Capabilities, contributes, createIntent } from "@dxos/app-framework";
5
+ import { defineArtifact, defineTool, ToolResult } from "@dxos/artifact";
6
+ import { createArtifactElement } from "@dxos/assistant";
7
+ import { ObjectId, S } from "@dxos/echo-schema";
8
+ import { ScriptType } from "@dxos/functions";
9
+ import { invariant } from "@dxos/invariant";
10
+ import { create, makeRef } from "@dxos/react-client/echo";
11
+ import { TextType } from "@dxos/schema";
12
+ import { SpaceAction } from "@dxos/plugin-space/types";
13
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/plugins/experimental/plugin-script/src/capabilities/artifact.ts";
14
+ var artifact_default = () => {
15
+ const definition = defineArtifact({
16
+ id: "plugin-script",
17
+ // TODO(dmaretskyi): Since writing scripts requires a lot of domain knowledge,
18
+ // we should offload the work of synthesizing the code to a separate model.
19
+ // The main reasoning model will give it a concrete task and the script model will synthesize the code, knowing all the docs.
20
+ instructions: `
21
+ If the user explicitly requests you to write a script, you can create one.
22
+ If the user requests you to change one of the existing script, you can update it.
23
+ Scripts are short code pieces of executable code that can be used to perform computations, integrate with external systems, and perform automated tasks.
24
+ Each script must follow as strict shape for the definition but the body can contain any valid executable code.
25
+ Scripts are written in JavaScript or TypeScript.
26
+ Each script must define an input schema and output schema.
27
+ Each script must have its own detailed description.
28
+
29
+ Important: You cannot execute scripts. Scripts are only available as tools after the user deploys them. You must only call the available tools.
30
+
31
+ Description:
32
+ The description is a detailed description of the script.
33
+ It is used to describe the script's purpose, input, and output.
34
+ The description is used to generate the script's documentation.
35
+ The description is also goes into the script metadata.
36
+ The description is used by AI to understand the script and its purpose.
37
+ The description must provide cases on when the script should be used.
38
+
39
+ Schema:
40
+ The schema is defined using a schema-DSL library called Effect Schema.
41
+ The input schema describes the arguments that the script accepts.
42
+ The output schema describes the result that the script produces.
43
+ The schema is used to validate the script's input and output.
44
+ The schema is also goes into the script metadata.
45
+ The properties in the schema must have valid descriptions.
46
+ The input and output schemas must both be a struct of fields.
47
+
48
+ Restricts:
49
+ The scripts can only import code from "dxos:functions" module. No other modules are allowed.
50
+ Some web APIs are available - like fetch.
51
+
52
+ Reasoning:
53
+ Before writing a script, synthesize the following information:
54
+ - Description
55
+ - What APIs will be used.
56
+ - Detailed input schema
57
+ - Detailed output schema
58
+
59
+ <apis>
60
+ export function defineFunction(params: {
61
+ description: string,
62
+ inputSchema: S.Schema,
63
+ outputSchema: S.Schema,
64
+ handler: (params: { event: { data: TInput } }) => Promise<TOutput>
65
+ }): FunctionDefinition
66
+ /**
67
+ * Effect Schema
68
+ */
69
+ export const S;
70
+
71
+ // Examples:
72
+
73
+ S.String
74
+ S.Number
75
+ S.Boolean
76
+ S.Struct({
77
+ from: S.String.annotations({ description: 'The source currency' }),
78
+ to: S.String.annotations({ description: 'The target currency' }),
79
+ })
80
+ S.Array(S.String)
81
+ S.Union(S.String, S.Number)
82
+ S.optional(S.String)
83
+ S.String.annotations({ description: 'The source currency' })
84
+ </apis>
85
+
86
+ <handler_function>
87
+ Async function that takes the argument in the form of:
88
+
89
+ type HandlerFunctionParam = {
90
+ event: {
91
+ data: T // The input schema
92
+ },
93
+ }
94
+
95
+ The function must return the result that matches the output schema.
96
+ </handler_function>
97
+
98
+ <example>
99
+ import { defineFunction, S } from 'dxos:functions';
100
+
101
+ export default defineFunction({
102
+ description: 'Returns the exchange rate between two currencies.',
103
+
104
+ inputSchema: S.Struct({
105
+ from: S.String.annotations({ description: 'The source currency' }),
106
+ to: S.String.annotations({ description: 'The target currency' }),
107
+ }),
108
+
109
+ outputSchema: S.Struct({
110
+ rate: S.String.annotations({ description: 'The exchange rate' }),
111
+ }),
112
+
113
+ handler: async ({
114
+ event: {
115
+ data: { from, to },
116
+ },
117
+ }: any) => {
118
+ const res = await fetch(\`https://free.ratesdb.com/v1/rates?from=\${from}&to=\${to}\`);
119
+ const {
120
+ data: { rates },
121
+ } = await res.json();
122
+
123
+ return { rate: rates[to].toString() };
124
+ },
125
+ });
126
+ </example>
127
+ `,
128
+ schema: ScriptType,
129
+ tools: [
130
+ defineTool({
131
+ name: "script_new",
132
+ description: "Create a new script. Returns the artifact definition for the script",
133
+ schema: S.Struct({
134
+ name: S.String.annotations({
135
+ description: "The name of the script"
136
+ }),
137
+ code: S.String.annotations({
138
+ description: "The full code of the script in JavaScript or TypeScript. Must be valid executable code."
139
+ })
140
+ }),
141
+ execute: async ({ name, code }, { extensions }) => {
142
+ invariant(extensions?.space, "No space", {
143
+ F: __dxlog_file,
144
+ L: 149,
145
+ S: void 0,
146
+ A: [
147
+ "extensions?.space",
148
+ "'No space'"
149
+ ]
150
+ });
151
+ invariant(extensions?.dispatch, "No intent dispatcher", {
152
+ F: __dxlog_file,
153
+ L: 150,
154
+ S: void 0,
155
+ A: [
156
+ "extensions?.dispatch",
157
+ "'No intent dispatcher'"
158
+ ]
159
+ });
160
+ const script = create(ScriptType, {
161
+ name,
162
+ source: makeRef(create(TextType, {
163
+ content: code
164
+ }))
165
+ });
166
+ extensions.space.db.add(script);
167
+ await extensions.space.db.flush();
168
+ const intent = createIntent(SpaceAction.AddObject, {
169
+ target: extensions.space,
170
+ object: script
171
+ });
172
+ const { data, error } = await extensions.dispatch(intent);
173
+ if (!data || error) {
174
+ return ToolResult.Error(error?.message ?? "Failed to create chess game");
175
+ }
176
+ return ToolResult.Success(createArtifactElement(script.id));
177
+ }
178
+ }),
179
+ defineTool({
180
+ name: "script_inspect",
181
+ description: "Inspect a script. Returns the artifact definition for the script",
182
+ schema: S.Struct({
183
+ id: ObjectId
184
+ }),
185
+ execute: async ({ id }, { extensions }) => {
186
+ invariant(extensions?.space, "No space", {
187
+ F: __dxlog_file,
188
+ L: 178,
189
+ S: void 0,
190
+ A: [
191
+ "extensions?.space",
192
+ "'No space'"
193
+ ]
194
+ });
195
+ const script = await extensions.space.db.query({
196
+ id
197
+ }).first();
198
+ const { content } = await script.source.load();
199
+ return ToolResult.Success({
200
+ name: script.name,
201
+ code: content
202
+ });
203
+ }
204
+ }),
205
+ defineTool({
206
+ name: "script_update",
207
+ description: "Update a script. Returns the artifact definition for the script",
208
+ schema: S.Struct({
209
+ id: ObjectId,
210
+ code: S.String.annotations({
211
+ description: "The full code of the script in JavaScript or TypeScript. Must be valid executable code."
212
+ })
213
+ }),
214
+ execute: async ({ id, code }, { extensions }) => {
215
+ invariant(extensions?.space, "No space", {
216
+ F: __dxlog_file,
217
+ L: 199,
218
+ S: void 0,
219
+ A: [
220
+ "extensions?.space",
221
+ "'No space'"
222
+ ]
223
+ });
224
+ const script = await extensions.space.db.query({
225
+ id
226
+ }).first();
227
+ const source = await script.source.load();
228
+ if (!source) {
229
+ return ToolResult.Error("Script not found");
230
+ }
231
+ source.content = code;
232
+ await extensions.space?.db.flush();
233
+ return ToolResult.Success({
234
+ name: script.name
235
+ });
236
+ }
237
+ })
238
+ ]
239
+ });
240
+ return contributes(Capabilities.ArtifactDefinition, definition);
241
+ };
242
+ export {
243
+ artifact_default as default
244
+ };
245
+ //# sourceMappingURL=artifact-IX4ZCTUF.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/capabilities/artifact.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport { Capabilities, contributes, createIntent, type PromiseIntentDispatcher } from '@dxos/app-framework';\nimport { defineArtifact, defineTool, ToolResult } from '@dxos/artifact';\nimport { createArtifactElement } from '@dxos/assistant';\nimport { ObjectId, S } from '@dxos/echo-schema';\nimport { ScriptType } from '@dxos/functions';\nimport { invariant } from '@dxos/invariant';\nimport { create, makeRef, type Space } from '@dxos/react-client/echo';\nimport { TextType } from '@dxos/schema';\nimport { SpaceAction } from '@dxos/plugin-space/types';\n\n// TODO(burdon): Factor out.\ndeclare global {\n interface ToolContextExtensions {\n space?: Space;\n dispatch?: PromiseIntentDispatcher;\n }\n}\n\nexport default () => {\n const definition = defineArtifact({\n id: 'plugin-script',\n // TODO(dmaretskyi): Since writing scripts requires a lot of domain knowledge,\n // we should offload the work of synthesizing the code to a separate model.\n // The main reasoning model will give it a concrete task and the script model will synthesize the code, knowing all the docs.\n instructions: `\n If the user explicitly requests you to write a script, you can create one.\n If the user requests you to change one of the existing script, you can update it.\n Scripts are short code pieces of executable code that can be used to perform computations, integrate with external systems, and perform automated tasks.\n Each script must follow as strict shape for the definition but the body can contain any valid executable code.\n Scripts are written in JavaScript or TypeScript.\n Each script must define an input schema and output schema.\n Each script must have its own detailed description.\n\n Important: You cannot execute scripts. Scripts are only available as tools after the user deploys them. You must only call the available tools.\n\n Description:\n The description is a detailed description of the script.\n It is used to describe the script's purpose, input, and output.\n The description is used to generate the script's documentation.\n The description is also goes into the script metadata.\n The description is used by AI to understand the script and its purpose.\n The description must provide cases on when the script should be used.\n\n Schema: \n The schema is defined using a schema-DSL library called Effect Schema.\n The input schema describes the arguments that the script accepts.\n The output schema describes the result that the script produces.\n The schema is used to validate the script's input and output.\n The schema is also goes into the script metadata.\n The properties in the schema must have valid descriptions.\n The input and output schemas must both be a struct of fields.\n\n Restricts:\n The scripts can only import code from \"dxos:functions\" module. No other modules are allowed.\n Some web APIs are available - like fetch.\n\n Reasoning:\n Before writing a script, synthesize the following information:\n - Description\n - What APIs will be used.\n - Detailed input schema\n - Detailed output schema\n\n <apis>\n export function defineFunction(params: { \n description: string, \n inputSchema: S.Schema, \n outputSchema: S.Schema, \n handler: (params: { event: { data: TInput } }) => Promise<TOutput> \n }): FunctionDefinition\n /**\n * Effect Schema\n */\n export const S; \n\n // Examples: \n\n S.String\n S.Number\n S.Boolean\n S.Struct({\n from: S.String.annotations({ description: 'The source currency' }),\n to: S.String.annotations({ description: 'The target currency' }),\n })\n S.Array(S.String)\n S.Union(S.String, S.Number)\n S.optional(S.String)\n S.String.annotations({ description: 'The source currency' })\n </apis>\n\n <handler_function>\n Async function that takes the argument in the form of:\n\n type HandlerFunctionParam = {\n event: {\n data: T // The input schema\n },\n }\n\n The function must return the result that matches the output schema.\n </handler_function>\n \n <example>\n import { defineFunction, S } from 'dxos:functions';\n\n export default defineFunction({\n description: 'Returns the exchange rate between two currencies.',\n\n inputSchema: S.Struct({\n from: S.String.annotations({ description: 'The source currency' }),\n to: S.String.annotations({ description: 'The target currency' }),\n }),\n\n outputSchema: S.Struct({\n rate: S.String.annotations({ description: 'The exchange rate' }),\n }),\n\n handler: async ({\n event: {\n data: { from, to },\n },\n }: any) => {\n const res = await fetch(\\`https://free.ratesdb.com/v1/rates?from=\\${from}&to=\\${to}\\`);\n const {\n data: { rates },\n } = await res.json();\n\n return { rate: rates[to].toString() };\n },\n });\n </example>\n `,\n schema: ScriptType,\n tools: [\n defineTool({\n name: 'script_new',\n description: 'Create a new script. Returns the artifact definition for the script',\n schema: S.Struct({\n name: S.String.annotations({ description: 'The name of the script' }),\n code: S.String.annotations({\n description: 'The full code of the script in JavaScript or TypeScript. Must be valid executable code.',\n }),\n }),\n execute: async ({ name, code }, { extensions }) => {\n invariant(extensions?.space, 'No space');\n invariant(extensions?.dispatch, 'No intent dispatcher');\n const script = create(ScriptType, {\n name,\n source: makeRef(\n create(TextType, {\n content: code,\n }),\n ),\n });\n extensions.space.db.add(script);\n await extensions.space.db.flush();\n\n const intent = createIntent(SpaceAction.AddObject, { target: extensions.space, object: script });\n const { data, error } = await extensions.dispatch(intent);\n if (!data || error) {\n return ToolResult.Error(error?.message ?? 'Failed to create chess game');\n }\n\n return ToolResult.Success(createArtifactElement(script.id));\n },\n }),\n defineTool({\n name: 'script_inspect',\n description: 'Inspect a script. Returns the artifact definition for the script',\n schema: S.Struct({\n id: ObjectId,\n }),\n execute: async ({ id }, { extensions }) => {\n invariant(extensions?.space, 'No space');\n\n const script = (await extensions.space.db.query({ id }).first()) as ScriptType;\n const { content } = await script.source.load();\n\n return ToolResult.Success({\n name: script.name,\n code: content,\n });\n },\n }),\n defineTool({\n name: 'script_update',\n description: 'Update a script. Returns the artifact definition for the script',\n schema: S.Struct({\n id: ObjectId,\n code: S.String.annotations({\n description: 'The full code of the script in JavaScript or TypeScript. Must be valid executable code.',\n }),\n }),\n execute: async ({ id, code }, { extensions }) => {\n invariant(extensions?.space, 'No space');\n\n const script = (await extensions.space.db.query({ id }).first()) as ScriptType;\n const source = await script.source.load();\n if (!source) {\n return ToolResult.Error('Script not found');\n }\n\n source.content = code;\n await extensions.space?.db.flush();\n\n return ToolResult.Success({\n name: script.name,\n });\n },\n }),\n ],\n });\n\n return contributes(Capabilities.ArtifactDefinition, definition);\n};\n"],
5
+ "mappings": ";;;AAIA,SAASA,cAAcC,aAAaC,oBAAkD;AACtF,SAASC,gBAAgBC,YAAYC,kBAAkB;AACvD,SAASC,6BAA6B;AACtC,SAASC,UAAUC,SAAS;AAC5B,SAASC,kBAAkB;AAC3B,SAASC,iBAAiB;AAC1B,SAASC,QAAQC,eAA2B;AAC5C,SAASC,gBAAgB;AACzB,SAASC,mBAAmB;;AAU5B,IAAA,mBAAe,MAAA;AACb,QAAMC,aAAaZ,eAAe;IAChCa,IAAI;;;;IAIJC,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA4GdC,QAAQT;IACRU,OAAO;MACLf,WAAW;QACTgB,MAAM;QACNC,aAAa;QACbH,QAAQV,EAAEc,OAAO;UACfF,MAAMZ,EAAEe,OAAOC,YAAY;YAAEH,aAAa;UAAyB,CAAA;UACnEI,MAAMjB,EAAEe,OAAOC,YAAY;YACzBH,aAAa;UACf,CAAA;QACF,CAAA;QACAK,SAAS,OAAO,EAAEN,MAAMK,KAAI,GAAI,EAAEE,WAAU,MAAE;AAC5CjB,oBAAUiB,YAAYC,OAAO,YAAA;;;;;;;;;AAC7BlB,oBAAUiB,YA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AUiB,YAAYC,OAAO,YAAA;;;;;;;;;AAE7B,gBAAME,SAAU,MAAMH,WAAWC,MAAMK,GAAGY,MAAM;YAAE7B;UAAG,CAAA,EAAG8B,MAAK;AAC7D,gBAAMf,SAAS,MAAMD,OAAOC,OAAOgB,KAAI;AACvC,cAAI,CAAChB,QAAQ;AACX,mBAAO1B,WAAWqC,MAAM,kBAAA;UAC1B;AAEAX,iBAAOC,UAAUP;AACjB,gBAAME,WAAWC,OAAOK,GAAGE,MAAAA;AAE3B,iBAAO9B,WAAWuC,QAAQ;YACxBxB,MAAMU,OAAOV;UACf,CAAA;QACF;MACF,CAAA;;EAEJ,CAAA;AAEA,SAAOnB,YAAYD,aAAagD,oBAAoBjC,UAAAA;AACtD;",
6
+ "names": ["Capabilities", "contributes", "createIntent", "defineArtifact", "defineTool", "ToolResult", "createArtifactElement", "ObjectId", "S", "ScriptType", "invariant", "create", "makeRef", "TextType", "SpaceAction", "definition", "id", "instructions", "schema", "tools", "name", "description", "Struct", "String", "annotations", "code", "execute", "extensions", "space", "dispatch", "script", "source", "content", "db", "add", "flush", "intent", "AddObject", "target", "object", "data", "error", "Error", "message", "Success", "query", "first", "load", "ArtifactDefinition"]
7
+ }
@@ -60,7 +60,7 @@ import { FunctionType, getInvocationUrl, getUserFunctionUrlInMetadata } from "@d
60
60
  import { log } from "@dxos/log";
61
61
  import { useClient as useClient2 } from "@dxos/react-client";
62
62
  import { Filter, getMeta, getSpace, useQuery } from "@dxos/react-client/echo";
63
- import { Button as Button2, Clipboard, Input, Separator, useControlledValue, useTranslation as useTranslation2 } from "@dxos/react-ui";
63
+ import { Button as Button2, Clipboard, Input, Separator, useControlledState, useTranslation as useTranslation2 } from "@dxos/react-ui";
64
64
  import { AccessTokenType } from "@dxos/schema";
65
65
  var __dxlog_file = "/home/runner/work/dxos/dxos/packages/plugins/experimental/plugin-script/src/components/ScriptSettingsPanel.tsx";
66
66
  var kebabize = (str) => str.replace(/[A-Z]+(?![a-z])|[A-Z]/g, ($, ofs) => (ofs ? "-" : "") + $.toLowerCase());
@@ -108,7 +108,7 @@ var ScriptSettingsPanel = ({ script }) => {
108
108
  githubToken,
109
109
  gistKey
110
110
  ]);
111
- const [binding, setBinding] = useControlledValue(fn?.binding ?? "");
111
+ const [binding, setBinding] = useControlledState(fn?.binding ?? "");
112
112
  const handleBindingChange = useCallback((event) => {
113
113
  setBinding(event.target.value);
114
114
  }, [
@@ -226,7 +226,7 @@ var ScriptSettingsPanel = ({ script }) => {
226
226
  // packages/plugins/experimental/plugin-script/src/components/index.ts
227
227
  import { lazy } from "react";
228
228
  var AutomationPanel = lazy(() => import("./AutomationPanel-W6SKG35R.mjs"));
229
- var ScriptContainer = lazy(() => import("./ScriptContainer-F7SNP53Z.mjs"));
229
+ var ScriptContainer = lazy(() => import("./ScriptContainer-ZQRQSVJA.mjs"));
230
230
 
231
231
  export {
232
232
  ScriptSettings,
@@ -234,4 +234,4 @@ export {
234
234
  AutomationPanel,
235
235
  ScriptContainer
236
236
  };
237
- //# sourceMappingURL=chunk-PRGBYF4B.mjs.map
237
+ //# sourceMappingURL=chunk-YGA2AFHL.mjs.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/components/ScriptSettings/ScriptSettings.tsx", "../../../src/components/ScriptSettingsPanel.tsx", "../../../src/components/index.ts"],
4
- "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport React from 'react';\n\nimport { type Credential } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { useClient } from '@dxos/react-client';\nimport { Button, Select, useTranslation } from '@dxos/react-ui';\nimport { type EditorInputMode, EditorInputModes } from '@dxos/react-ui-editor';\nimport { DeprecatedFormContainer, DeprecatedFormInput } from '@dxos/react-ui-form';\n\nimport { SCRIPT_PLUGIN } from '../../meta';\nimport { type ScriptSettingsProps } from '../../types';\n\nexport const ScriptSettings = ({ settings }: { settings: ScriptSettingsProps }) => {\n const { t } = useTranslation(SCRIPT_PLUGIN);\n const client = useClient();\n\n // TODO(burdon): Check token.\n const handleAuthenticate = async () => {\n const { identityKey } = client.halo.identity.get()!;\n await client.halo.writeCredentials([\n {\n issuer: identityKey,\n issuanceDate: new Date(),\n subject: {\n id: identityKey,\n assertion: {\n '@type': 'dxos.halo.credentials.ServiceAccess',\n serverName: 'hub.dxos.network',\n serverKey: identityKey,\n identityKey,\n capabilities: ['composer:beta'],\n },\n },\n } satisfies Credential,\n ]);\n };\n\n return (\n <DeprecatedFormContainer>\n {/* TODO(wittjosiah): Hide outside of dev environments. */}\n <DeprecatedFormInput label={t('authenticate action label')}>\n <Button onClick={handleAuthenticate}>{t('authenticate button label')}</Button>\n </DeprecatedFormInput>\n\n <DeprecatedFormInput label={t('editor input mode label')}>\n <Select.Root\n value={settings.editorInputMode ?? 'default'}\n onValueChange={(value) => {\n settings.editorInputMode = value as EditorInputMode;\n }}\n >\n <Select.TriggerButton placeholder={t('select editor input mode placeholder')} />\n <Select.Portal>\n <Select.Content>\n <Select.Viewport>\n {EditorInputModes.map((mode) => (\n <Select.Option key={mode} value={mode}>\n {t(`settings editor input mode ${mode} label`)}\n </Select.Option>\n ))}\n </Select.Viewport>\n </Select.Content>\n </Select.Portal>\n </Select.Root>\n </DeprecatedFormInput>\n </DeprecatedFormContainer>\n );\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { Octokit } from '@octokit/core';\nimport React, { type ChangeEvent, useCallback, useEffect, useState } from 'react';\n\nimport { createIntent, SettingsAction, useIntentDispatcher } from '@dxos/app-framework';\nimport { FunctionType, type ScriptType, getInvocationUrl, getUserFunctionUrlInMetadata } from '@dxos/functions';\nimport { log } from '@dxos/log';\nimport { useClient } from '@dxos/react-client';\nimport { Filter, getMeta, getSpace, useQuery } from '@dxos/react-client/echo';\nimport { Button, Clipboard, Input, Separator, useControlledValue, useTranslation } from '@dxos/react-ui';\nimport { AccessTokenType } from '@dxos/schema';\n\nimport { SCRIPT_PLUGIN } from '../meta';\n\n// TODO(wittjosiah): Factor out.\n// From https://stackoverflow.com/a/67243723/2804332\nconst kebabize = (str: string) => str.replace(/[A-Z]+(?![a-z])|[A-Z]/g, ($, ofs) => (ofs ? '-' : '') + $.toLowerCase());\n\nexport type ScriptSettingsPanelProps = {\n script: ScriptType;\n};\n\nexport const ScriptSettingsPanel = ({ script }: ScriptSettingsPanelProps) => {\n const { t } = useTranslation(SCRIPT_PLUGIN);\n const { dispatchPromise: dispatch } = useIntentDispatcher();\n const client = useClient();\n const space = getSpace(script);\n const [fn] = useQuery(space, Filter.schema(FunctionType, { source: script }));\n const [githubToken] = useQuery(space, Filter.schema(AccessTokenType, { source: 'github.com' }));\n const gistKey = getMeta(script).keys.find(({ source }) => source === 'github.com');\n const [gistUrl, setGistUrl] = useState<string | undefined>();\n\n useEffect(() => {\n const token = githubToken?.token;\n const gistId = gistKey?.id;\n if (!token || !gistId) {\n setGistUrl(undefined);\n return;\n }\n\n const timeout = setTimeout(async () => {\n try {\n const octokit = new Octokit({ auth: githubToken.token });\n const response = await octokit.request('GET /gists/{gist_id}', {\n gist_id: gistId,\n });\n setGistUrl(response.data.html_url);\n } catch (err) {\n log.catch(err);\n setGistUrl(undefined);\n }\n });\n\n return () => clearTimeout(timeout);\n }, [githubToken, gistKey]);\n\n const [binding, setBinding] = useControlledValue(fn?.binding ?? '');\n const handleBindingChange = useCallback(\n (event: ChangeEvent<HTMLInputElement>) => {\n setBinding(event.target.value);\n },\n [setBinding],\n );\n const handleBindingBlur = useCallback(() => {\n fn.binding = binding;\n }, [fn, binding]);\n\n const functionPath = fn && getUserFunctionUrlInMetadata(getMeta(fn));\n const functionUrl =\n functionPath &&\n getInvocationUrl(functionPath, client.config.values.runtime?.services?.edge?.url ?? '', {\n spaceId: space?.id,\n });\n\n const handleOpenTokenManager = useCallback(\n () => dispatch(createIntent(SettingsAction.Open, { plugin: 'dxos.org/plugin/token-manager' })),\n [],\n );\n\n const [publishing, setPublishing] = useState(false);\n const handlePublish = useCallback(async () => {\n setPublishing(true);\n const octokit = new Octokit({ auth: githubToken.token });\n const source = await script.source.load();\n const filename = script.name ? kebabize(script.name) : 'composer-script';\n const files = { [`${filename}.ts`]: { content: source.content } };\n\n try {\n // TODO(wittjosiah): Factor out to intent.\n const meta = getMeta(script);\n const githubKey = meta.keys.find(({ source }) => source === 'github.com');\n const gistId = githubKey?.id;\n if (gistId) {\n await octokit.request('PATCH /gists/{gist_id}', {\n gist_id: gistId,\n files,\n });\n } else {\n const response = await octokit.request('POST /gists', {\n public: true,\n files,\n });\n if (response.data.id) {\n meta.keys.push({ source: 'github.com', id: response.data.id });\n }\n }\n } finally {\n setPublishing(false);\n }\n }, [script, githubToken]);\n\n return (\n <>\n <div role='form' className='flex flex-col w-full p-2 gap-4'>\n <Input.Root>\n <div role='none' className='flex flex-col gap-1'>\n <Input.Label>{t('description label')}</Input.Label>\n <Input.TextInput\n placeholder={t('description placeholder')}\n value={script.description ?? ''}\n onChange={(event) => {\n script.description = event.target.value;\n }}\n />\n </div>\n </Input.Root>\n </div>\n {fn && functionUrl && (\n <>\n <Separator />\n <div role='form' className='flex flex-col w-full p-2 gap-4'>\n <h2>{t('remote function settings heading')}</h2>\n <Input.Root>\n <div role='none' className='flex flex-col gap-1'>\n <Input.Label>{t('function url label')}</Input.Label>\n <div role='none' className='flex gap-1'>\n <Input.TextInput\n disabled\n value={functionUrl}\n onChange={(event) => {\n fn.name = event.target.value;\n }}\n />\n <Clipboard.IconButton value={functionUrl} />\n </div>\n </div>\n </Input.Root>\n <Input.Root>\n <div role='none' className='flex flex-col gap-1'>\n <Input.Label>{t('function binding label')}</Input.Label>\n <Input.TextInput\n placeholder={t('function binding placeholder')}\n value={binding}\n onChange={handleBindingChange}\n onBlur={handleBindingBlur}\n />\n </div>\n </Input.Root>\n </div>\n </>\n )}\n <Separator />\n <div className='flex flex-col w-full p-2 gap-4'>\n <div>\n <h2>{t('script publish settings label')}</h2>\n <p className='text-description text-sm'>{t('script publish settings description')}</p>\n </div>\n {!githubToken && (\n <div className='flex flex-col items-center justify-center gap-2'>\n <span>{t('no github token label')}</span>\n <Button onClick={handleOpenTokenManager}>{t('open token manager label')}</Button>\n </div>\n )}\n {githubToken && (\n <div className='flex justify-end gap-2'>\n {gistUrl && <Clipboard.IconButton value={gistUrl} />}\n <Button disabled={publishing} onClick={handlePublish}>\n {t(publishing ? 'publishing label' : 'publish label')}\n </Button>\n </div>\n )}\n </div>\n </>\n );\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { lazy } from 'react';\n\nexport * from './ScriptSettings';\nexport * from './ScriptSettingsPanel';\n\nexport const AutomationPanel = lazy(() => import('./AutomationPanel'));\nexport const ScriptContainer = lazy(() => import('./ScriptContainer'));\n"],
4
+ "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport React from 'react';\n\nimport { type Credential } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { useClient } from '@dxos/react-client';\nimport { Button, Select, useTranslation } from '@dxos/react-ui';\nimport { type EditorInputMode, EditorInputModes } from '@dxos/react-ui-editor';\nimport { DeprecatedFormContainer, DeprecatedFormInput } from '@dxos/react-ui-form';\n\nimport { SCRIPT_PLUGIN } from '../../meta';\nimport { type ScriptSettingsProps } from '../../types';\n\nexport const ScriptSettings = ({ settings }: { settings: ScriptSettingsProps }) => {\n const { t } = useTranslation(SCRIPT_PLUGIN);\n const client = useClient();\n\n // TODO(burdon): Check token.\n const handleAuthenticate = async () => {\n const { identityKey } = client.halo.identity.get()!;\n await client.halo.writeCredentials([\n {\n issuer: identityKey,\n issuanceDate: new Date(),\n subject: {\n id: identityKey,\n assertion: {\n '@type': 'dxos.halo.credentials.ServiceAccess',\n serverName: 'hub.dxos.network',\n serverKey: identityKey,\n identityKey,\n capabilities: ['composer:beta'],\n },\n },\n } satisfies Credential,\n ]);\n };\n\n return (\n <DeprecatedFormContainer>\n {/* TODO(wittjosiah): Hide outside of dev environments. */}\n <DeprecatedFormInput label={t('authenticate action label')}>\n <Button onClick={handleAuthenticate}>{t('authenticate button label')}</Button>\n </DeprecatedFormInput>\n\n <DeprecatedFormInput label={t('editor input mode label')}>\n <Select.Root\n value={settings.editorInputMode ?? 'default'}\n onValueChange={(value) => {\n settings.editorInputMode = value as EditorInputMode;\n }}\n >\n <Select.TriggerButton placeholder={t('select editor input mode placeholder')} />\n <Select.Portal>\n <Select.Content>\n <Select.Viewport>\n {EditorInputModes.map((mode) => (\n <Select.Option key={mode} value={mode}>\n {t(`settings editor input mode ${mode} label`)}\n </Select.Option>\n ))}\n </Select.Viewport>\n </Select.Content>\n </Select.Portal>\n </Select.Root>\n </DeprecatedFormInput>\n </DeprecatedFormContainer>\n );\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { Octokit } from '@octokit/core';\nimport React, { type ChangeEvent, useCallback, useEffect, useState } from 'react';\n\nimport { createIntent, SettingsAction, useIntentDispatcher } from '@dxos/app-framework';\nimport { FunctionType, type ScriptType, getInvocationUrl, getUserFunctionUrlInMetadata } from '@dxos/functions';\nimport { log } from '@dxos/log';\nimport { useClient } from '@dxos/react-client';\nimport { Filter, getMeta, getSpace, useQuery } from '@dxos/react-client/echo';\nimport { Button, Clipboard, Input, Separator, useControlledState, useTranslation } from '@dxos/react-ui';\nimport { AccessTokenType } from '@dxos/schema';\n\nimport { SCRIPT_PLUGIN } from '../meta';\n\n// TODO(wittjosiah): Factor out.\n// From https://stackoverflow.com/a/67243723/2804332\nconst kebabize = (str: string) => str.replace(/[A-Z]+(?![a-z])|[A-Z]/g, ($, ofs) => (ofs ? '-' : '') + $.toLowerCase());\n\nexport type ScriptSettingsPanelProps = {\n script: ScriptType;\n};\n\nexport const ScriptSettingsPanel = ({ script }: ScriptSettingsPanelProps) => {\n const { t } = useTranslation(SCRIPT_PLUGIN);\n const { dispatchPromise: dispatch } = useIntentDispatcher();\n const client = useClient();\n const space = getSpace(script);\n const [fn] = useQuery(space, Filter.schema(FunctionType, { source: script }));\n const [githubToken] = useQuery(space, Filter.schema(AccessTokenType, { source: 'github.com' }));\n const gistKey = getMeta(script).keys.find(({ source }) => source === 'github.com');\n const [gistUrl, setGistUrl] = useState<string | undefined>();\n\n useEffect(() => {\n const token = githubToken?.token;\n const gistId = gistKey?.id;\n if (!token || !gistId) {\n setGistUrl(undefined);\n return;\n }\n\n const timeout = setTimeout(async () => {\n try {\n const octokit = new Octokit({ auth: githubToken.token });\n const response = await octokit.request('GET /gists/{gist_id}', {\n gist_id: gistId,\n });\n setGistUrl(response.data.html_url);\n } catch (err) {\n log.catch(err);\n setGistUrl(undefined);\n }\n });\n\n return () => clearTimeout(timeout);\n }, [githubToken, gistKey]);\n\n const [binding, setBinding] = useControlledState(fn?.binding ?? '');\n const handleBindingChange = useCallback(\n (event: ChangeEvent<HTMLInputElement>) => {\n setBinding(event.target.value);\n },\n [setBinding],\n );\n const handleBindingBlur = useCallback(() => {\n fn.binding = binding;\n }, [fn, binding]);\n\n const functionPath = fn && getUserFunctionUrlInMetadata(getMeta(fn));\n const functionUrl =\n functionPath &&\n getInvocationUrl(functionPath, client.config.values.runtime?.services?.edge?.url ?? '', {\n spaceId: space?.id,\n });\n\n const handleOpenTokenManager = useCallback(\n () => dispatch(createIntent(SettingsAction.Open, { plugin: 'dxos.org/plugin/token-manager' })),\n [],\n );\n\n const [publishing, setPublishing] = useState(false);\n const handlePublish = useCallback(async () => {\n setPublishing(true);\n const octokit = new Octokit({ auth: githubToken.token });\n const source = await script.source.load();\n const filename = script.name ? kebabize(script.name) : 'composer-script';\n const files = { [`${filename}.ts`]: { content: source.content } };\n\n try {\n // TODO(wittjosiah): Factor out to intent.\n const meta = getMeta(script);\n const githubKey = meta.keys.find(({ source }) => source === 'github.com');\n const gistId = githubKey?.id;\n if (gistId) {\n await octokit.request('PATCH /gists/{gist_id}', {\n gist_id: gistId,\n files,\n });\n } else {\n const response = await octokit.request('POST /gists', {\n public: true,\n files,\n });\n if (response.data.id) {\n meta.keys.push({ source: 'github.com', id: response.data.id });\n }\n }\n } finally {\n setPublishing(false);\n }\n }, [script, githubToken]);\n\n return (\n <>\n <div role='form' className='flex flex-col w-full p-2 gap-4'>\n <Input.Root>\n <div role='none' className='flex flex-col gap-1'>\n <Input.Label>{t('description label')}</Input.Label>\n <Input.TextInput\n placeholder={t('description placeholder')}\n value={script.description ?? ''}\n onChange={(event) => {\n script.description = event.target.value;\n }}\n />\n </div>\n </Input.Root>\n </div>\n {fn && functionUrl && (\n <>\n <Separator />\n <div role='form' className='flex flex-col w-full p-2 gap-4'>\n <h2>{t('remote function settings heading')}</h2>\n <Input.Root>\n <div role='none' className='flex flex-col gap-1'>\n <Input.Label>{t('function url label')}</Input.Label>\n <div role='none' className='flex gap-1'>\n <Input.TextInput\n disabled\n value={functionUrl}\n onChange={(event) => {\n fn.name = event.target.value;\n }}\n />\n <Clipboard.IconButton value={functionUrl} />\n </div>\n </div>\n </Input.Root>\n <Input.Root>\n <div role='none' className='flex flex-col gap-1'>\n <Input.Label>{t('function binding label')}</Input.Label>\n <Input.TextInput\n placeholder={t('function binding placeholder')}\n value={binding}\n onChange={handleBindingChange}\n onBlur={handleBindingBlur}\n />\n </div>\n </Input.Root>\n </div>\n </>\n )}\n <Separator />\n <div className='flex flex-col w-full p-2 gap-4'>\n <div>\n <h2>{t('script publish settings label')}</h2>\n <p className='text-description text-sm'>{t('script publish settings description')}</p>\n </div>\n {!githubToken && (\n <div className='flex flex-col items-center justify-center gap-2'>\n <span>{t('no github token label')}</span>\n <Button onClick={handleOpenTokenManager}>{t('open token manager label')}</Button>\n </div>\n )}\n {githubToken && (\n <div className='flex justify-end gap-2'>\n {gistUrl && <Clipboard.IconButton value={gistUrl} />}\n <Button disabled={publishing} onClick={handlePublish}>\n {t(publishing ? 'publishing label' : 'publish label')}\n </Button>\n </div>\n )}\n </div>\n </>\n );\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { lazy } from 'react';\n\nexport * from './ScriptSettings';\nexport * from './ScriptSettingsPanel';\n\nexport const AutomationPanel = lazy(() => import('./AutomationPanel'));\n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IAAOC,SAASrC;KAAyBhE,EAAE,0BAAA,CAAA,CAAA,GAG/CgB,eACC,gBAAAiE,OAAA,cAACC,OAAAA;IAAIE,WAAU;KACZ9D,WAAW,gBAAA2D,OAAA,cAACc,UAAUC,YAAU;IAAC7C,OAAO7B;MACzC,gBAAA2D,OAAA,cAACmB,SAAAA;IAAON,UAAUzB;IAAYgC,SAAS9B;KACpCvE,EAAEqE,aAAa,qBAAqB,eAAA,CAAA,CAAA,CAAA,CAAA;AAOnD;;;ACvLA,SAASiC,YAAY;AAKd,IAAMC,kBAAkBC,KAAK,MAAM,OAAO,gCAAA,CAAA;AAC1C,IAAMC,kBAAkBD,KAAK,MAAM,OAAO,gCAAA,CAAA;",
6
- "names": ["React", "useClient", "Button", "Select", "useTranslation", "EditorInputModes", "DeprecatedFormContainer", "DeprecatedFormInput", "ScriptSettings", "settings", "t", "useTranslation", "SCRIPT_PLUGIN", "client", "useClient", "handleAuthenticate", "identityKey", "halo", "identity", "get", "writeCredentials", "issuer", "issuanceDate", "Date", "subject", "id", "assertion", "serverName", "serverKey", "capabilities", "DeprecatedFormContainer", "DeprecatedFormInput", "label", "Button", "onClick", "Select", "Root", "value", "editorInputMode", "onValueChange", "TriggerButton", "placeholder", "Portal", "Content", "Viewport", "EditorInputModes", "map", "mode", "Option", "key", "Octokit", "React", "useCallback", "useEffect", "useState", "createIntent", "SettingsAction", "useIntentDispatcher", "FunctionType", "getInvocationUrl", "getUserFunctionUrlInMetadata", "log", "useClient", "Filter", "getMeta", "getSpace", "useQuery", "Button", "Clipboard", "Input", "Separator", "useControlledValue", "useTranslation", "AccessTokenType", "kebabize", "str", "replace", "$", "ofs", "toLowerCase", "ScriptSettingsPanel", "script", "t", "useTranslation", "SCRIPT_PLUGIN", "dispatchPromise", "dispatch", "useIntentDispatcher", "client", "useClient", "space", "getSpace", "fn", "useQuery", "Filter", "schema", "FunctionType", "source", "githubToken", "AccessTokenType", "gistKey", "getMeta", "keys", "find", "gistUrl", "setGistUrl", "useState", "useEffect", "token", "gistId", "id", "undefined", "timeout", "setTimeout", "octokit", "Octokit", "auth", "response", "request", "gist_id", "data", "html_url", "err", "log", "catch", "clearTimeout", "binding", "setBinding", "useControlledValue", "handleBindingChange", "useCallback", "event", "target", "value", "handleBindingBlur", "functionPath", "getUserFunctionUrlInMetadata", "functionUrl", "getInvocationUrl", "config", "values", "runtime", "services", "edge", "url", "spaceId", "handleOpenTokenManager", "createIntent", "SettingsAction", "Open", "plugin", "publishing", "setPublishing", "handlePublish", "load", "filename", "name", "files", "content", "meta", "githubKey", "public", "push", "React", "div", "role", "className", "Input", "Root", "Label", "TextInput", "placeholder", "description", "onChange", "Separator", "h2", "disabled", "Clipboard", "IconButton", "onBlur", "p", "span", "Button", "onClick", "lazy", "AutomationPanel", "lazy", "ScriptContainer"]
6
+ "names": ["React", "useClient", "Button", "Select", "useTranslation", "EditorInputModes", "DeprecatedFormContainer", "DeprecatedFormInput", "ScriptSettings", "settings", "t", "useTranslation", "SCRIPT_PLUGIN", "client", "useClient", "handleAuthenticate", "identityKey", "halo", "identity", "get", "writeCredentials", "issuer", "issuanceDate", "Date", "subject", "id", "assertion", "serverName", "serverKey", "capabilities", "DeprecatedFormContainer", "DeprecatedFormInput", "label", "Button", "onClick", "Select", "Root", "value", "editorInputMode", "onValueChange", "TriggerButton", "placeholder", "Portal", "Content", "Viewport", "EditorInputModes", "map", "mode", "Option", "key", "Octokit", "React", "useCallback", "useEffect", "useState", "createIntent", "SettingsAction", "useIntentDispatcher", "FunctionType", "getInvocationUrl", "getUserFunctionUrlInMetadata", "log", "useClient", "Filter", "getMeta", "getSpace", "useQuery", "Button", "Clipboard", "Input", "Separator", "useControlledState", "useTranslation", "AccessTokenType", "kebabize", "str", "replace", "$", "ofs", "toLowerCase", "ScriptSettingsPanel", "script", "t", "useTranslation", "SCRIPT_PLUGIN", "dispatchPromise", "dispatch", "useIntentDispatcher", "client", "useClient", "space", "getSpace", "fn", "useQuery", "Filter", "schema", "FunctionType", "source", "githubToken", "AccessTokenType", "gistKey", "getMeta", "keys", "find", "gistUrl", "setGistUrl", "useState", "useEffect", "token", "gistId", "id", "undefined", "timeout", "setTimeout", "octokit", "Octokit", "auth", "response", "request", "gist_id", "data", "html_url", "err", "log", "catch", "clearTimeout", "binding", "setBinding", "useControlledState", "handleBindingChange", "useCallback", "event", "target", "value", "handleBindingBlur", "functionPath", "getUserFunctionUrlInMetadata", "functionUrl", "getInvocationUrl", "config", "values", "runtime", "services", "edge", "url", "spaceId", "handleOpenTokenManager", "createIntent", "SettingsAction", "Open", "plugin", "publishing", "setPublishing", "handlePublish", "load", "filename", "name", "files", "content", "meta", "githubKey", "public", "push", "React", "div", "role", "className", "Input", "Root", "Label", "TextInput", "placeholder", "description", "onChange", "Separator", "h2", "disabled", "Clipboard", "IconButton", "onBlur", "p", "span", "Button", "onClick", "lazy", "AutomationPanel", "lazy", "ScriptContainer"]
7
7
  }
@@ -1,7 +1,4 @@
1
1
  import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
- import {
3
- initializeBundler
4
- } from "./chunk-G76M6O46.mjs";
5
2
  import {
6
3
  ScriptCapabilities
7
4
  } from "./chunk-CP5LXTK5.mjs";
@@ -10,6 +7,7 @@ import "./chunk-P2V2Y5LV.mjs";
10
7
  // packages/plugins/experimental/plugin-script/src/capabilities/compiler.ts
11
8
  import wasmUrl from "esbuild-wasm/esbuild.wasm?url";
12
9
  import { contributes } from "@dxos/app-framework";
10
+ import { initializeBundler } from "@dxos/functions/bundler";
13
11
 
14
12
  // packages/plugins/experimental/plugin-script/src/compiler/compiler.ts
15
13
  import { createDefaultMapFromCDN, createSystem, createVirtualTypeScriptEnvironment } from "@typescript/vfs";
@@ -82,4 +80,4 @@ var compiler_default = async () => {
82
80
  export {
83
81
  compiler_default as default
84
82
  };
85
- //# sourceMappingURL=compiler-PDN46H4Y.mjs.map
83
+ //# sourceMappingURL=compiler-XTXFGZJM.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/capabilities/compiler.ts", "../../../src/compiler/compiler.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport wasmUrl from 'esbuild-wasm/esbuild.wasm?url';\n\nimport { contributes } from '@dxos/app-framework';\nimport { initializeBundler } from '@dxos/functions/bundler';\n\nimport { ScriptCapabilities } from './capabilities';\nimport { Compiler } from '../compiler';\n\nexport default async () => {\n const compiler = new Compiler();\n\n await compiler.initialize();\n // TODO(wittjosiah): Fetch types for https modules.\n compiler.setFile('/src/typings.d.ts', \"declare module 'https://*';\");\n // TODO(wittjosiah): Proper function handler types.\n // TODO(wittjosiah): Remove.\n compiler.setFile(\n '/src/runtime.ts',\n `\n export const Filter: any = {};\n export type FunctionHandler = ({ event, context }: { event: any; context: any }) => Promise<Response>;\n export const functionHandler = (handler: FunctionHandler) => handler;\n `,\n );\n await initializeBundler({ wasmUrl });\n\n return contributes(ScriptCapabilities.Compiler, compiler);\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport {\n createDefaultMapFromCDN,\n createSystem,\n createVirtualTypeScriptEnvironment,\n type VirtualTypeScriptEnvironment,\n} from '@typescript/vfs';\nimport ts from 'typescript';\n\nimport { invariant } from '@dxos/invariant';\n\nconst defaultOptions: ts.CompilerOptions = {\n lib: ['DOM', 'es2022'],\n target: ts.ScriptTarget.ES2022,\n};\n\nexport class Compiler {\n private _env: VirtualTypeScriptEnvironment | undefined;\n private _fsMap: Map<string, string> | undefined;\n\n constructor(private readonly _options: ts.CompilerOptions = defaultOptions) {}\n\n async initialize() {\n if (this._env) {\n return;\n }\n\n // TODO(wittjosiah): Figure out how to get workers working in plugin packages.\n // https://github.com/val-town/codemirror-ts?tab=readme-ov-file#setup-worker\n this._fsMap = await createDefaultMapFromCDN(this._options, '5.5.4', true, ts);\n const system = createSystem(this._fsMap);\n this._env = createVirtualTypeScriptEnvironment(system, [], ts, this._options);\n }\n\n get environment() {\n invariant(this._env, 'Compiler environment not initialized.');\n return this._env;\n }\n\n setFile(fileName: string, content: string) {\n invariant(this._fsMap, 'File system map not initialized.');\n this.environment.createFile(fileName, content);\n }\n\n compile(fileName: string) {\n return this.environment.languageService.getEmitOutput(fileName);\n }\n}\n"],
5
+ "mappings": ";;;;;;;AAKA,OAAOA,aAAa;AAEpB,SAASC,mBAAmB;AAC5B,SAASC,yBAAyB;;;ACJlC,SACEC,yBACAC,cACAC,0CAEK;AACP,OAAOC,QAAQ;AAEf,SAASC,iBAAiB;;AAE1B,IAAMC,iBAAqC;EACzCC,KAAK;IAAC;IAAO;;EACbC,QAAQJ,GAAGK,aAAaC;AAC1B;AAEO,IAAMC,WAAN,MAAMA;EAIXC,YAA6BC,WAA+BP,gBAAgB;SAA/CO,WAAAA;EAAgD;EAE7E,MAAMC,aAAa;AACjB,QAAI,KAAKC,MAAM;AACb;IACF;AAIA,SAAKC,SAAS,MAAMf,wBAAwB,KAAKY,UAAU,SAAS,MAAMT,EAAAA;AAC1E,UAAMa,SAASf,aAAa,KAAKc,MAAM;AACvC,SAAKD,OAAOZ,mCAAmCc,QAAQ,CAAA,GAAIb,IAAI,KAAKS,QAAQ;EAC9E;EAEA,IAAIK,cAAc;AAChBb,cAAU,KAAKU,MAAM,yCAAA;;;;;;;;;AACrB,WAAO,KAAKA;EACd;EAEAI,QAAQC,UAAkBC,SAAiB;AACzChB,cAAU,KAAKW,QAAQ,oCAAA;;;;;;;;;AACvB,SAAKE,YAAYI,WAAWF,UAAUC,OAAAA;EACxC;EAEAE,QAAQH,UAAkB;AACxB,WAAO,KAAKF,YAAYM,gBAAgBC,cAAcL,QAAAA;EACxD;AACF;;;ADrCA,IAAA,mBAAe,YAAA;AACb,QAAMM,WAAW,IAAIC,SAAAA;AAErB,QAAMD,SAASE,WAAU;AAEzBF,WAASG,QAAQ,qBAAqB,6BAAA;AAGtCH,WAASG,QACP,mBACA;;;;OAIG;AAEL,QAAMC,kBAAkB;IAAEC;EAAQ,CAAA;AAElC,SAAOC,YAAYC,mBAAmBN,UAAUD,QAAAA;AAClD;",
6
+ "names": ["wasmUrl", "contributes", "initializeBundler", "createDefaultMapFromCDN", "createSystem", "createVirtualTypeScriptEnvironment", "ts", "invariant", "defaultOptions", "lib", "target", "ScriptTarget", "ES2022", "Compiler", "constructor", "_options", "initialize", "_env", "_fsMap", "system", "environment", "setFile", "fileName", "content", "createFile", "compile", "languageService", "getEmitOutput", "compiler", "Compiler", "initialize", "setFile", "initializeBundler", "wasmUrl", "contributes", "ScriptCapabilities"]
7
+ }
@@ -1,14 +1,10 @@
1
1
  import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
- import {
3
- Bundler,
4
- initializeBundler
5
- } from "./chunk-G76M6O46.mjs";
6
2
  import {
7
3
  AutomationPanel,
8
4
  ScriptContainer,
9
5
  ScriptSettings,
10
6
  ScriptSettingsPanel
11
- } from "./chunk-PRGBYF4B.mjs";
7
+ } from "./chunk-YGA2AFHL.mjs";
12
8
  import {
13
9
  ScriptCapabilities
14
10
  } from "./chunk-CP5LXTK5.mjs";
@@ -22,10 +18,11 @@ import {
22
18
 
23
19
  // packages/plugins/experimental/plugin-script/src/capabilities/index.ts
24
20
  import { lazy } from "@dxos/app-framework";
25
- var Compiler = lazy(() => import("./compiler-PDN46H4Y.mjs"));
21
+ var Compiler = lazy(() => import("./compiler-XTXFGZJM.mjs"));
26
22
  var IntentResolver = lazy(() => import("./intent-resolver-75BHFRUK.mjs"));
27
- var ReactSurface = lazy(() => import("./react-surface-PKUVZH4S.mjs"));
23
+ var ReactSurface = lazy(() => import("./react-surface-BNC2OM5X.mjs"));
28
24
  var ScriptSettings2 = lazy(() => import("./settings-GR4O2WHZ.mjs"));
25
+ var Artifact = lazy(() => import("./artifact-IX4ZCTUF.mjs"));
29
26
 
30
27
  // packages/plugins/experimental/plugin-script/src/ScriptPlugin.tsx
31
28
  import { Capabilities, contributes, createIntent, defineModule, definePlugin, Events } from "@dxos/app-framework";
@@ -147,18 +144,21 @@ var ScriptPlugin = () => definePlugin(meta, [
147
144
  id: `${meta.id}/module/intent-resolver`,
148
145
  activatesOn: Events.SetupIntents,
149
146
  activate: IntentResolver
147
+ }),
148
+ defineModule({
149
+ id: `${meta.id}/module/artifact`,
150
+ activatesOn: Events.Startup,
151
+ activate: Artifact
150
152
  })
151
153
  ]);
152
154
  export {
153
155
  AutomationPanel,
154
- Bundler,
155
156
  SCRIPT_PLUGIN,
156
157
  ScriptCapabilities,
157
158
  ScriptContainer,
158
159
  ScriptPlugin,
159
160
  ScriptSettings,
160
161
  ScriptSettingsPanel,
161
- initializeBundler,
162
162
  meta
163
163
  };
164
164
  //# sourceMappingURL=index.mjs.map