@dxos/plugin-script 0.8.3 → 0.8.4-main.f9ba587

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 (126) hide show
  1. package/dist/lib/browser/DeploymentDialog-RIGSJM6A.mjs +12 -0
  2. package/dist/lib/browser/{ScriptContainer-RSN52NH7.mjs → ScriptContainer-BAN4WZHG.mjs} +9 -9
  3. package/dist/lib/browser/{app-graph-builder-5Z3MUX4N.mjs → app-graph-builder-HLQ7K3BT.mjs} +3 -3
  4. package/dist/lib/browser/{artifact-definition-A4TBQL75.mjs → artifact-definition-KMBAZFRR.mjs} +4 -4
  5. package/dist/lib/browser/{chunk-YSQMXTYO.mjs → chunk-5TVBECWH.mjs} +3 -3
  6. package/dist/lib/browser/{chunk-3FU4QZVP.mjs → chunk-7CIKV2MG.mjs} +13 -13
  7. package/dist/lib/browser/{chunk-3FU4QZVP.mjs.map → chunk-7CIKV2MG.mjs.map} +3 -3
  8. package/dist/lib/browser/{chunk-WB3X5Z7Q.mjs → chunk-EEL5O3IC.mjs} +3 -3
  9. package/dist/lib/browser/{chunk-QJH7I2UV.mjs → chunk-OORJVKHC.mjs} +8 -8
  10. package/dist/lib/browser/{chunk-LA66DQGU.mjs → chunk-QHVTSNHD.mjs} +5 -5
  11. package/dist/lib/browser/{chunk-6ZHHWU6S.mjs → chunk-QYAREHGH.mjs} +2 -2
  12. package/dist/lib/browser/{chunk-3JLR2SHJ.mjs → chunk-QYLAH5AK.mjs} +12 -12
  13. package/dist/lib/browser/{chunk-3JLR2SHJ.mjs.map → chunk-QYLAH5AK.mjs.map} +2 -2
  14. package/dist/lib/browser/{compiler-W4BYJYTL.mjs → compiler-CXCUA4UQ.mjs} +7 -7
  15. package/dist/lib/browser/index.mjs +24 -25
  16. package/dist/lib/browser/index.mjs.map +3 -3
  17. package/dist/lib/browser/{intent-resolver-JOJNH4UX.mjs → intent-resolver-HQRUYTML.mjs} +8 -8
  18. package/dist/lib/browser/meta.json +1 -1
  19. package/dist/lib/browser/{react-surface-7BKUWL2U.mjs → react-surface-FNLARN5M.mjs} +9 -9
  20. package/dist/lib/browser/{react-surface-7BKUWL2U.mjs.map → react-surface-FNLARN5M.mjs.map} +1 -1
  21. package/dist/lib/browser/{settings-Z22D6JVJ.mjs → settings-XU54CGQD.mjs} +4 -4
  22. package/dist/lib/browser/types.mjs +2 -2
  23. package/dist/lib/node-esm/{DeploymentDialog-IA4CH6WZ.mjs → DeploymentDialog-6Z7JH3VO.mjs} +5 -5
  24. package/dist/lib/node-esm/{ScriptContainer-4IOOIPBF.mjs → ScriptContainer-RB5CSIZ7.mjs} +9 -9
  25. package/dist/lib/node-esm/{app-graph-builder-IOOUTHV2.mjs → app-graph-builder-7EYIHWH4.mjs} +3 -3
  26. package/dist/lib/node-esm/{artifact-definition-4XRYAP54.mjs → artifact-definition-EBLXG5AR.mjs} +4 -4
  27. package/dist/lib/node-esm/{chunk-2KJYPUQD.mjs → chunk-35M3CHYE.mjs} +3 -3
  28. package/dist/lib/node-esm/{chunk-MJJQBUOL.mjs → chunk-ABAPR7VQ.mjs} +8 -8
  29. package/dist/lib/node-esm/{chunk-AEB5TPEW.mjs → chunk-AHXJ6NQU.mjs} +2 -2
  30. package/dist/lib/node-esm/{chunk-B4TP3LSZ.mjs → chunk-HD6MDK3H.mjs} +12 -12
  31. package/dist/lib/node-esm/{chunk-B4TP3LSZ.mjs.map → chunk-HD6MDK3H.mjs.map} +2 -2
  32. package/dist/lib/node-esm/{chunk-W2DAXWHA.mjs → chunk-ORZMINLO.mjs} +13 -13
  33. package/dist/lib/node-esm/{chunk-W2DAXWHA.mjs.map → chunk-ORZMINLO.mjs.map} +3 -3
  34. package/dist/lib/node-esm/{chunk-UESZKXLR.mjs → chunk-OVSJYR6O.mjs} +3 -3
  35. package/dist/lib/node-esm/{chunk-T7XDCUTF.mjs → chunk-YVJGDDNV.mjs} +5 -5
  36. package/dist/lib/node-esm/{compiler-7PQ4D43R.mjs → compiler-EPFKQXPE.mjs} +7 -7
  37. package/dist/lib/node-esm/index.mjs +24 -25
  38. package/dist/lib/node-esm/index.mjs.map +3 -3
  39. package/dist/lib/node-esm/{intent-resolver-HTM5PSRZ.mjs → intent-resolver-XLV6FPWH.mjs} +8 -8
  40. package/dist/lib/node-esm/meta.json +1 -1
  41. package/dist/lib/node-esm/{react-surface-6UO64YOS.mjs → react-surface-BTYC7MGG.mjs} +9 -9
  42. package/dist/lib/node-esm/{react-surface-6UO64YOS.mjs.map → react-surface-BTYC7MGG.mjs.map} +1 -1
  43. package/dist/lib/node-esm/{settings-KZEGCDYX.mjs → settings-QCMDG2MZ.mjs} +4 -4
  44. package/dist/lib/node-esm/types.mjs +2 -2
  45. package/dist/types/src/components/DeploymentDialog/DeploymentDialog.stories.d.ts +1 -1
  46. package/dist/types/src/components/DeploymentDialog/DeploymentDialog.stories.d.ts.map +1 -1
  47. package/dist/types/src/components/ScriptToolbar/ScriptToolbar.stories.d.ts +1 -1
  48. package/dist/types/src/components/ScriptToolbar/ScriptToolbar.stories.d.ts.map +1 -1
  49. package/dist/types/src/components/TestPanel/TestContainer.d.ts +4 -3
  50. package/dist/types/src/components/TestPanel/TestContainer.d.ts.map +1 -1
  51. package/dist/types/src/components/TypescriptEditor/TypescriptEditor.stories.d.ts +1 -1
  52. package/dist/types/src/components/TypescriptEditor/TypescriptEditor.stories.d.ts.map +1 -1
  53. package/dist/types/src/hooks/template.d.ts.map +1 -1
  54. package/dist/types/src/translations.d.ts +65 -176
  55. package/dist/types/src/translations.d.ts.map +1 -1
  56. package/dist/types/tsconfig.tsbuildinfo +1 -1
  57. package/package.json +53 -55
  58. package/src/ScriptPlugin.tsx +3 -3
  59. package/src/capabilities/react-surface.tsx +2 -2
  60. package/src/components/DeploymentDialog/DeploymentDialog.stories.tsx +2 -2
  61. package/src/components/ScriptToolbar/ScriptToolbar.stories.tsx +1 -1
  62. package/src/components/TestPanel/TestContainer.tsx +6 -1
  63. package/src/components/TypescriptEditor/TypescriptEditor.stories.tsx +1 -1
  64. package/src/hooks/template.ts +2 -2
  65. package/src/templates/email.ts +2 -2
  66. package/src/translations.ts +6 -6
  67. package/dist/lib/browser/DeploymentDialog-RPPPWEEL.mjs +0 -12
  68. package/dist/lib/node/DeploymentDialog-C3EEYGRH.cjs +0 -33
  69. package/dist/lib/node/DeploymentDialog-C3EEYGRH.cjs.map +0 -7
  70. package/dist/lib/node/ScriptContainer-CAC7AISY.cjs +0 -278
  71. package/dist/lib/node/ScriptContainer-CAC7AISY.cjs.map +0 -7
  72. package/dist/lib/node/app-graph-builder-25OOTBW4.cjs +0 -80
  73. package/dist/lib/node/app-graph-builder-25OOTBW4.cjs.map +0 -7
  74. package/dist/lib/node/artifact-definition-QKZI6PTO.cjs +0 -265
  75. package/dist/lib/node/artifact-definition-QKZI6PTO.cjs.map +0 -7
  76. package/dist/lib/node/chunk-AU2FOE26.cjs +0 -369
  77. package/dist/lib/node/chunk-AU2FOE26.cjs.map +0 -7
  78. package/dist/lib/node/chunk-BUOBOT3V.cjs +0 -179
  79. package/dist/lib/node/chunk-BUOBOT3V.cjs.map +0 -7
  80. package/dist/lib/node/chunk-HCRW6T3G.cjs +0 -60
  81. package/dist/lib/node/chunk-HCRW6T3G.cjs.map +0 -7
  82. package/dist/lib/node/chunk-OSBMUJ4T.cjs +0 -580
  83. package/dist/lib/node/chunk-OSBMUJ4T.cjs.map +0 -7
  84. package/dist/lib/node/chunk-QG2X6J74.cjs +0 -52
  85. package/dist/lib/node/chunk-QG2X6J74.cjs.map +0 -7
  86. package/dist/lib/node/chunk-YO5W2IPQ.cjs +0 -251
  87. package/dist/lib/node/chunk-YO5W2IPQ.cjs.map +0 -7
  88. package/dist/lib/node/chunk-ZEV3VARQ.cjs +0 -34
  89. package/dist/lib/node/chunk-ZEV3VARQ.cjs.map +0 -7
  90. package/dist/lib/node/compiler-TFSJRLL4.cjs +0 -104
  91. package/dist/lib/node/compiler-TFSJRLL4.cjs.map +0 -7
  92. package/dist/lib/node/index.cjs +0 -225
  93. package/dist/lib/node/index.cjs.map +0 -7
  94. package/dist/lib/node/intent-resolver-BQ2NKEM7.cjs +0 -100
  95. package/dist/lib/node/intent-resolver-BQ2NKEM7.cjs.map +0 -7
  96. package/dist/lib/node/meta.json +0 -1
  97. package/dist/lib/node/react-surface-EUKPDFU3.cjs +0 -120
  98. package/dist/lib/node/react-surface-EUKPDFU3.cjs.map +0 -7
  99. package/dist/lib/node/settings-WO53FLYZ.cjs +0 -38
  100. package/dist/lib/node/settings-WO53FLYZ.cjs.map +0 -7
  101. package/dist/lib/node/types.cjs +0 -34
  102. package/dist/lib/node/types.cjs.map +0 -7
  103. /package/dist/lib/browser/{DeploymentDialog-RPPPWEEL.mjs.map → DeploymentDialog-RIGSJM6A.mjs.map} +0 -0
  104. /package/dist/lib/browser/{ScriptContainer-RSN52NH7.mjs.map → ScriptContainer-BAN4WZHG.mjs.map} +0 -0
  105. /package/dist/lib/browser/{app-graph-builder-5Z3MUX4N.mjs.map → app-graph-builder-HLQ7K3BT.mjs.map} +0 -0
  106. /package/dist/lib/browser/{artifact-definition-A4TBQL75.mjs.map → artifact-definition-KMBAZFRR.mjs.map} +0 -0
  107. /package/dist/lib/browser/{chunk-YSQMXTYO.mjs.map → chunk-5TVBECWH.mjs.map} +0 -0
  108. /package/dist/lib/browser/{chunk-WB3X5Z7Q.mjs.map → chunk-EEL5O3IC.mjs.map} +0 -0
  109. /package/dist/lib/browser/{chunk-QJH7I2UV.mjs.map → chunk-OORJVKHC.mjs.map} +0 -0
  110. /package/dist/lib/browser/{chunk-LA66DQGU.mjs.map → chunk-QHVTSNHD.mjs.map} +0 -0
  111. /package/dist/lib/browser/{chunk-6ZHHWU6S.mjs.map → chunk-QYAREHGH.mjs.map} +0 -0
  112. /package/dist/lib/browser/{compiler-W4BYJYTL.mjs.map → compiler-CXCUA4UQ.mjs.map} +0 -0
  113. /package/dist/lib/browser/{intent-resolver-JOJNH4UX.mjs.map → intent-resolver-HQRUYTML.mjs.map} +0 -0
  114. /package/dist/lib/browser/{settings-Z22D6JVJ.mjs.map → settings-XU54CGQD.mjs.map} +0 -0
  115. /package/dist/lib/node-esm/{DeploymentDialog-IA4CH6WZ.mjs.map → DeploymentDialog-6Z7JH3VO.mjs.map} +0 -0
  116. /package/dist/lib/node-esm/{ScriptContainer-4IOOIPBF.mjs.map → ScriptContainer-RB5CSIZ7.mjs.map} +0 -0
  117. /package/dist/lib/node-esm/{app-graph-builder-IOOUTHV2.mjs.map → app-graph-builder-7EYIHWH4.mjs.map} +0 -0
  118. /package/dist/lib/node-esm/{artifact-definition-4XRYAP54.mjs.map → artifact-definition-EBLXG5AR.mjs.map} +0 -0
  119. /package/dist/lib/node-esm/{chunk-2KJYPUQD.mjs.map → chunk-35M3CHYE.mjs.map} +0 -0
  120. /package/dist/lib/node-esm/{chunk-MJJQBUOL.mjs.map → chunk-ABAPR7VQ.mjs.map} +0 -0
  121. /package/dist/lib/node-esm/{chunk-AEB5TPEW.mjs.map → chunk-AHXJ6NQU.mjs.map} +0 -0
  122. /package/dist/lib/node-esm/{chunk-UESZKXLR.mjs.map → chunk-OVSJYR6O.mjs.map} +0 -0
  123. /package/dist/lib/node-esm/{chunk-T7XDCUTF.mjs.map → chunk-YVJGDDNV.mjs.map} +0 -0
  124. /package/dist/lib/node-esm/{compiler-7PQ4D43R.mjs.map → compiler-EPFKQXPE.mjs.map} +0 -0
  125. /package/dist/lib/node-esm/{intent-resolver-HTM5PSRZ.mjs.map → intent-resolver-XLV6FPWH.mjs.map} +0 -0
  126. /package/dist/lib/node-esm/{settings-KZEGCDYX.mjs.map → settings-QCMDG2MZ.mjs.map} +0 -0
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/hooks/deploy.ts", "raw-loader:./chat.ts?raw", "raw-loader:./chess.ts?raw", "raw-loader:./data-generator.ts?raw", "raw-loader:./discord.ts?raw", "raw-loader:./echo.ts?raw", "raw-loader:./email.ts?raw", "raw-loader:./forex-effect.ts?raw", "raw-loader:./forex.ts?raw", "raw-loader:./gmail.ts?raw", "../../../src/templates/index.ts", "../../../src/hooks/useToolbarState.ts", "../../../src/hooks/format.ts", "../../../src/hooks/template.ts"],
4
- "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport { useEffect, useMemo } from 'react';\n\nimport { FunctionType, type ScriptType, getUserFunctionUrlInMetadata } from '@dxos/functions';\nimport { log } from '@dxos/log';\nimport { type Client, useClient } from '@dxos/react-client';\nimport { getMeta, getSpace, Query, Ref, type Space, useQuery } from '@dxos/react-client/echo';\nimport { type TFunction } from '@dxos/react-ui';\nimport { createMenuAction } from '@dxos/react-ui-menu';\nimport { errorMessageColors } from '@dxos/react-ui-theme';\n\nimport { SCRIPT_PLUGIN } from '../meta';\nimport { deployScript, getFunctionUrl, isScriptDeployed } from '../util';\n\nexport type DeployActionProperties = { type: 'deploy' } | { type: 'copy' };\n\nexport type DeployState = {\n deploying: boolean;\n deployed: boolean;\n functionUrl: string;\n error: string;\n};\n\nexport type CreateDeployOptions = {\n state: Partial<DeployState>;\n script: ScriptType;\n fn: FunctionType;\n space?: Space;\n existingFunctionUrl?: string;\n client: Client;\n t: TFunction;\n};\n\nexport const createDeploy = ({ state, script, space, fn, client, existingFunctionUrl, t }: CreateDeployOptions) => {\n // TODO(wittjosiah): Should this be an action?\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 classNames: state.error && errorMessageColors,\n });\n\n const deployAction = createMenuAction<DeployActionProperties>(\n 'deploy',\n async () => {\n if (!script.source || !space) {\n return;\n }\n\n state.error = undefined;\n state.deploying = true;\n\n const result = await deployScript({ script, client, space, fn, existingFunctionUrl });\n\n if (!result.success) {\n log.catch(result.error);\n state.error = t('upload failed label');\n }\n\n state.deploying = false;\n },\n {\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\n const copyAction = createMenuAction<DeployActionProperties>(\n 'copy',\n async () => {\n if (!state.functionUrl) {\n return;\n }\n await navigator.clipboard.writeText(state.functionUrl);\n },\n {\n type: 'copy',\n label: ['copy link label', { ns: SCRIPT_PLUGIN }],\n icon: 'ph--link--regular',\n disabled: !state.functionUrl,\n },\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\nexport const useDeployState = ({ state, script }: { state: Partial<DeployState>; script: ScriptType }) => {\n const { space, client, fn, existingFunctionUrl } = useDeployDeps({ script });\n useEffect(() => {\n if (!existingFunctionUrl) {\n return;\n }\n\n state.functionUrl = getFunctionUrl({\n script,\n fn,\n edgeUrl: client.config.values.runtime?.services?.edge?.url ?? '',\n });\n }, [existingFunctionUrl, space, fn, script, client.config.values.runtime?.services?.edge?.url]);\n\n useEffect(() => {\n state.deployed = isScriptDeployed({ script, fn });\n }, [script.changed, existingFunctionUrl, fn, script]);\n};\n\nexport const useDeployDeps = ({ script }: { script: ScriptType }) => {\n const space = getSpace(script);\n const [fn] = useQuery(space, Query.type(FunctionType, { source: Ref.make(script) }));\n const client = useClient();\n const existingFunctionUrl = useMemo(() => fn && getUserFunctionUrlInMetadata(getMeta(fn)), [fn]);\n return { space, fn, client, existingFunctionUrl };\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\n// @ts-ignore\nimport { transformServerSentEvents } from 'https://esm.sh/@dxos/script-toolbox?bundle=false';\n\n/**\n * Chatbot that answers questions based on the context data.\n */\nexport default async ({ data: { bodyText }, context: { space, ai } }: any) => {\n let parsedRequest: any;\n try {\n parsedRequest = JSON.parse(bodyText);\n } catch (err) {\n const answer = await ai.run('@cf/meta/llama-3.1-8b-instruct', {\n stream: true,\n prompt: `\n Using only the context data below to answer the user's question.\n If you cannot answer the question from the provided content, then reply with \"I don't know.\"\n\n CONTEXT:\n ${await getContext({ space })}\n\n QUESTION:\n ${bodyText}\n `,\n });\n return new Response(transformServerSentEvents(answer));\n }\n\n const promptId = parsedRequest.trigger.promptId;\n const promptObject = await space.crud.query({ id: promptId }).first();\n\n if (parsedRequest.data.objects.length !== 1) {\n return new Response('Message batches not supported.');\n }\n\n const messageId = parsedRequest.data.objects[0];\n let message;\n try {\n message = await space.crud.query({ id: messageId }).first();\n } catch (err) {\n return new Response('Message not replicated yet.', { status: 409 });\n }\n\n if (message.text.includes('--------')) {\n return new Response('Message was already processed.');\n }\n\n let prompt = promptObject.template;\n for (const input of promptObject.inputs) {\n let value: string | null = null;\n if (input.type === TemplateInputType.VALUE) {\n value = String(input.value);\n } else if (input.type === TemplateInputType.RETRIEVER) {\n value = await getContext({ space });\n } else if (input.type === TemplateInputType.PASS_THROUGH) {\n value = message.text;\n }\n if (value) {\n prompt = prompt.replaceAll(`{${input.name}}`, value);\n }\n }\n\n const answer = await ai.run('@cf/meta/llama-3.1-8b-instruct', {\n stream: false,\n prompt,\n });\n const response = { response: answer.response, prompt, message };\n const textWithAnswer = message.text + '\\n--------\\n\\n' + answer.response;\n await space.crud.update({ id: messageId }, { text: textWithAnswer });\n\n return new Response(JSON.stringify(response));\n};\n\nconst getContext = async ({ space }: any) => {\n let context = '';\n const { objects: docs } = await space.crud.query({ __typename: 'dxos.org/type/Document' }).run();\n for (const doc of docs) {\n const { content } = await space.crud.query({ id: doc.content }).first();\n context += content + '\\n\\n';\n }\n return context;\n};\n\nenum TemplateInputType {\n VALUE = 0,\n PASS_THROUGH = 1,\n RETRIEVER = 2,\n FUNCTION = 3,\n QUERY = 4,\n RESOLVER = 5,\n CONTEXT = 6,\n SCHEMA = 7,\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S } from 'dxos:functions';\n// @ts-ignore\nimport { Chess } from 'https://esm.sh/chess.js@0.13.1?bundle=false';\n\nexport default defineFunction({\n description: 'Plays a random move in a chess game.',\n\n inputSchema: S.Struct({\n changedObjectId: S.String.annotations({\n description: 'The objects to play the game on.',\n }),\n player: S.optional(S.Literal('w', 'b')).annotations({\n description: 'The player to play the game as.',\n }),\n }),\n\n outputSchema: S.Struct({\n state: S.String.annotations({\n description: 'The state of the game as an ASCII art board.',\n }),\n }),\n\n handler: async ({ data: { changedObjectId, player = 'b' }, context: { space } }: any) => {\n const { pgn } = await space.db.query({ id: changedObjectId }).first();\n const game = new Chess();\n game.load_pgn(pgn);\n if (game.turn() !== player) {\n return new Response('Invalid turn', { status: 409 });\n }\n\n const moves = game.moves();\n const move = moves[Math.floor(Math.random() * moves.length)];\n if (!move) {\n return new Response('No legal moves', { status: 406 });\n }\n\n game.move(move);\n const newPgn = game.pgn();\n await space.db.update({ id: changedObjectId }, { pgn: newPgn, fen: game.fen() });\n return { state: game.ascii() };\n },\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S, create, Expando } from 'dxos:functions';\n// @ts-ignore\nimport { randText } from 'https://esm.sh/@ngneat/falso@7.1.1?bundle=false';\n\nexport default defineFunction({\n inputSchema: S.Struct({\n documentAmount: S.optional(S.Number),\n textSize: S.optional(S.Number),\n mutationAmount: S.optional(S.Number),\n }),\n\n outputSchema: S.Struct({}),\n\n handler: async ({ data: { documentAmount = 1, textSize = 10, mutationAmount = 0 }, context: { space } }: any) => {\n await space.db.graph.schemaRegistry.addSchema([Expando]);\n const result: Record<string, any> = {};\n const objects: Expando[] = [];\n\n // Create objects.\n for (let i = 0; i < documentAmount; i++) {\n const obj = space.db.add(\n create(Expando, {\n name: 'scriptGenerated',\n content: randText({ charCount: textSize }),\n }),\n );\n objects.push(obj);\n const objectResult: any = {};\n // Mutate the object.\n for (let i = 0; i < mutationAmount; i++) {\n obj.content = randText({ charCount: textSize });\n }\n objectResult.mutations = mutationAmount;\n objectResult.contentLength = obj.content.length;\n result[obj.id] = objectResult;\n }\n\n // Flush and wait for data to propagate.\n await space.db.flush();\n await new Promise((resolve) => setTimeout(resolve, 10_000));\n return result;\n },\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { create, defineFunction, DXN, EchoObject, Filter, ObjectId, S } from 'dxos:functions';\n// @ts-ignore\nimport { FetchHttpClient } from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.14.21&bundle=false';\nimport {\n DiscordConfig,\n DiscordREST,\n DiscordRESTMemoryLive,\n // @ts-ignore\n} from 'https://esm.sh/dfx@0.113.0?deps=effect@3.14.21&bundle=false';\n// @ts-ignore\nimport { Effect, Config, Redacted, Ref } from 'https://esm.sh/effect@3.14.21?bundle=false';\n\nconst MessageSchema = S.Struct({\n id: ObjectId,\n foreignId: S.Any, // bigint?\n from: S.String,\n created: S.String,\n content: S.String,\n}).pipe(\n EchoObject({\n typename: 'example.com/type/Message',\n version: '0.1.0',\n }),\n);\n\nconst DEFAULT_AFTER = 1704067200; // 2024-01-01\n\nconst generateSnowflake = (unixTimestamp: number): bigint => {\n const discordEpoch = 1420070400000n; // Discord Epoch (ms)\n return (BigInt(unixTimestamp * 1000) - discordEpoch) << 22n;\n};\n\nexport default defineFunction({\n inputSchema: S.Struct({\n // TODO(wittjosiah): Remove. This is used to provide a terminal for a cron trigger.\n tick: S.optional(S.String),\n channelId: S.String,\n after: S.optional(S.Number),\n pageSize: S.optional(S.Number),\n queueId: S.String,\n }),\n\n outputSchema: S.Struct({\n newMessages: S.Number,\n }),\n\n handler: ({ data: { channelId, queueId, after = DEFAULT_AFTER, pageSize = 5 }, context: { space } }: any) =>\n Effect.gen(function* () {\n const { token } = yield* Effect.tryPromise({\n try: () => space.db.query(Filter.typename('dxos.org/type/AccessToken', { source: 'discord.com' })).first(),\n catch: (e: any) => e,\n });\n const { objects } = yield* Effect.tryPromise({\n try: () => space.queues.queryQueue(DXN.parse(queueId)),\n catch: (e: any) => e,\n });\n const backfill = objects.length === 0;\n const newMessages = yield* Ref.make(0);\n const lastMessage = yield* Ref.make(objects.at(-1));\n\n const enqueueMessages = Effect.gen(function* () {\n const rest = yield* DiscordREST;\n\n while (true) {\n const last = yield* Ref.get(lastMessage);\n const options = {\n after: backfill && !last ? `${generateSnowflake(after)}` : last?.foreignId,\n limit: pageSize,\n };\n const messages = yield* rest.getChannelMessages(channelId, options).pipe((res: any) => res.json);\n const queueMessages = messages\n .map((message: any) =>\n create(MessageSchema, {\n id: ObjectId.random(),\n foreignId: message.id,\n from: message.author.username,\n created: message.timestamp,\n content: message.content,\n }),\n )\n .toReversed();\n if (queueMessages.length > 0) {\n yield* Effect.tryPromise({\n try: () => space.queues.insertIntoQueue(DXN.parse(queueId), queueMessages),\n catch: (e: any) => e,\n });\n yield* Ref.update(newMessages, (n: any) => n + queueMessages.length);\n yield* Ref.update(lastMessage, (m: any) => queueMessages.at(-1));\n }\n if (messages.length < pageSize) {\n break;\n }\n }\n }).pipe(\n Effect.provide(DiscordRESTMemoryLive),\n Effect.provide(\n DiscordConfig.layerConfig({\n token: Config.succeed(Redacted.make(token)),\n }),\n ),\n Effect.provide(FetchHttpClient.layer),\n );\n\n yield* enqueueMessages;\n return { newMessages: yield* Ref.get(newMessages) };\n }),\n});\n", "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Echos the request data.\n */\nexport default async ({ data }: any) => data;\n", "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Appends a message to the end of a Document configured through a trigger.\n * Trigger must have a targetDocumentId field set in Meta.\n */\nexport default async ({ data: { bodyText }, context: { space } }: any) => {\n const { email, targetDocumentId: documentId } = JSON.parse(bodyText) as RequestPayload;\n\n const document = await space.db.query({ id: documentId }, { format: 'plain' }).first();\n\n const contentId = document.content['/'].split(':')[3];\n const documentContent = await space.db.query({ id: contentId }, { format: 'plain' }).first();\n const modifiedContent = [\n documentContent.content,\n '',\n '---',\n `**From:** ${email.from}`,\n `**Subject:** ${email.subject}`,\n `**Date:** ${email.created}`,\n '',\n email.body,\n ].join('\\n');\n\n await space.db.update({ id: contentId }, { content: modifiedContent });\n\n return new Response(JSON.stringify({ success: true }));\n};\n\ntype RequestPayload = {\n email: { from: string; subject: string; created: string; body: string };\n targetDocumentId: string;\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { S, defineFunction } from 'dxos:functions';\nimport {\n HttpClient,\n HttpClientRequest,\n FetchHttpClient,\n // @ts-ignore\n} from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.14.21&bundle=false';\n// @ts-ignore\nimport { Effect, Schedule } from 'https://esm.sh/effect@3.14.21?bundle=false';\n\nexport 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.String.annotations({ description: 'The exchange rate between the two currencies' }),\n\n handler: async ({ data: { from, to } }: any) =>\n Effect.gen(function* () {\n const res = yield* HttpClientRequest.get(`https://free.ratesdb.com/v1/rates?from=${from}&to=${to}`).pipe(\n HttpClient.execute,\n Effect.flatMap((res: any) => res.json),\n Effect.timeout('1 second'),\n Effect.retry(Schedule.exponential(1_000).pipe(Schedule.compose(Schedule.recurs(3)))),\n Effect.scoped,\n );\n\n return res.data.rates[to].toString();\n }).pipe(Effect.provide(FetchHttpClient.layer)),\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S } from 'dxos:functions';\n\nexport 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 handler: async ({ data: { from, to } }: 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 rates[to].toString();\n },\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { create, defineFunction, EchoObject, Filter, ObjectId, S } from 'dxos:functions';\n// @ts-ignore\nimport {\n HttpClient,\n HttpClientRequest,\n FetchHttpClient,\n // @ts-ignore\n} from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.14.21&bundle=false';\n// @ts-ignore\nimport { format, subDays } from 'https://esm.sh/date-fns@3.3.1?bundle=false';\n// @ts-ignore\nimport { pipe, Chunk, Effect, Ref, Schedule, Stream } from 'https://esm.sh/effect@3.14.21?bundle=false';\n\nexport default defineFunction({\n inputSchema: S.Struct({\n mailboxId: S.String,\n userId: S.optional(S.String).pipe(S.withDecodingDefault(() => 'me')),\n after: S.optional(S.Union(S.Number, S.String)).pipe(\n S.withDecodingDefault(() => format(subDays(new Date(), 30), 'yyyy-MM-dd')),\n ),\n pageSize: S.optional(S.Number).pipe(S.withDecodingDefault(() => 100)),\n // TODO(wittjosiah): Remove. This is used to provide a terminal for a cron trigger.\n tick: S.optional(S.String),\n }),\n\n outputSchema: S.Struct({\n newMessages: S.Number,\n }),\n\n handler: ({ context: { space }, data: { mailboxId, userId, after, pageSize } }: any) =>\n Effect.gen(function* () {\n const { token } = yield* Effect.tryPromise({\n try: () => space.db.query(Filter.typename('dxos.org/type/AccessToken', { source: 'gmail.com' })).first(),\n catch: (e: any) => e,\n });\n\n // NOTE: Google API bundles size is v. large and caused runtime issues.\n const makeRequest = (url: string) =>\n pipe(\n url,\n HttpClientRequest.get,\n HttpClientRequest.setHeaders({ Authorization: `Bearer ${token}`, Accept: 'application/json' }),\n HttpClient.execute,\n Effect.flatMap((res: any) => res.json),\n Effect.timeout('1 second'),\n Effect.retry(Schedule.exponential(1000).pipe(Schedule.compose(Schedule.recurs(3)))),\n Effect.scoped,\n );\n\n const listMessages = (userId: string, q: string, pageSize: number, pageToken: string | null) =>\n makeRequest(getUrl(userId, undefined, { q, pageSize, pageToken }));\n\n const getMessage = (userId: string, messageId: string) => makeRequest(getUrl(userId, messageId));\n\n const mailbox = yield* Effect.tryPromise({\n try: () => space.db.query({ id: mailboxId }).first(),\n catch: (e: any) => e,\n });\n const { objects } = yield* Effect.tryPromise({\n try: () => space.queues.queryQueue(mailbox.queue.dxn),\n catch: (e: any) => e,\n });\n const newMessages = yield* Ref.make([]);\n const nextPage = yield* Ref.make(null);\n\n do {\n const last = objects.at(-1);\n const q = last\n ? `in:inbox after:${Math.floor(new Date(last.created).getTime() / 1000)}`\n : `in:inbox after:${after}`;\n const pageToken = yield* Ref.get(nextPage);\n const { messages, nextPageToken } = yield* listMessages(userId, q, pageSize, pageToken);\n yield* Ref.update(nextPage, () => nextPageToken);\n for (const message of messages) {\n const messageDetails = yield* getMessage(userId, message.id);\n const created = new Date(parseInt(messageDetails.internalDate)).toISOString();\n const from = messageDetails.payload.headers.find((h: any) => h.name === 'From');\n const sender = from && parseEmailString(from.value);\n // TODO(wittjosiah): Improve parsing of email contents.\n const content =\n messageDetails.payload.body?.data ??\n messageDetails.payload.parts?.find((p: any) => p.mimeType === 'text/plain')?.body.data;\n // Skip the message if content or sender is missing.\n // Skip the message if it's the same as the last message.\n // TODO(wittjosiah): This comparison should be done via foreignId probably.\n if (!content || !sender || created === last?.created) {\n continue;\n }\n const subject = messageDetails.payload.headers.find((h: any) => h.name === 'Subject')?.value;\n const object = create(MessageType, {\n id: ObjectId.random(),\n created,\n sender,\n blocks: [\n {\n type: 'text',\n text: Buffer.from(content, 'base64').toString('utf-8'),\n },\n ],\n properties: {\n subject,\n threadId: message.threadId,\n },\n });\n // TODO(wittjosiah): Set foreignId in object meta.\n yield* Ref.update(newMessages, (n: any) => [object, ...n]);\n }\n } while (yield* Ref.get(nextPage));\n\n const queueMessages = yield* Ref.get(newMessages);\n if (queueMessages.length > 0) {\n yield* pipe(\n queueMessages,\n Stream.fromIterable,\n Stream.grouped(10),\n Stream.flatMap((batch: any) =>\n Effect.tryPromise({\n try: () => space.queues.insertIntoQueue(mailbox.queue.dxn, Chunk.toReadonlyArray(batch)),\n catch: (e: any) => e,\n }),\n ),\n Stream.runDrain,\n );\n }\n\n return { newMessages: queueMessages.length };\n }).pipe(Effect.provide(FetchHttpClient.layer)),\n});\n\nconst getUrl = (userId: string, messageId?: string, params?: Record<string, any>) => {\n const api = new URL(\n [`https://gmail.googleapis.com/gmail/v1/users/${userId}/messages`, messageId].filter(Boolean).join('/'),\n );\n Object.entries(params ?? {})\n .filter(([_, value]) => value != null)\n .forEach(([key, value]) => api.searchParams.set(key, value));\n return api.toString();\n};\n\n/**\n * Parses an email string in the format \"Name <email@example.com>\" into separate name and email components.\n */\nconst parseEmailString = (emailString: string): { name?: string; email: string } | undefined => {\n const match = emailString.match(/^([^<]+?)\\s*<([^>]+@[^>]+)>$/);\n if (match) {\n const [, name, email] = match;\n return {\n name: name.trim(),\n email: email.trim(),\n };\n }\n\n return undefined;\n};\n\n//\n// Schemas\n// TODO(wittjosiah): These schemas should be imported from @dxos/S.\n//\n\nconst ActorRoles = ['user', 'assistant'] as const;\nconst ActorRole = S.Literal(...ActorRoles);\ntype ActorRole = S.Schema.Type<typeof ActorRole>;\n\nconst ActorSchema = S.Struct({\n identityKey: S.optional(S.String),\n email: S.optional(S.String),\n name: S.optional(S.String),\n role: S.optional(ActorRole),\n});\n\nconst AbstractContentBlock = S.Struct({\n pending: S.optional(S.Boolean),\n});\ntype AbstractContentBlock = S.Schema.Type<typeof AbstractContentBlock>;\nconst TextContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('text'),\n disposition: S.optional(S.String),\n text: S.String,\n }),\n).pipe(S.mutable);\ntype TextContentBlock = S.Schema.Type<typeof TextContentBlock>;\nconst JsonContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('json'),\n disposition: S.optional(S.String),\n data: S.String,\n }),\n).pipe(S.mutable);\ntype JsonContentBlock = S.Schema.Type<typeof JsonContentBlock>;\nconst Base64ImageSource = S.Struct({\n type: S.Literal('base64'),\n mediaType: S.String,\n data: S.String,\n}).pipe(S.mutable);\nconst HttpImageSource = S.Struct({\n type: S.Literal('http'),\n url: S.String,\n}).pipe(S.mutable);\nconst ImageSource = S.Union(Base64ImageSource, HttpImageSource);\ntype ImageSource = S.Schema.Type<typeof ImageSource>;\nconst ImageContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('image'),\n id: S.optional(S.String),\n source: S.optional(ImageSource),\n }),\n).pipe(S.mutable);\ntype ImageContentBlock = S.Schema.Type<typeof ImageContentBlock>;\nconst ReferenceContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('reference'),\n reference: S.Any,\n }),\n).pipe(S.mutable);\ntype ReferenceContentBlock = S.Schema.Type<typeof ReferenceContentBlock>;\nconst MessageContentBlock = S.Union(TextContentBlock, JsonContentBlock, ImageContentBlock, ReferenceContentBlock);\n\nconst MessageType = S.Struct({\n id: ObjectId,\n created: S.String.annotations({\n description: 'ISO date string when the message was sent.',\n }),\n sender: ActorSchema.annotations({\n description: 'Identity of the message sender.',\n }),\n blocks: S.Array(MessageContentBlock).annotations({\n description: 'Contents of the message.',\n }),\n properties: S.optional(\n S.mutable(\n S.Record({ key: S.String, value: S.Any }).annotations({\n description: 'Custom properties for specific message types (e.g. attention context, email subject, etc.).',\n }),\n ),\n ),\n}).pipe(\n EchoObject({\n typename: 'dxos.org/type/Message',\n version: '0.2.0',\n }),\n);\ntype MessageType = S.Schema.Type<typeof MessageType>;\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport chat from './chat.ts?raw';\nimport chess from './chess.ts?raw';\nimport dataGenerator from './data-generator.ts?raw';\nimport discord from './discord.ts?raw';\nimport echo from './echo.ts?raw';\nimport email from './email.ts?raw';\nimport forexEffect from './forex-effect.ts?raw';\nimport forex from './forex.ts?raw';\nimport gmail from './gmail.ts?raw';\n\nconst removeHeader = (str: string) => str.split('\\n').slice(4).join('\\n');\n\nexport type Template = {\n id: string;\n name: string;\n source: string;\n presetId?: string;\n};\n\nexport const templates: Template[] = [\n {\n id: 'dxos.org/script/echo',\n name: 'Echo',\n source: removeHeader(echo),\n },\n {\n id: 'dxos.org/script/forex',\n name: 'Forex',\n source: removeHeader(forex),\n },\n {\n id: 'dxos.org/script/forex-effect',\n name: 'Forex (Effect)',\n source: removeHeader(forexEffect),\n },\n {\n id: 'dxos.org/script/gpt',\n name: 'Gpt',\n source: removeHeader(chat),\n presetId: 'dxos.org/function/gpt',\n },\n {\n id: 'dxos.org/script/chess',\n name: 'Chess',\n source: removeHeader(chess),\n presetId: 'dxos.org/function/chess',\n },\n {\n id: 'dxos.org/script/email',\n name: 'Email',\n source: removeHeader(email),\n presetId: 'dxos.org/function/email',\n },\n {\n id: 'dxos.org/script/discord',\n name: 'Discord',\n source: removeHeader(discord),\n presetId: 'dxos.org/function/discord',\n },\n {\n id: 'dxos.org/script/gmail',\n name: 'Gmail',\n source: removeHeader(gmail),\n presetId: 'dxos.org/function/gmail',\n },\n {\n id: 'dxos.org/script/data-generator',\n name: 'Data Generator',\n source: removeHeader(dataGenerator),\n presetId: 'dxos.org/function/data-generator',\n },\n];\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { useMemo } from 'react';\n\nimport { live } from '@dxos/live-object';\n\nimport { type DeployState } from './deploy';\n\nexport type ScriptToolbarState = Partial<DeployState>;\n\n// TODO(burdon): Replace with context provider?\nexport const useToolbarState = (initialState: ScriptToolbarState = {}) => {\n return useMemo(() => live<ScriptToolbarState>(initialState), []);\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { format } from 'prettier';\nimport prettierPluginEstree from 'prettier/plugins/estree';\nimport prettierPluginTypescript from 'prettier/plugins/typescript';\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 = (script: ScriptType) => {\n const formatAction = createMenuAction(\n 'format',\n 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 },\n {\n label: ['format label', { ns: SCRIPT_PLUGIN }],\n icon: 'ph--magic-wand--regular',\n },\n );\n\n return {\n nodes: [formatAction],\n edges: [\n {\n source: 'root',\n target: 'format',\n },\n ],\n };\n};\n", "//\n// Copyright 2025 DXOS.org\n//\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 = (script: ScriptType) => {\n return templates.map((template) => {\n return createMenuAction<TemplateActionProperties>(\n `template--${template.id}`,\n () => {\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 label: template.name,\n value: template.id,\n type: 'template',\n },\n );\n });\n};\n\nexport const createTemplateSelect = (script: ScriptType) => {\n const templateSelectGroup = createTemplateSelectGroup();\n const templateSelectActions = createTemplateSelectActions(script);\n return {\n nodes: [templateSelectGroup, ...templateSelectActions],\n edges: [\n { source: 'root', target: 'template-select' },\n ...templateSelectActions.map((action) => ({ source: 'template-select', target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jB,SAASE;MAChBgB,MAAM;IACR,CAAA;EAEJ,CAAA;AACF;AAEO,IAAMC,uBAAuB,CAACtB,WAAAA;AACnC,QAAMuB,sBAAsB9B,0BAAAA;AAC5B,QAAM+B,wBAAwBzB,4BAA4BC,MAAAA;AAC1D,SAAO;IACLyB,OAAO;MAACF;SAAwBC;;IAChCE,OAAO;MACL;QAAEnB,QAAQ;QAAQC,QAAQ;MAAkB;SACzCgB,sBAAsBtB,IAAI,CAACyB,YAAY;QAAEpB,QAAQ;QAAmBC,QAAQmB,OAAOtB;MAAG,EAAA;;EAE7F;AACF;",
6
- "names": ["useEffect", "useMemo", "FunctionType", "getUserFunctionUrlInMetadata", "log", "useClient", "getMeta", "getSpace", "Query", "Ref", "useQuery", "createMenuAction", "errorMessageColors", "createDeploy", "state", "script", "space", "fn", "client", "existingFunctionUrl", "t", "errorItem", "createMenuAction", "label", "error", "ns", "SCRIPT_PLUGIN", "icon", "hidden", "classNames", "errorMessageColors", "deployAction", "source", "undefined", "deploying", "result", "deployScript", "success", "log", "catch", "type", "disabled", "copyAction", "functionUrl", "navigator", "clipboard", "writeText", "nodes", "edges", "target", "useDeployState", "useDeployDeps", "useEffect", "getFunctionUrl", "edgeUrl", "config", "values", "runtime", "services", "edge", "url", "deployed", "isScriptDeployed", "changed", "getSpace", "useQuery", "Query", "FunctionType", "Ref", "make", "useClient", "useMemo", "getUserFunctionUrlInMetadata", "getMeta", "removeHeader", "str", "split", "slice", "join", "templates", "id", "name", "source", "echo", "forex", "forexEffect", "chat", "presetId", "chess", "email", "discord", "gmail", "dataGenerator", "useMemo", "live", "useToolbarState", "initialState", "useMemo", "live", "format", "prettierPluginEstree", "prettierPluginTypescript", "log", "createMenuAction", "createFormat", "script", "formatAction", "createMenuAction", "source", "target", "content", "format", "parser", "plugins", "prettierPluginEstree", "prettierPluginTypescript", "semi", "singleQuote", "err", "log", "catch", "label", "ns", "SCRIPT_PLUGIN", "icon", "nodes", "edges", "FUNCTIONS_PRESET_META_KEY", "getMeta", "createMenuItemGroup", "createMenuAction", "createTemplateSelectGroup", "createMenuItemGroup", "label", "ns", "SCRIPT_PLUGIN", "variant", "createTemplateSelectActions", "script", "templates", "map", "template", "createMenuAction", "id", "name", "source", "target", "content", "metaKeys", "getMeta", "keys", "oldPresetIndex", "findIndex", "key", "FUNCTIONS_PRESET_META_KEY", "splice", "presetId", "push", "value", "type", "createTemplateSelect", "templateSelectGroup", "templateSelectActions", "nodes", "edges", "action"]
4
+ "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport { useEffect, useMemo } from 'react';\n\nimport { FunctionType, type ScriptType, getUserFunctionUrlInMetadata } from '@dxos/functions';\nimport { log } from '@dxos/log';\nimport { type Client, useClient } from '@dxos/react-client';\nimport { getMeta, getSpace, Query, Ref, type Space, useQuery } from '@dxos/react-client/echo';\nimport { type TFunction } from '@dxos/react-ui';\nimport { createMenuAction } from '@dxos/react-ui-menu';\nimport { errorMessageColors } from '@dxos/react-ui-theme';\n\nimport { SCRIPT_PLUGIN } from '../meta';\nimport { deployScript, getFunctionUrl, isScriptDeployed } from '../util';\n\nexport type DeployActionProperties = { type: 'deploy' } | { type: 'copy' };\n\nexport type DeployState = {\n deploying: boolean;\n deployed: boolean;\n functionUrl: string;\n error: string;\n};\n\nexport type CreateDeployOptions = {\n state: Partial<DeployState>;\n script: ScriptType;\n fn: FunctionType;\n space?: Space;\n existingFunctionUrl?: string;\n client: Client;\n t: TFunction;\n};\n\nexport const createDeploy = ({ state, script, space, fn, client, existingFunctionUrl, t }: CreateDeployOptions) => {\n // TODO(wittjosiah): Should this be an action?\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 classNames: state.error && errorMessageColors,\n });\n\n const deployAction = createMenuAction<DeployActionProperties>(\n 'deploy',\n async () => {\n if (!script.source || !space) {\n return;\n }\n\n state.error = undefined;\n state.deploying = true;\n\n const result = await deployScript({ script, client, space, fn, existingFunctionUrl });\n\n if (!result.success) {\n log.catch(result.error);\n state.error = t('upload failed label');\n }\n\n state.deploying = false;\n },\n {\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\n const copyAction = createMenuAction<DeployActionProperties>(\n 'copy',\n async () => {\n if (!state.functionUrl) {\n return;\n }\n await navigator.clipboard.writeText(state.functionUrl);\n },\n {\n type: 'copy',\n label: ['copy link label', { ns: SCRIPT_PLUGIN }],\n icon: 'ph--link--regular',\n disabled: !state.functionUrl,\n },\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\nexport const useDeployState = ({ state, script }: { state: Partial<DeployState>; script: ScriptType }) => {\n const { space, client, fn, existingFunctionUrl } = useDeployDeps({ script });\n useEffect(() => {\n if (!existingFunctionUrl) {\n return;\n }\n\n state.functionUrl = getFunctionUrl({\n script,\n fn,\n edgeUrl: client.config.values.runtime?.services?.edge?.url ?? '',\n });\n }, [existingFunctionUrl, space, fn, script, client.config.values.runtime?.services?.edge?.url]);\n\n useEffect(() => {\n state.deployed = isScriptDeployed({ script, fn });\n }, [script.changed, existingFunctionUrl, fn, script]);\n};\n\nexport const useDeployDeps = ({ script }: { script: ScriptType }) => {\n const space = getSpace(script);\n const [fn] = useQuery(space, Query.type(FunctionType, { source: Ref.make(script) }));\n const client = useClient();\n const existingFunctionUrl = useMemo(() => fn && getUserFunctionUrlInMetadata(getMeta(fn)), [fn]);\n return { space, fn, client, existingFunctionUrl };\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\n// @ts-ignore\nimport { transformServerSentEvents } from 'https://esm.sh/@dxos/script-toolbox?bundle=false';\n\n/**\n * Chatbot that answers questions based on the context data.\n */\nexport default async ({ data: { bodyText }, context: { space, ai } }: any) => {\n let parsedRequest: any;\n try {\n parsedRequest = JSON.parse(bodyText);\n } catch (err) {\n const answer = await ai.run('@cf/meta/llama-3.1-8b-instruct', {\n stream: true,\n prompt: `\n Using only the context data below to answer the user's question.\n If you cannot answer the question from the provided content, then reply with \"I don't know.\"\n\n CONTEXT:\n ${await getContext({ space })}\n\n QUESTION:\n ${bodyText}\n `,\n });\n return new Response(transformServerSentEvents(answer));\n }\n\n const promptId = parsedRequest.trigger.promptId;\n const promptObject = await space.crud.query({ id: promptId }).first();\n\n if (parsedRequest.data.objects.length !== 1) {\n return new Response('Message batches not supported.');\n }\n\n const messageId = parsedRequest.data.objects[0];\n let message;\n try {\n message = await space.crud.query({ id: messageId }).first();\n } catch (err) {\n return new Response('Message not replicated yet.', { status: 409 });\n }\n\n if (message.text.includes('--------')) {\n return new Response('Message was already processed.');\n }\n\n let prompt = promptObject.template;\n for (const input of promptObject.inputs) {\n let value: string | null = null;\n if (input.type === TemplateInputType.VALUE) {\n value = String(input.value);\n } else if (input.type === TemplateInputType.RETRIEVER) {\n value = await getContext({ space });\n } else if (input.type === TemplateInputType.PASS_THROUGH) {\n value = message.text;\n }\n if (value) {\n prompt = prompt.replaceAll(`{${input.name}}`, value);\n }\n }\n\n const answer = await ai.run('@cf/meta/llama-3.1-8b-instruct', {\n stream: false,\n prompt,\n });\n const response = { response: answer.response, prompt, message };\n const textWithAnswer = message.text + '\\n--------\\n\\n' + answer.response;\n await space.crud.update({ id: messageId }, { text: textWithAnswer });\n\n return new Response(JSON.stringify(response));\n};\n\nconst getContext = async ({ space }: any) => {\n let context = '';\n const { objects: docs } = await space.crud.query({ __typename: 'dxos.org/type/Document' }).run();\n for (const doc of docs) {\n const { content } = await space.crud.query({ id: doc.content }).first();\n context += content + '\\n\\n';\n }\n return context;\n};\n\nenum TemplateInputType {\n VALUE = 0,\n PASS_THROUGH = 1,\n RETRIEVER = 2,\n FUNCTION = 3,\n QUERY = 4,\n RESOLVER = 5,\n CONTEXT = 6,\n SCHEMA = 7,\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S } from 'dxos:functions';\n// @ts-ignore\nimport { Chess } from 'https://esm.sh/chess.js@0.13.1?bundle=false';\n\nexport default defineFunction({\n description: 'Plays a random move in a chess game.',\n\n inputSchema: S.Struct({\n changedObjectId: S.String.annotations({\n description: 'The objects to play the game on.',\n }),\n player: S.optional(S.Literal('w', 'b')).annotations({\n description: 'The player to play the game as.',\n }),\n }),\n\n outputSchema: S.Struct({\n state: S.String.annotations({\n description: 'The state of the game as an ASCII art board.',\n }),\n }),\n\n handler: async ({ data: { changedObjectId, player = 'b' }, context: { space } }: any) => {\n const { pgn } = await space.db.query({ id: changedObjectId }).first();\n const game = new Chess();\n game.load_pgn(pgn);\n if (game.turn() !== player) {\n return new Response('Invalid turn', { status: 409 });\n }\n\n const moves = game.moves();\n const move = moves[Math.floor(Math.random() * moves.length)];\n if (!move) {\n return new Response('No legal moves', { status: 406 });\n }\n\n game.move(move);\n const newPgn = game.pgn();\n await space.db.update({ id: changedObjectId }, { pgn: newPgn, fen: game.fen() });\n return { state: game.ascii() };\n },\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S, create, Expando } from 'dxos:functions';\n// @ts-ignore\nimport { randText } from 'https://esm.sh/@ngneat/falso@7.1.1?bundle=false';\n\nexport default defineFunction({\n inputSchema: S.Struct({\n documentAmount: S.optional(S.Number),\n textSize: S.optional(S.Number),\n mutationAmount: S.optional(S.Number),\n }),\n\n outputSchema: S.Struct({}),\n\n handler: async ({ data: { documentAmount = 1, textSize = 10, mutationAmount = 0 }, context: { space } }: any) => {\n await space.db.graph.schemaRegistry.addSchema([Expando]);\n const result: Record<string, any> = {};\n const objects: Expando[] = [];\n\n // Create objects.\n for (let i = 0; i < documentAmount; i++) {\n const obj = space.db.add(\n create(Expando, {\n name: 'scriptGenerated',\n content: randText({ charCount: textSize }),\n }),\n );\n objects.push(obj);\n const objectResult: any = {};\n // Mutate the object.\n for (let i = 0; i < mutationAmount; i++) {\n obj.content = randText({ charCount: textSize });\n }\n objectResult.mutations = mutationAmount;\n objectResult.contentLength = obj.content.length;\n result[obj.id] = objectResult;\n }\n\n // Flush and wait for data to propagate.\n await space.db.flush();\n await new Promise((resolve) => setTimeout(resolve, 10_000));\n return result;\n },\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { create, defineFunction, DXN, EchoObject, Filter, ObjectId, S } from 'dxos:functions';\n// @ts-ignore\nimport { FetchHttpClient } from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.14.21&bundle=false';\nimport {\n DiscordConfig,\n DiscordREST,\n DiscordRESTMemoryLive,\n // @ts-ignore\n} from 'https://esm.sh/dfx@0.113.0?deps=effect@3.14.21&bundle=false';\n// @ts-ignore\nimport { Effect, Config, Redacted, Ref } from 'https://esm.sh/effect@3.14.21?bundle=false';\n\nconst MessageSchema = S.Struct({\n id: ObjectId,\n foreignId: S.Any, // bigint?\n from: S.String,\n created: S.String,\n content: S.String,\n}).pipe(\n EchoObject({\n typename: 'example.com/type/Message',\n version: '0.1.0',\n }),\n);\n\nconst DEFAULT_AFTER = 1704067200; // 2024-01-01\n\nconst generateSnowflake = (unixTimestamp: number): bigint => {\n const discordEpoch = 1420070400000n; // Discord Epoch (ms)\n return (BigInt(unixTimestamp * 1000) - discordEpoch) << 22n;\n};\n\nexport default defineFunction({\n inputSchema: S.Struct({\n // TODO(wittjosiah): Remove. This is used to provide a terminal for a cron trigger.\n tick: S.optional(S.String),\n channelId: S.String,\n after: S.optional(S.Number),\n pageSize: S.optional(S.Number),\n queueId: S.String,\n }),\n\n outputSchema: S.Struct({\n newMessages: S.Number,\n }),\n\n handler: ({ data: { channelId, queueId, after = DEFAULT_AFTER, pageSize = 5 }, context: { space } }: any) =>\n Effect.gen(function* () {\n const { token } = yield* Effect.tryPromise({\n try: () => space.db.query(Filter.typename('dxos.org/type/AccessToken', { source: 'discord.com' })).first(),\n catch: (e: any) => e,\n });\n const { objects } = yield* Effect.tryPromise({\n try: () => space.queues.queryQueue(DXN.parse(queueId)),\n catch: (e: any) => e,\n });\n const backfill = objects.length === 0;\n const newMessages = yield* Ref.make(0);\n const lastMessage = yield* Ref.make(objects.at(-1));\n\n const enqueueMessages = Effect.gen(function* () {\n const rest = yield* DiscordREST;\n\n while (true) {\n const last = yield* Ref.get(lastMessage);\n const options = {\n after: backfill && !last ? `${generateSnowflake(after)}` : last?.foreignId,\n limit: pageSize,\n };\n const messages = yield* rest.getChannelMessages(channelId, options).pipe((res: any) => res.json);\n const queueMessages = messages\n .map((message: any) =>\n create(MessageSchema, {\n id: ObjectId.random(),\n foreignId: message.id,\n from: message.author.username,\n created: message.timestamp,\n content: message.content,\n }),\n )\n .toReversed();\n if (queueMessages.length > 0) {\n yield* Effect.tryPromise({\n try: () => space.queues.insertIntoQueue(DXN.parse(queueId), queueMessages),\n catch: (e: any) => e,\n });\n yield* Ref.update(newMessages, (n: any) => n + queueMessages.length);\n yield* Ref.update(lastMessage, (m: any) => queueMessages.at(-1));\n }\n if (messages.length < pageSize) {\n break;\n }\n }\n }).pipe(\n Effect.provide(DiscordRESTMemoryLive),\n Effect.provide(\n DiscordConfig.layerConfig({\n token: Config.succeed(Redacted.make(token)),\n }),\n ),\n Effect.provide(FetchHttpClient.layer),\n );\n\n yield* enqueueMessages;\n return { newMessages: yield* Ref.get(newMessages) };\n }),\n});\n", "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Echos the request data.\n */\nexport default async ({ data }: any) => data;\n", "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Appends a message to the end of a Document configured through a trigger.\n * Trigger must have a targetDocumentId field set in Meta.\n */\nexport default async ({ data: { bodyText }, context: { space } }: any) => {\n const { email, targetDocumentId: documentId } = JSON.parse(bodyText) as RequestPayload;\n\n const document = await space.db.query({ id: documentId }).first();\n\n const contentId = document.content['/'].split(':')[3];\n const documentContent = await space.db.query({ id: contentId }).first();\n const modifiedContent = [\n documentContent.content,\n '',\n '---',\n `**From:** ${email.from}`,\n `**Subject:** ${email.subject}`,\n `**Date:** ${email.created}`,\n '',\n email.body,\n ].join('\\n');\n\n await space.db.update({ id: contentId }, { content: modifiedContent });\n\n return new Response(JSON.stringify({ success: true }));\n};\n\ntype RequestPayload = {\n email: { from: string; subject: string; created: string; body: string };\n targetDocumentId: string;\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { S, defineFunction } from 'dxos:functions';\nimport {\n HttpClient,\n HttpClientRequest,\n FetchHttpClient,\n // @ts-ignore\n} from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.14.21&bundle=false';\n// @ts-ignore\nimport { Effect, Schedule } from 'https://esm.sh/effect@3.14.21?bundle=false';\n\nexport 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.String.annotations({ description: 'The exchange rate between the two currencies' }),\n\n handler: async ({ data: { from, to } }: any) =>\n Effect.gen(function* () {\n const res = yield* HttpClientRequest.get(`https://free.ratesdb.com/v1/rates?from=${from}&to=${to}`).pipe(\n HttpClient.execute,\n Effect.flatMap((res: any) => res.json),\n Effect.timeout('1 second'),\n Effect.retry(Schedule.exponential(1_000).pipe(Schedule.compose(Schedule.recurs(3)))),\n Effect.scoped,\n );\n\n return res.data.rates[to].toString();\n }).pipe(Effect.provide(FetchHttpClient.layer)),\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S } from 'dxos:functions';\n\nexport 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 handler: async ({ data: { from, to } }: 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 rates[to].toString();\n },\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { create, defineFunction, EchoObject, Filter, ObjectId, S } from 'dxos:functions';\n// @ts-ignore\nimport {\n HttpClient,\n HttpClientRequest,\n FetchHttpClient,\n // @ts-ignore\n} from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.14.21&bundle=false';\n// @ts-ignore\nimport { format, subDays } from 'https://esm.sh/date-fns@3.3.1?bundle=false';\n// @ts-ignore\nimport { pipe, Chunk, Effect, Ref, Schedule, Stream } from 'https://esm.sh/effect@3.14.21?bundle=false';\n\nexport default defineFunction({\n inputSchema: S.Struct({\n mailboxId: S.String,\n userId: S.optional(S.String).pipe(S.withDecodingDefault(() => 'me')),\n after: S.optional(S.Union(S.Number, S.String)).pipe(\n S.withDecodingDefault(() => format(subDays(new Date(), 30), 'yyyy-MM-dd')),\n ),\n pageSize: S.optional(S.Number).pipe(S.withDecodingDefault(() => 100)),\n // TODO(wittjosiah): Remove. This is used to provide a terminal for a cron trigger.\n tick: S.optional(S.String),\n }),\n\n outputSchema: S.Struct({\n newMessages: S.Number,\n }),\n\n handler: ({ context: { space }, data: { mailboxId, userId, after, pageSize } }: any) =>\n Effect.gen(function* () {\n const { token } = yield* Effect.tryPromise({\n try: () => space.db.query(Filter.typename('dxos.org/type/AccessToken', { source: 'gmail.com' })).first(),\n catch: (e: any) => e,\n });\n\n // NOTE: Google API bundles size is v. large and caused runtime issues.\n const makeRequest = (url: string) =>\n pipe(\n url,\n HttpClientRequest.get,\n HttpClientRequest.setHeaders({ Authorization: `Bearer ${token}`, Accept: 'application/json' }),\n HttpClient.execute,\n Effect.flatMap((res: any) => res.json),\n Effect.timeout('1 second'),\n Effect.retry(Schedule.exponential(1000).pipe(Schedule.compose(Schedule.recurs(3)))),\n Effect.scoped,\n );\n\n const listMessages = (userId: string, q: string, pageSize: number, pageToken: string | null) =>\n makeRequest(getUrl(userId, undefined, { q, pageSize, pageToken }));\n\n const getMessage = (userId: string, messageId: string) => makeRequest(getUrl(userId, messageId));\n\n const mailbox = yield* Effect.tryPromise({\n try: () => space.db.query({ id: mailboxId }).first(),\n catch: (e: any) => e,\n });\n const { objects } = yield* Effect.tryPromise({\n try: () => space.queues.queryQueue(mailbox.queue.dxn),\n catch: (e: any) => e,\n });\n const newMessages = yield* Ref.make([]);\n const nextPage = yield* Ref.make(null);\n\n do {\n const last = objects.at(-1);\n const q = last\n ? `in:inbox after:${Math.floor(new Date(last.created).getTime() / 1000)}`\n : `in:inbox after:${after}`;\n const pageToken = yield* Ref.get(nextPage);\n const { messages, nextPageToken } = yield* listMessages(userId, q, pageSize, pageToken);\n yield* Ref.update(nextPage, () => nextPageToken);\n for (const message of messages) {\n const messageDetails = yield* getMessage(userId, message.id);\n const created = new Date(parseInt(messageDetails.internalDate)).toISOString();\n const from = messageDetails.payload.headers.find((h: any) => h.name === 'From');\n const sender = from && parseEmailString(from.value);\n // TODO(wittjosiah): Improve parsing of email contents.\n const content =\n messageDetails.payload.body?.data ??\n messageDetails.payload.parts?.find((p: any) => p.mimeType === 'text/plain')?.body.data;\n // Skip the message if content or sender is missing.\n // Skip the message if it's the same as the last message.\n // TODO(wittjosiah): This comparison should be done via foreignId probably.\n if (!content || !sender || created === last?.created) {\n continue;\n }\n const subject = messageDetails.payload.headers.find((h: any) => h.name === 'Subject')?.value;\n const object = create(MessageType, {\n id: ObjectId.random(),\n created,\n sender,\n blocks: [\n {\n type: 'text',\n text: Buffer.from(content, 'base64').toString('utf-8'),\n },\n ],\n properties: {\n subject,\n threadId: message.threadId,\n },\n });\n // TODO(wittjosiah): Set foreignId in object meta.\n yield* Ref.update(newMessages, (n: any) => [object, ...n]);\n }\n } while (yield* Ref.get(nextPage));\n\n const queueMessages = yield* Ref.get(newMessages);\n if (queueMessages.length > 0) {\n yield* pipe(\n queueMessages,\n Stream.fromIterable,\n Stream.grouped(10),\n Stream.flatMap((batch: any) =>\n Effect.tryPromise({\n try: () => space.queues.insertIntoQueue(mailbox.queue.dxn, Chunk.toReadonlyArray(batch)),\n catch: (e: any) => e,\n }),\n ),\n Stream.runDrain,\n );\n }\n\n return { newMessages: queueMessages.length };\n }).pipe(Effect.provide(FetchHttpClient.layer)),\n});\n\nconst getUrl = (userId: string, messageId?: string, params?: Record<string, any>) => {\n const api = new URL(\n [`https://gmail.googleapis.com/gmail/v1/users/${userId}/messages`, messageId].filter(Boolean).join('/'),\n );\n Object.entries(params ?? {})\n .filter(([_, value]) => value != null)\n .forEach(([key, value]) => api.searchParams.set(key, value));\n return api.toString();\n};\n\n/**\n * Parses an email string in the format \"Name <email@example.com>\" into separate name and email components.\n */\nconst parseEmailString = (emailString: string): { name?: string; email: string } | undefined => {\n const match = emailString.match(/^([^<]+?)\\s*<([^>]+@[^>]+)>$/);\n if (match) {\n const [, name, email] = match;\n return {\n name: name.trim(),\n email: email.trim(),\n };\n }\n\n return undefined;\n};\n\n//\n// Schemas\n// TODO(wittjosiah): These schemas should be imported from @dxos/S.\n//\n\nconst ActorRoles = ['user', 'assistant'] as const;\nconst ActorRole = S.Literal(...ActorRoles);\ntype ActorRole = S.Schema.Type<typeof ActorRole>;\n\nconst ActorSchema = S.Struct({\n identityKey: S.optional(S.String),\n email: S.optional(S.String),\n name: S.optional(S.String),\n role: S.optional(ActorRole),\n});\n\nconst AbstractContentBlock = S.Struct({\n pending: S.optional(S.Boolean),\n});\ntype AbstractContentBlock = S.Schema.Type<typeof AbstractContentBlock>;\nconst TextContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('text'),\n disposition: S.optional(S.String),\n text: S.String,\n }),\n).pipe(S.mutable);\ntype TextContentBlock = S.Schema.Type<typeof TextContentBlock>;\nconst JsonContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('json'),\n disposition: S.optional(S.String),\n data: S.String,\n }),\n).pipe(S.mutable);\ntype JsonContentBlock = S.Schema.Type<typeof JsonContentBlock>;\nconst Base64ImageSource = S.Struct({\n type: S.Literal('base64'),\n mediaType: S.String,\n data: S.String,\n}).pipe(S.mutable);\nconst HttpImageSource = S.Struct({\n type: S.Literal('http'),\n url: S.String,\n}).pipe(S.mutable);\nconst ImageSource = S.Union(Base64ImageSource, HttpImageSource);\ntype ImageSource = S.Schema.Type<typeof ImageSource>;\nconst ImageContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('image'),\n id: S.optional(S.String),\n source: S.optional(ImageSource),\n }),\n).pipe(S.mutable);\ntype ImageContentBlock = S.Schema.Type<typeof ImageContentBlock>;\nconst ReferenceContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('reference'),\n reference: S.Any,\n }),\n).pipe(S.mutable);\ntype ReferenceContentBlock = S.Schema.Type<typeof ReferenceContentBlock>;\nconst MessageContentBlock = S.Union(TextContentBlock, JsonContentBlock, ImageContentBlock, ReferenceContentBlock);\n\nconst MessageType = S.Struct({\n id: ObjectId,\n created: S.String.annotations({\n description: 'ISO date string when the message was sent.',\n }),\n sender: ActorSchema.annotations({\n description: 'Identity of the message sender.',\n }),\n blocks: S.Array(MessageContentBlock).annotations({\n description: 'Contents of the message.',\n }),\n properties: S.optional(\n S.mutable(\n S.Record({ key: S.String, value: S.Any }).annotations({\n description: 'Custom properties for specific message types (e.g. attention context, email subject, etc.).',\n }),\n ),\n ),\n}).pipe(\n EchoObject({\n typename: 'dxos.org/type/Message',\n version: '0.2.0',\n }),\n);\ntype MessageType = S.Schema.Type<typeof MessageType>;\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport chat from './chat.ts?raw';\nimport chess from './chess.ts?raw';\nimport dataGenerator from './data-generator.ts?raw';\nimport discord from './discord.ts?raw';\nimport echo from './echo.ts?raw';\nimport email from './email.ts?raw';\nimport forexEffect from './forex-effect.ts?raw';\nimport forex from './forex.ts?raw';\nimport gmail from './gmail.ts?raw';\n\nconst removeHeader = (str: string) => str.split('\\n').slice(4).join('\\n');\n\nexport type Template = {\n id: string;\n name: string;\n source: string;\n presetId?: string;\n};\n\nexport const templates: Template[] = [\n {\n id: 'dxos.org/script/echo',\n name: 'Echo',\n source: removeHeader(echo),\n },\n {\n id: 'dxos.org/script/forex',\n name: 'Forex',\n source: removeHeader(forex),\n },\n {\n id: 'dxos.org/script/forex-effect',\n name: 'Forex (Effect)',\n source: removeHeader(forexEffect),\n },\n {\n id: 'dxos.org/script/gpt',\n name: 'Gpt',\n source: removeHeader(chat),\n presetId: 'dxos.org/function/gpt',\n },\n {\n id: 'dxos.org/script/chess',\n name: 'Chess',\n source: removeHeader(chess),\n presetId: 'dxos.org/function/chess',\n },\n {\n id: 'dxos.org/script/email',\n name: 'Email',\n source: removeHeader(email),\n presetId: 'dxos.org/function/email',\n },\n {\n id: 'dxos.org/script/discord',\n name: 'Discord',\n source: removeHeader(discord),\n presetId: 'dxos.org/function/discord',\n },\n {\n id: 'dxos.org/script/gmail',\n name: 'Gmail',\n source: removeHeader(gmail),\n presetId: 'dxos.org/function/gmail',\n },\n {\n id: 'dxos.org/script/data-generator',\n name: 'Data Generator',\n source: removeHeader(dataGenerator),\n presetId: 'dxos.org/function/data-generator',\n },\n];\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { useMemo } from 'react';\n\nimport { live } from '@dxos/live-object';\n\nimport { type DeployState } from './deploy';\n\nexport type ScriptToolbarState = Partial<DeployState>;\n\n// TODO(burdon): Replace with context provider?\nexport const useToolbarState = (initialState: ScriptToolbarState = {}) => {\n return useMemo(() => live<ScriptToolbarState>(initialState), []);\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { format } from 'prettier';\nimport prettierPluginEstree from 'prettier/plugins/estree';\nimport prettierPluginTypescript from 'prettier/plugins/typescript';\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 = (script: ScriptType) => {\n const formatAction = createMenuAction(\n 'format',\n 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 },\n {\n label: ['format label', { ns: SCRIPT_PLUGIN }],\n icon: 'ph--magic-wand--regular',\n },\n );\n\n return {\n nodes: [formatAction],\n edges: [\n {\n source: 'root',\n target: 'format',\n },\n ],\n };\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Obj } from '@dxos/echo';\nimport { FUNCTIONS_PRESET_META_KEY, type ScriptType } from '@dxos/functions';\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 = (script: ScriptType) => {\n return templates.map((template) => {\n return createMenuAction<TemplateActionProperties>(\n `template--${template.id}`,\n () => {\n script.name = template.name;\n script.source!.target!.content = template.source;\n const metaKeys = Obj.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 label: template.name,\n value: template.id,\n type: 'template',\n },\n );\n });\n};\n\nexport const createTemplateSelect = (script: ScriptType) => {\n const templateSelectGroup = createTemplateSelectGroup();\n const templateSelectActions = createTemplateSelectActions(script);\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"],
5
+ "mappings": ";;;;;;;;;;;AAIA,SAASA,WAAWC,eAAe;AAEnC,SAASC,cAA+BC,oCAAoC;AAC5E,SAASC,WAAW;AACpB,SAAsBC,iBAAiB;AACvC,SAASC,SAASC,UAAUC,OAAOC,KAAiBC,gBAAgB;AAEpE,SAASC,wBAAwB;AACjC,SAASC,0BAA0B;;AAwB5B,IAAMC,eAAe,CAAC,EAAEC,OAAOC,QAAQC,OAAOC,IAAIC,QAAQC,qBAAqBC,EAAC,MAAuB;AAE5G,QAAMC,YAAYC,iBAAiB,SAAS,MAAA;EAAO,GAAG;IACpDC,OAAOT,MAAMU,SAAS;MAAC;MAAkB;QAAEC,IAAIC;MAAc;;IAC7DC,MAAM;IACNC,QAAQ,CAACd,MAAMU;IACfK,YAAYf,MAAMU,SAASM;EAC7B,CAAA;AAEA,QAAMC,eAAeT,iBACnB,UACA,YAAA;AACE,QAAI,CAACP,OAAOiB,UAAU,CAAChB,OAAO;AAC5B;IACF;AAEAF,UAAMU,QAAQS;AACdnB,UAAMoB,YAAY;AAElB,UAAMC,SAAS,MAAMC,aAAa;MAAErB;MAAQG;MAAQF;MAAOC;MAAIE;IAAoB,CAAA;AAEnF,QAAI,CAACgB,OAAOE,SAAS;AACnBC,UAAIC,MAAMJ,OAAOX,OAAK,QAAA;;;;;;AACtBV,YAAMU,QAAQJ,EAAE,qBAAA;IAClB;AAEAN,UAAMoB,YAAY;EACpB,GACA;IACEM,MAAM;IACNjB,OAAO;MAACT,MAAMoB,YAAY,kBAAkB;MAAgB;QAAET,IAAIC;MAAc;;IAChFC,MAAMb,MAAMoB,YAAY,6BAA6B;IACrDO,UAAU3B,MAAMoB;IAChBL,YAAYf,MAAMoB,YAAY,yBAAyB;EACzD,CAA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AAIX,SAASgB,UAAU;AACrBT,iBAASU,KAAK;UAAEb,QAAQU;UAA2BZ,IAAIF,SAASgB;QAAS,CAAA;MAC3E;IACF,GACA;MACExB,OAAOQ,SAASG;MAChBe,OAAOlB,SAASE;MAChBiB,MAAM;IACR,CAAA;EAEJ,CAAA;AACF;AAEO,IAAMC,uBAAuB,CAACvB,WAAAA;AACnC,QAAMwB,sBAAsB/B,0BAAAA;AAC5B,QAAMgC,wBAAwB1B,4BAA4BC,MAAAA;AAC1D,SAAO;IACL0B,OAAO;MAACF;SAAwBC;;IAChCE,OAAO;MACL;QAAEpB,QAAQ;QAAQC,QAAQ;MAAkB;SACzCiB,sBAAsBvB,IAAI,CAAC0B,YAAY;QAAErB,QAAQ;QAAmBC,QAAQoB,OAAOvB;MAAG,EAAA;;EAE7F;AACF;",
6
+ "names": ["useEffect", "useMemo", "FunctionType", "getUserFunctionUrlInMetadata", "log", "useClient", "getMeta", "getSpace", "Query", "Ref", "useQuery", "createMenuAction", "errorMessageColors", "createDeploy", "state", "script", "space", "fn", "client", "existingFunctionUrl", "t", "errorItem", "createMenuAction", "label", "error", "ns", "SCRIPT_PLUGIN", "icon", "hidden", "classNames", "errorMessageColors", "deployAction", "source", "undefined", "deploying", "result", "deployScript", "success", "log", "catch", "type", "disabled", "copyAction", "functionUrl", "navigator", "clipboard", "writeText", "nodes", "edges", "target", "useDeployState", "useDeployDeps", "useEffect", "getFunctionUrl", "edgeUrl", "config", "values", "runtime", "services", "edge", "url", "deployed", "isScriptDeployed", "changed", "getSpace", "useQuery", "Query", "FunctionType", "Ref", "make", "useClient", "useMemo", "getUserFunctionUrlInMetadata", "getMeta", "removeHeader", "str", "split", "slice", "join", "templates", "id", "name", "source", "echo", "forex", "forexEffect", "chat", "presetId", "chess", "email", "discord", "gmail", "dataGenerator", "useMemo", "live", "useToolbarState", "initialState", "useMemo", "live", "format", "prettierPluginEstree", "prettierPluginTypescript", "log", "createMenuAction", "createFormat", "script", "formatAction", "createMenuAction", "source", "target", "content", "format", "parser", "plugins", "prettierPluginEstree", "prettierPluginTypescript", "semi", "singleQuote", "err", "log", "catch", "label", "ns", "SCRIPT_PLUGIN", "icon", "nodes", "edges", "Obj", "FUNCTIONS_PRESET_META_KEY", "createMenuItemGroup", "createMenuAction", "createTemplateSelectGroup", "createMenuItemGroup", "label", "ns", "SCRIPT_PLUGIN", "variant", "createTemplateSelectActions", "script", "templates", "map", "template", "createMenuAction", "id", "name", "source", "target", "content", "metaKeys", "Obj", "getMeta", "keys", "oldPresetIndex", "findIndex", "key", "FUNCTIONS_PRESET_META_KEY", "splice", "presetId", "push", "value", "type", "createTemplateSelect", "templateSelectGroup", "templateSelectActions", "nodes", "edges", "action"]
7
7
  }
@@ -1,9 +1,9 @@
1
1
  import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
2
  import {
3
3
  SCRIPT_PLUGIN
4
- } from "./chunk-AEB5TPEW.mjs";
4
+ } from "./chunk-AHXJ6NQU.mjs";
5
5
 
6
- // packages/plugins/plugin-script/src/types.ts
6
+ // src/types.ts
7
7
  import { Schema } from "effect";
8
8
  import { SpaceSchema } from "@dxos/client/echo";
9
9
  import { ScriptType } from "@dxos/functions";
@@ -38,4 +38,4 @@ export {
38
38
  ScriptSettingsSchema,
39
39
  ScriptAction
40
40
  };
41
- //# sourceMappingURL=chunk-UESZKXLR.mjs.map
41
+ //# sourceMappingURL=chunk-OVSJYR6O.mjs.map
@@ -1,12 +1,12 @@
1
1
  import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
2
  import {
3
3
  useCreateAndDeployScriptTemplates
4
- } from "./chunk-MJJQBUOL.mjs";
4
+ } from "./chunk-ABAPR7VQ.mjs";
5
5
  import {
6
6
  SCRIPT_PLUGIN
7
- } from "./chunk-AEB5TPEW.mjs";
7
+ } from "./chunk-AHXJ6NQU.mjs";
8
8
 
9
- // packages/plugins/plugin-script/src/components/DeploymentDialog/DeploymentDialog.tsx
9
+ // src/components/DeploymentDialog/DeploymentDialog.tsx
10
10
  import { useSignals as _useSignals } from "@preact-signals/safe-react/tracking";
11
11
  import React, { useEffect, useMemo } from "react";
12
12
  import { createIntent, LayoutAction, useIntentDispatcher } from "@dxos/app-framework";
@@ -144,11 +144,11 @@ var DeploymentDialog = ({ accessToken, scriptTemplates }) => {
144
144
  }
145
145
  };
146
146
 
147
- // packages/plugins/plugin-script/src/components/DeploymentDialog/index.ts
147
+ // src/components/DeploymentDialog/index.ts
148
148
  var DeploymentDialog_default = DeploymentDialog;
149
149
 
150
150
  export {
151
151
  DEPLOYMENT_DIALOG,
152
152
  DeploymentDialog_default
153
153
  };
154
- //# sourceMappingURL=chunk-T7XDCUTF.mjs.map
154
+ //# sourceMappingURL=chunk-YVJGDDNV.mjs.map
@@ -1,19 +1,19 @@
1
1
  import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
2
  import {
3
3
  ScriptCapabilities
4
- } from "./chunk-2KJYPUQD.mjs";
5
- import "./chunk-AEB5TPEW.mjs";
4
+ } from "./chunk-35M3CHYE.mjs";
5
+ import "./chunk-AHXJ6NQU.mjs";
6
6
 
7
- // packages/plugins/plugin-script/src/capabilities/compiler.ts
7
+ // src/capabilities/compiler.ts
8
8
  import wasmUrl from "esbuild-wasm/esbuild.wasm?url";
9
9
  import { contributes } from "@dxos/app-framework";
10
10
  import { initializeBundler } from "@dxos/functions/bundler";
11
11
 
12
- // packages/plugins/plugin-script/src/compiler/compiler.ts
12
+ // src/compiler/compiler.ts
13
13
  import { createDefaultMapFromCDN, createSystem, createVirtualTypeScriptEnvironment } from "@typescript/vfs";
14
14
  import ts from "typescript";
15
15
  import { invariant } from "@dxos/invariant";
16
- var __dxlog_file = "/home/runner/work/dxos/dxos/packages/plugins/plugin-script/src/compiler/compiler.ts";
16
+ var __dxlog_file = "/__w/dxos/dxos/packages/plugins/plugin-script/src/compiler/compiler.ts";
17
17
  var defaultOptions = {
18
18
  lib: [
19
19
  "DOM",
@@ -62,7 +62,7 @@ var Compiler = class {
62
62
  }
63
63
  };
64
64
 
65
- // packages/plugins/plugin-script/src/capabilities/compiler.ts
65
+ // src/capabilities/compiler.ts
66
66
  var compiler_default = async () => {
67
67
  const compiler = new Compiler();
68
68
  await compiler.initialize();
@@ -80,4 +80,4 @@ var compiler_default = async () => {
80
80
  export {
81
81
  compiler_default as default
82
82
  };
83
- //# sourceMappingURL=compiler-7PQ4D43R.mjs.map
83
+ //# sourceMappingURL=compiler-EPFKQXPE.mjs.map
@@ -1,7 +1,7 @@
1
1
  import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
2
  import {
3
3
  ScriptCapabilities
4
- } from "./chunk-2KJYPUQD.mjs";
4
+ } from "./chunk-35M3CHYE.mjs";
5
5
  import {
6
6
  DeploymentDialog,
7
7
  ScriptContainer,
@@ -10,60 +10,59 @@ import {
10
10
  ScriptProperties,
11
11
  TestContainer,
12
12
  TestPanel
13
- } from "./chunk-B4TP3LSZ.mjs";
13
+ } from "./chunk-HD6MDK3H.mjs";
14
14
  import {
15
15
  DEPLOYMENT_DIALOG
16
- } from "./chunk-T7XDCUTF.mjs";
17
- import "./chunk-W2DAXWHA.mjs";
18
- import "./chunk-MJJQBUOL.mjs";
16
+ } from "./chunk-YVJGDDNV.mjs";
17
+ import "./chunk-ORZMINLO.mjs";
18
+ import "./chunk-ABAPR7VQ.mjs";
19
19
  import {
20
20
  ScriptAction
21
- } from "./chunk-UESZKXLR.mjs";
21
+ } from "./chunk-OVSJYR6O.mjs";
22
22
  import {
23
23
  SCRIPT_PLUGIN,
24
24
  defaultScriptsForIntegration,
25
25
  meta
26
- } from "./chunk-AEB5TPEW.mjs";
26
+ } from "./chunk-AHXJ6NQU.mjs";
27
27
 
28
- // packages/plugins/plugin-script/src/capabilities/index.ts
28
+ // src/capabilities/index.ts
29
29
  import { lazy } from "@dxos/app-framework";
30
- var AppGraphBuilder = lazy(() => import("./app-graph-builder-IOOUTHV2.mjs"));
31
- var ArtifactDefinition = lazy(() => import("./artifact-definition-4XRYAP54.mjs"));
32
- var Compiler = lazy(() => import("./compiler-7PQ4D43R.mjs"));
33
- var IntentResolver = lazy(() => import("./intent-resolver-HTM5PSRZ.mjs"));
34
- var ReactSurface = lazy(() => import("./react-surface-6UO64YOS.mjs"));
35
- var ScriptSettings = lazy(() => import("./settings-KZEGCDYX.mjs"));
30
+ var AppGraphBuilder = lazy(() => import("./app-graph-builder-7EYIHWH4.mjs"));
31
+ var ArtifactDefinition = lazy(() => import("./artifact-definition-EBLXG5AR.mjs"));
32
+ var Compiler = lazy(() => import("./compiler-EPFKQXPE.mjs"));
33
+ var IntentResolver = lazy(() => import("./intent-resolver-XLV6FPWH.mjs"));
34
+ var ReactSurface = lazy(() => import("./react-surface-BTYC7MGG.mjs"));
35
+ var ScriptSettings = lazy(() => import("./settings-QCMDG2MZ.mjs"));
36
36
 
37
- // packages/plugins/plugin-script/src/ScriptPlugin.tsx
37
+ // src/ScriptPlugin.tsx
38
38
  import { Schema } from "effect";
39
39
  import { Capabilities, contributes, createIntent, defineModule, definePlugin, Events } from "@dxos/app-framework";
40
+ import { Ref } from "@dxos/echo";
40
41
  import { ScriptType as ScriptType2 } from "@dxos/functions";
41
- import { RefArray } from "@dxos/live-object";
42
42
  import { ClientEvents } from "@dxos/plugin-client";
43
43
  import { SpaceCapabilities } from "@dxos/plugin-space";
44
44
  import { defineObjectForm } from "@dxos/plugin-space/types";
45
45
 
46
- // packages/plugins/plugin-script/src/events.ts
46
+ // src/events.ts
47
47
  import { defineEvent } from "@dxos/app-framework";
48
48
  (function(ScriptEvents2) {
49
49
  ScriptEvents2.SetupCompiler = defineEvent(`${SCRIPT_PLUGIN}/event/setup-compiler`);
50
50
  })(ScriptEvents || (ScriptEvents = {}));
51
51
  var ScriptEvents;
52
52
 
53
- // packages/plugins/plugin-script/src/translations.ts
54
- import { Type } from "@dxos/echo";
53
+ // src/translations.ts
55
54
  import { ScriptType } from "@dxos/functions";
56
- var translations_default = [
55
+ var translations = [
57
56
  {
58
57
  "en-US": {
59
- [Type.getTypename(ScriptType)]: {
58
+ [ScriptType.typename]: {
60
59
  "typename label": "Script",
61
60
  "typename label_zero": "Scripts",
62
61
  "typename label_one": "Script",
63
62
  "typename label_other": "Scripts",
64
63
  "object name placeholder": "New script"
65
64
  },
66
- [SCRIPT_PLUGIN]: {
65
+ [meta.id]: {
67
66
  "plugin name": "Scripts",
68
67
  "description label": "Description",
69
68
  "description placeholder": "Enter description",
@@ -122,7 +121,7 @@ var translations_default = [
122
121
  }
123
122
  ];
124
123
 
125
- // packages/plugins/plugin-script/src/ScriptPlugin.tsx
124
+ // src/ScriptPlugin.tsx
126
125
  var ScriptPlugin = () => definePlugin(meta, [
127
126
  defineModule({
128
127
  id: `${meta.id}/module/settings`,
@@ -137,7 +136,7 @@ var ScriptPlugin = () => definePlugin(meta, [
137
136
  defineModule({
138
137
  id: `${meta.id}/module/translations`,
139
138
  activatesOn: Events.SetupTranslations,
140
- activate: () => contributes(Capabilities.Translations, translations_default)
139
+ activate: () => contributes(Capabilities.Translations, translations)
141
140
  }),
142
141
  defineModule({
143
142
  id: `${meta.id}/module/metadata`,
@@ -147,7 +146,7 @@ var ScriptPlugin = () => definePlugin(meta, [
147
146
  metadata: {
148
147
  icon: "ph--code--regular",
149
148
  // TODO(wittjosiah): Move out of metadata.
150
- loadReferences: async (script) => await RefArray.loadAll([
149
+ loadReferences: async (script) => await Ref.Array.loadAll([
151
150
  script.source
152
151
  ])
153
152
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/capabilities/index.ts", "../../../src/ScriptPlugin.tsx", "../../../src/events.ts", "../../../src/translations.ts"],
4
- "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport { lazy } from '@dxos/app-framework';\n\nexport const AppGraphBuilder = lazy(() => import('./app-graph-builder'));\nexport const ArtifactDefinition = lazy(() => import('./artifact-definition'));\nexport const Compiler = lazy(() => import('./compiler'));\nexport const IntentResolver = lazy(() => import('./intent-resolver'));\nexport const ReactSurface = lazy(() => import('./react-surface'));\nexport const ScriptSettings = lazy(() => import('./settings'));\n\nexport * from './capabilities';\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { Schema } from 'effect';\n\nimport { Capabilities, contributes, createIntent, defineModule, definePlugin, Events } from '@dxos/app-framework';\nimport { ScriptType } from '@dxos/functions';\nimport { RefArray } from '@dxos/live-object';\nimport { ClientEvents } from '@dxos/plugin-client';\nimport { SpaceCapabilities } from '@dxos/plugin-space';\nimport { defineObjectForm } from '@dxos/plugin-space/types';\n\nimport {\n AppGraphBuilder,\n ArtifactDefinition,\n Compiler,\n IntentResolver,\n ReactSurface,\n ScriptSettings,\n} from './capabilities';\nimport { ScriptEvents } from './events';\nimport { meta } from './meta';\nimport translations from './translations';\nimport { ScriptAction } from './types';\n\nexport const ScriptPlugin = () =>\n definePlugin(meta, [\n defineModule({\n id: `${meta.id}/module/settings`,\n activatesOn: Events.SetupSettings,\n activate: ScriptSettings,\n }),\n defineModule({\n id: `${meta.id}/module/compiler`,\n activatesOn: ScriptEvents.SetupCompiler,\n activate: Compiler,\n }),\n defineModule({\n id: `${meta.id}/module/translations`,\n activatesOn: Events.SetupTranslations,\n activate: () => contributes(Capabilities.Translations, translations),\n }),\n defineModule({\n id: `${meta.id}/module/metadata`,\n activatesOn: Events.SetupMetadata,\n activate: () =>\n contributes(Capabilities.Metadata, {\n id: ScriptType.typename,\n metadata: {\n icon: 'ph--code--regular',\n // TODO(wittjosiah): Move out of metadata.\n loadReferences: async (script: ScriptType) => await RefArray.loadAll([script.source]),\n },\n }),\n }),\n defineModule({\n id: `${meta.id}/module/app-graph-builder`,\n activatesOn: Events.SetupAppGraph,\n activate: AppGraphBuilder,\n }),\n defineModule({\n id: `${meta.id}/module/object-form`,\n activatesOn: ClientEvents.SetupSchema,\n activate: () =>\n contributes(\n SpaceCapabilities.ObjectForm,\n defineObjectForm({\n objectSchema: ScriptType,\n formSchema: ScriptAction.CreateScriptSchema.pipe(Schema.omit('initialTemplateId')),\n getIntent: (props, options) => createIntent(ScriptAction.Create, { ...props, space: options.space }),\n }),\n ),\n }),\n defineModule({\n id: `${meta.id}/module/react-surface`,\n activatesOn: Events.SetupReactSurface,\n // TODO(wittjosiah): Should occur before the script editor is loaded when surfaces activation is more granular.\n activatesBefore: [ScriptEvents.SetupCompiler],\n activate: ReactSurface,\n }),\n defineModule({\n id: `${meta.id}/module/intent-resolver`,\n activatesOn: Events.SetupIntentResolver,\n activate: IntentResolver,\n }),\n defineModule({\n id: `${meta.id}/module/artifact-definition`,\n activatesOn: Events.SetupArtifactDefinition,\n activate: ArtifactDefinition,\n }),\n ]);\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { defineEvent } from '@dxos/app-framework';\n\nimport { SCRIPT_PLUGIN } from './meta';\n\nexport namespace ScriptEvents {\n export const SetupCompiler = defineEvent(`${SCRIPT_PLUGIN}/event/setup-compiler`);\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { Type } from '@dxos/echo';\nimport { ScriptType } from '@dxos/functions';\n\nimport { SCRIPT_PLUGIN } from './meta';\n\nexport default [\n {\n 'en-US': {\n [Type.getTypename(ScriptType)]: {\n 'typename label': 'Script',\n 'typename label_zero': 'Scripts',\n 'typename label_one': 'Script',\n 'typename label_other': 'Scripts',\n 'object name placeholder': 'New script',\n },\n [SCRIPT_PLUGIN]: {\n 'plugin name': 'Scripts',\n 'description label': 'Description',\n 'description placeholder': 'Enter description',\n 'binding placeholder': 'Function name',\n 'function request placeholder': 'Function request',\n 'deploy label': 'Deploy',\n 'deployed label': 'Current version of the script is deployed',\n 'upload failed label': 'Upload failed',\n 'copy link label': 'Copy function link',\n 'format label': 'Format',\n 'toggle details label': 'Toggle details panel',\n 'authenticate action label': 'Authenticate functions service',\n 'authenticate button label': 'Authenticate',\n 'name label': 'Name',\n 'remote function settings heading': 'Remote Function',\n 'function url label': 'Invocation URL',\n 'function binding label': 'Function binding',\n 'function binding placeholder': 'Enter binding name (e.g., NAME)',\n 'script publish settings label': 'Publishing',\n 'script publish settings description': 'Scripts can be shared publicly as Github gists.',\n 'no github token label': 'This space has no GitHub access token available.',\n 'open token manager label': 'Open Token Manager',\n 'publish label': 'Publish',\n 'publishing label': 'Publishing',\n 'editor input mode label': 'Editor input mode',\n 'select editor input mode placeholder': 'Select editor input mode…',\n 'settings editor input mode default label': 'Default',\n 'settings editor input mode vim label': 'Vim',\n 'settings editor input mode vscode label': 'VS Code',\n 'template select group label': 'Select template',\n 'function panel label': 'Debug Function',\n 'script test label': 'Test',\n 'script logs label': 'Logs',\n 'deployment dialog title': 'Default Scripts',\n 'deployment dialog scripts found message_one':\n 'We found the following script template for your new integration:',\n 'deployment dialog scripts found message_other':\n 'We found the following script templates for your new integration:',\n 'deployment dialog deploy functions button label_one': 'Create and deploy script',\n 'deployment dialog deploy functions button label_other': 'Create and deploy scripts',\n 'deployment dialog deploy functions pending button label_one': 'Deploying script',\n 'deployment dialog deploy functions pending button label_other': 'Deploying scripts',\n 'deployment dialog skip button label': 'Skip',\n 'script deployment toast label_one': 'Script deployed',\n 'script deployment toast label_other': 'Scripts deployed',\n 'script deployment toast description_one': 'Your script has been deployed successfully.',\n 'script deployment toast description_other': 'Your scripts have been deployed successfully.',\n 'script deployment toast close label_one': 'Close',\n 'script deployment toast close label_other': 'Close',\n 'script deployment error toast label_one': 'Script deployment failed',\n 'script deployment error toast label_other': 'Scripts deployment failed',\n 'script deployment error toast description_one': 'There was an error deploying your script.',\n 'script deployment error toast description_other': 'There was an error deploying your scripts.',\n 'script deployment error toast close label_one': 'Close',\n 'script deployment error toast close label_other': 'Close',\n },\n },\n },\n];\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,SAASA,YAAY;AAEd,IAAMC,kBAAkBC,KAAK,MAAM,OAAO,kCAAA,CAAA;AAC1C,IAAMC,qBAAqBD,KAAK,MAAM,OAAO,oCAAA,CAAA;AAC7C,IAAME,WAAWF,KAAK,MAAM,OAAO,yBAAA,CAAA;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GAAGH;QAAOI,OAAOH,QAAQG;MAAM,CAAA;IACpG,CAAA,CAAA;EAEN,CAAA;EACA7C,aAAa;IACXC,IAAI,GAAGF,KAAKE,EAAE;IACdC,aAAaC,OAAO2C;;IAEpBC,iBAAiB;MAACxC,aAAaC;;IAC/BH,UAAU2C;EACZ,CAAA;EACAhD,aAAa;IACXC,IAAI,GAAGF,KAAKE,EAAE;IACdC,aAAaC,OAAO8C;IACpB5C,UAAU6C;EACZ,CAAA;EACAlD,aAAa;IACXC,IAAI,GAAGF,KAAKE,EAAE;IACdC,aAAaC,OAAOgD;IACpB9C,UAAU+C;EACZ,CAAA;CACD;",
6
- "names": ["lazy", "AppGraphBuilder", "lazy", "ArtifactDefinition", "Compiler", "IntentResolver", "ReactSurface", "ScriptSettings", "Schema", "Capabilities", "contributes", "createIntent", "defineModule", "definePlugin", "Events", "ScriptType", "RefArray", "ClientEvents", "SpaceCapabilities", "defineObjectForm", "defineEvent", "ScriptEvents", "SetupCompiler", "defineEvent", "SCRIPT_PLUGIN", "Type", "ScriptType", "Type", "getTypename", "ScriptType", "SCRIPT_PLUGIN", "ScriptPlugin", "definePlugin", "meta", "defineModule", "id", "activatesOn", "Events", "SetupSettings", "activate", "ScriptSettings", "ScriptEvents", "SetupCompiler", "Compiler", "SetupTranslations", "contributes", "Capabilities", "Translations", "translations", "SetupMetadata", "Metadata", "ScriptType", "typename", "metadata", "icon", "loadReferences", "script", "RefArray", "loadAll", "source", "SetupAppGraph", "AppGraphBuilder", "ClientEvents", "SetupSchema", "SpaceCapabilities", "ObjectForm", "defineObjectForm", "objectSchema", "formSchema", "ScriptAction", "CreateScriptSchema", "pipe", "Schema", "omit", "getIntent", "props", "options", "createIntent", "Create", "space", "SetupReactSurface", "activatesBefore", "ReactSurface", "SetupIntentResolver", "IntentResolver", "SetupArtifactDefinition", "ArtifactDefinition"]
4
+ "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport { lazy } from '@dxos/app-framework';\n\nexport const AppGraphBuilder = lazy(() => import('./app-graph-builder'));\nexport const ArtifactDefinition = lazy(() => import('./artifact-definition'));\nexport const Compiler = lazy(() => import('./compiler'));\nexport const IntentResolver = lazy(() => import('./intent-resolver'));\nexport const ReactSurface = lazy(() => import('./react-surface'));\nexport const ScriptSettings = lazy(() => import('./settings'));\n\nexport * from './capabilities';\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { Schema } from 'effect';\n\nimport { Capabilities, contributes, createIntent, defineModule, definePlugin, Events } from '@dxos/app-framework';\nimport { Ref } from '@dxos/echo';\nimport { ScriptType } from '@dxos/functions';\nimport { ClientEvents } from '@dxos/plugin-client';\nimport { SpaceCapabilities } from '@dxos/plugin-space';\nimport { defineObjectForm } from '@dxos/plugin-space/types';\n\nimport {\n AppGraphBuilder,\n ArtifactDefinition,\n Compiler,\n IntentResolver,\n ReactSurface,\n ScriptSettings,\n} from './capabilities';\nimport { ScriptEvents } from './events';\nimport { meta } from './meta';\nimport { translations } from './translations';\nimport { ScriptAction } from './types';\n\nexport const ScriptPlugin = () =>\n definePlugin(meta, [\n defineModule({\n id: `${meta.id}/module/settings`,\n activatesOn: Events.SetupSettings,\n activate: ScriptSettings,\n }),\n defineModule({\n id: `${meta.id}/module/compiler`,\n activatesOn: ScriptEvents.SetupCompiler,\n activate: Compiler,\n }),\n defineModule({\n id: `${meta.id}/module/translations`,\n activatesOn: Events.SetupTranslations,\n activate: () => contributes(Capabilities.Translations, translations),\n }),\n defineModule({\n id: `${meta.id}/module/metadata`,\n activatesOn: Events.SetupMetadata,\n activate: () =>\n contributes(Capabilities.Metadata, {\n id: ScriptType.typename,\n metadata: {\n icon: 'ph--code--regular',\n // TODO(wittjosiah): Move out of metadata.\n loadReferences: async (script: ScriptType) => await Ref.Array.loadAll([script.source]),\n },\n }),\n }),\n defineModule({\n id: `${meta.id}/module/app-graph-builder`,\n activatesOn: Events.SetupAppGraph,\n activate: AppGraphBuilder,\n }),\n defineModule({\n id: `${meta.id}/module/object-form`,\n activatesOn: ClientEvents.SetupSchema,\n activate: () =>\n contributes(\n SpaceCapabilities.ObjectForm,\n defineObjectForm({\n objectSchema: ScriptType,\n formSchema: ScriptAction.CreateScriptSchema.pipe(Schema.omit('initialTemplateId')),\n getIntent: (props, options) => createIntent(ScriptAction.Create, { ...props, space: options.space }),\n }),\n ),\n }),\n defineModule({\n id: `${meta.id}/module/react-surface`,\n activatesOn: Events.SetupReactSurface,\n // TODO(wittjosiah): Should occur before the script editor is loaded when surfaces activation is more granular.\n activatesBefore: [ScriptEvents.SetupCompiler],\n activate: ReactSurface,\n }),\n defineModule({\n id: `${meta.id}/module/intent-resolver`,\n activatesOn: Events.SetupIntentResolver,\n activate: IntentResolver,\n }),\n defineModule({\n id: `${meta.id}/module/artifact-definition`,\n activatesOn: Events.SetupArtifactDefinition,\n activate: ArtifactDefinition,\n }),\n ]);\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { defineEvent } from '@dxos/app-framework';\n\nimport { SCRIPT_PLUGIN } from './meta';\n\nexport namespace ScriptEvents {\n export const SetupCompiler = defineEvent(`${SCRIPT_PLUGIN}/event/setup-compiler`);\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { ScriptType } from '@dxos/functions';\nimport { type Resource } from '@dxos/react-ui';\n\nimport { meta } from './meta';\n\nexport const translations = [\n {\n 'en-US': {\n [ScriptType.typename]: {\n 'typename label': 'Script',\n 'typename label_zero': 'Scripts',\n 'typename label_one': 'Script',\n 'typename label_other': 'Scripts',\n 'object name placeholder': 'New script',\n },\n [meta.id]: {\n 'plugin name': 'Scripts',\n 'description label': 'Description',\n 'description placeholder': 'Enter description',\n 'binding placeholder': 'Function name',\n 'function request placeholder': 'Function request',\n 'deploy label': 'Deploy',\n 'deployed label': 'Current version of the script is deployed',\n 'upload failed label': 'Upload failed',\n 'copy link label': 'Copy function link',\n 'format label': 'Format',\n 'toggle details label': 'Toggle details panel',\n 'authenticate action label': 'Authenticate functions service',\n 'authenticate button label': 'Authenticate',\n 'name label': 'Name',\n 'remote function settings heading': 'Remote Function',\n 'function url label': 'Invocation URL',\n 'function binding label': 'Function binding',\n 'function binding placeholder': 'Enter binding name (e.g., NAME)',\n 'script publish settings label': 'Publishing',\n 'script publish settings description': 'Scripts can be shared publicly as Github gists.',\n 'no github token label': 'This space has no GitHub access token available.',\n 'open token manager label': 'Open Token Manager',\n 'publish label': 'Publish',\n 'publishing label': 'Publishing',\n 'editor input mode label': 'Editor input mode',\n 'select editor input mode placeholder': 'Select editor input mode…',\n 'settings editor input mode default label': 'Default',\n 'settings editor input mode vim label': 'Vim',\n 'settings editor input mode vscode label': 'VS Code',\n 'template select group label': 'Select template',\n 'function panel label': 'Debug Function',\n 'script test label': 'Test',\n 'script logs label': 'Logs',\n 'deployment dialog title': 'Default Scripts',\n 'deployment dialog scripts found message_one':\n 'We found the following script template for your new integration:',\n 'deployment dialog scripts found message_other':\n 'We found the following script templates for your new integration:',\n 'deployment dialog deploy functions button label_one': 'Create and deploy script',\n 'deployment dialog deploy functions button label_other': 'Create and deploy scripts',\n 'deployment dialog deploy functions pending button label_one': 'Deploying script',\n 'deployment dialog deploy functions pending button label_other': 'Deploying scripts',\n 'deployment dialog skip button label': 'Skip',\n 'script deployment toast label_one': 'Script deployed',\n 'script deployment toast label_other': 'Scripts deployed',\n 'script deployment toast description_one': 'Your script has been deployed successfully.',\n 'script deployment toast description_other': 'Your scripts have been deployed successfully.',\n 'script deployment toast close label_one': 'Close',\n 'script deployment toast close label_other': 'Close',\n 'script deployment error toast label_one': 'Script deployment failed',\n 'script deployment error toast label_other': 'Scripts deployment failed',\n 'script deployment error toast description_one': 'There was an error deploying your script.',\n 'script deployment error toast description_other': 'There was an error deploying your scripts.',\n 'script deployment error toast close label_one': 'Close',\n 'script deployment error toast close label_other': 'Close',\n },\n },\n },\n] as const satisfies Resource[];\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,SAASA,YAAY;AAEd,IAAMC,kBAAkBC,KAA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,aAAaC,mBAAmBC,KAAKC,OAAOC,KAAK,mBAAA,CAAA;MAC7DC,WAAW,CAACC,OAAOC,YAAYC,aAAaR,aAAaS,QAAQ;QAAE,GAAGH;QAAOI,OAAOH,QAAQG;MAAM,CAAA;IACpG,CAAA,CAAA;EAEN,CAAA;EACA9C,aAAa;IACXC,IAAI,GAAGF,KAAKE,EAAE;IACdC,aAAaC,OAAO4C;;IAEpBC,iBAAiB;MAACzC,aAAaC;;IAC/BH,UAAU4C;EACZ,CAAA;EACAjD,aAAa;IACXC,IAAI,GAAGF,KAAKE,EAAE;IACdC,aAAaC,OAAO+C;IACpB7C,UAAU8C;EACZ,CAAA;EACAnD,aAAa;IACXC,IAAI,GAAGF,KAAKE,EAAE;IACdC,aAAaC,OAAOiD;IACpB/C,UAAUgD;EACZ,CAAA;CACD;",
6
+ "names": ["lazy", "AppGraphBuilder", "lazy", "ArtifactDefinition", "Compiler", "IntentResolver", "ReactSurface", "ScriptSettings", "Schema", "Capabilities", "contributes", "createIntent", "defineModule", "definePlugin", "Events", "Ref", "ScriptType", "ClientEvents", "SpaceCapabilities", "defineObjectForm", "defineEvent", "ScriptEvents", "SetupCompiler", "defineEvent", "SCRIPT_PLUGIN", "ScriptType", "translations", "ScriptType", "typename", "meta", "id", "ScriptPlugin", "definePlugin", "meta", "defineModule", "id", "activatesOn", "Events", "SetupSettings", "activate", "ScriptSettings", "ScriptEvents", "SetupCompiler", "Compiler", "SetupTranslations", "contributes", "Capabilities", "Translations", "translations", "SetupMetadata", "Metadata", "ScriptType", "typename", "metadata", "icon", "loadReferences", "script", "Ref", "Array", "loadAll", "source", "SetupAppGraph", "AppGraphBuilder", "ClientEvents", "SetupSchema", "SpaceCapabilities", "ObjectForm", "defineObjectForm", "objectSchema", "formSchema", "ScriptAction", "CreateScriptSchema", "pipe", "Schema", "omit", "getIntent", "props", "options", "createIntent", "Create", "space", "SetupReactSurface", "activatesBefore", "ReactSurface", "SetupIntentResolver", "IntentResolver", "SetupArtifactDefinition", "ArtifactDefinition"]
7
7
  }
@@ -1,20 +1,20 @@
1
1
  import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
- import "./chunk-B4TP3LSZ.mjs";
2
+ import "./chunk-HD6MDK3H.mjs";
3
3
  import {
4
4
  DEPLOYMENT_DIALOG
5
- } from "./chunk-T7XDCUTF.mjs";
5
+ } from "./chunk-YVJGDDNV.mjs";
6
6
  import {
7
7
  templates
8
- } from "./chunk-W2DAXWHA.mjs";
9
- import "./chunk-MJJQBUOL.mjs";
8
+ } from "./chunk-ORZMINLO.mjs";
9
+ import "./chunk-ABAPR7VQ.mjs";
10
10
  import {
11
11
  ScriptAction
12
- } from "./chunk-UESZKXLR.mjs";
12
+ } from "./chunk-OVSJYR6O.mjs";
13
13
  import {
14
14
  defaultScriptsForIntegration
15
- } from "./chunk-AEB5TPEW.mjs";
15
+ } from "./chunk-AHXJ6NQU.mjs";
16
16
 
17
- // packages/plugins/plugin-script/src/capabilities/intent-resolver.ts
17
+ // src/capabilities/intent-resolver.ts
18
18
  import { Octokit } from "@octokit/core";
19
19
  import { Predicate } from "effect";
20
20
  import { contributes, Capabilities, createResolver, createIntent, LayoutAction } from "@dxos/app-framework";
@@ -88,4 +88,4 @@ var intent_resolver_default = () => contributes(Capabilities.IntentResolver, [
88
88
  export {
89
89
  intent_resolver_default as default
90
90
  };
91
- //# sourceMappingURL=intent-resolver-HTM5PSRZ.mjs.map
91
+ //# sourceMappingURL=intent-resolver-XLV6FPWH.mjs.map