@dxos/plugin-script 0.6.12-staging.e11e696 → 0.6.12

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 (179) hide show
  1. package/dist/lib/browser/{ScriptContainer-AGDWRBHJ.mjs → ScriptEditor-5Y3EROG3.mjs} +106 -258
  2. package/dist/lib/browser/ScriptEditor-5Y3EROG3.mjs.map +7 -0
  3. package/dist/lib/browser/TypescriptEditor-GPE72Y6I.mjs +9 -0
  4. package/dist/lib/browser/{chunk-G6FWCTGT.mjs → chunk-DL5XQRQM.mjs} +5 -7
  5. package/dist/lib/browser/chunk-DL5XQRQM.mjs.map +7 -0
  6. package/dist/lib/browser/{chunk-MDX7ACIK.mjs → chunk-JBACGDOJ.mjs} +6 -3
  7. package/dist/lib/browser/chunk-JBACGDOJ.mjs.map +7 -0
  8. package/dist/lib/browser/chunk-MRGOT5RF.mjs +78 -0
  9. package/dist/lib/browser/chunk-MRGOT5RF.mjs.map +7 -0
  10. package/dist/lib/browser/{chunk-CAEANETO.mjs → chunk-O4LWBX6A.mjs} +2 -2
  11. package/dist/lib/browser/{chunk-CAEANETO.mjs.map → chunk-O4LWBX6A.mjs.map} +2 -2
  12. package/dist/lib/browser/{chunk-G6H56WFS.mjs → chunk-RHEZ5LUU.mjs} +2 -51
  13. package/dist/lib/browser/{chunk-G6H56WFS.mjs.map → chunk-RHEZ5LUU.mjs.map} +4 -4
  14. package/dist/lib/browser/edge/index.mjs +1 -3
  15. package/dist/lib/browser/index.mjs +62 -80
  16. package/dist/lib/browser/index.mjs.map +4 -4
  17. package/dist/lib/browser/meta.json +1 -1
  18. package/dist/lib/browser/meta.mjs +1 -1
  19. package/dist/lib/browser/types/index.mjs +2 -2
  20. package/dist/lib/node/ScriptEditor-YCUQFWQM.cjs +526 -0
  21. package/dist/lib/node/ScriptEditor-YCUQFWQM.cjs.map +7 -0
  22. package/dist/lib/node/{chunk-OJ77BZRH.cjs → TypescriptEditor-M3WWFIP2.cjs} +8 -19
  23. package/dist/lib/node/TypescriptEditor-M3WWFIP2.cjs.map +7 -0
  24. package/dist/lib/node/{chunk-ACLCRWDB.cjs → chunk-4GTXIELQ.cjs} +6 -44
  25. package/dist/lib/node/chunk-4GTXIELQ.cjs.map +7 -0
  26. package/dist/lib/node/chunk-4VMNBXWU.cjs +54 -0
  27. package/dist/lib/node/chunk-4VMNBXWU.cjs.map +7 -0
  28. package/dist/lib/node/{chunk-2PZKJXNP.cjs → chunk-5RBVXKXT.cjs} +6 -6
  29. package/dist/lib/node/{chunk-2PZKJXNP.cjs.map → chunk-5RBVXKXT.cjs.map} +2 -2
  30. package/dist/lib/node/chunk-IMLDKD5Y.cjs +111 -0
  31. package/dist/lib/node/chunk-IMLDKD5Y.cjs.map +7 -0
  32. package/dist/lib/node/{chunk-UZ3ZXEBF.cjs → chunk-PFH3ROEH.cjs} +8 -11
  33. package/dist/lib/node/chunk-PFH3ROEH.cjs.map +7 -0
  34. package/dist/lib/node/edge/index.cjs +8 -10
  35. package/dist/lib/node/edge/index.cjs.map +2 -2
  36. package/dist/lib/node/index.cjs +82 -95
  37. package/dist/lib/node/index.cjs.map +4 -4
  38. package/dist/lib/node/meta.cjs +3 -3
  39. package/dist/lib/node/meta.cjs.map +1 -1
  40. package/dist/lib/node/meta.json +1 -1
  41. package/dist/lib/node/types/index.cjs +5 -5
  42. package/dist/lib/node/types/index.cjs.map +1 -1
  43. package/dist/types/src/ScriptPlugin.d.ts.map +1 -1
  44. package/dist/types/src/components/DebugPanel.d.ts.map +1 -0
  45. package/dist/types/src/components/{FrameContainer → ScriptBlock/FrameContainer}/FrameContainer.d.ts +1 -1
  46. package/dist/types/src/components/ScriptBlock/FrameContainer/FrameContainer.d.ts.map +1 -0
  47. package/dist/types/src/components/ScriptBlock/FrameContainer/frame.d.ts.map +1 -0
  48. package/dist/types/src/components/ScriptBlock/FrameContainer/index.d.ts.map +1 -0
  49. package/dist/types/src/components/ScriptBlock/ScriptBlock.d.ts +3 -1
  50. package/dist/types/src/components/ScriptBlock/ScriptBlock.d.ts.map +1 -1
  51. package/dist/types/src/components/ScriptBlock/ScriptBlock.stories.d.ts +1 -1
  52. package/dist/types/src/components/ScriptBlock/ScriptBlock.stories.d.ts.map +1 -1
  53. package/dist/types/src/components/ScriptBlock/Splitter/Splitter.d.ts +15 -0
  54. package/dist/types/src/components/ScriptBlock/Splitter/Splitter.d.ts.map +1 -0
  55. package/dist/types/src/components/ScriptBlock/Splitter/Splitter.stories.d.ts +13 -0
  56. package/dist/types/src/components/ScriptBlock/Splitter/Splitter.stories.d.ts.map +1 -0
  57. package/dist/types/src/components/ScriptBlock/Splitter/index.d.ts +2 -0
  58. package/dist/types/src/components/ScriptBlock/Splitter/index.d.ts.map +1 -0
  59. package/dist/types/src/components/ScriptEditor.d.ts +5 -4
  60. package/dist/types/src/components/ScriptEditor.d.ts.map +1 -1
  61. package/dist/types/src/components/Toolbar.d.ts +13 -0
  62. package/dist/types/src/components/Toolbar.d.ts.map +1 -0
  63. package/dist/types/src/components/Toolbar.stories.d.ts +14 -0
  64. package/dist/types/src/components/Toolbar.stories.d.ts.map +1 -0
  65. package/dist/types/src/components/{TypescriptEditor/TypescriptEditor.d.ts → TypescriptEditor.d.ts} +2 -1
  66. package/dist/types/src/components/TypescriptEditor.d.ts.map +1 -0
  67. package/dist/types/src/components/TypescriptEditor.stories.d.ts +10 -0
  68. package/dist/types/src/components/TypescriptEditor.stories.d.ts.map +1 -0
  69. package/dist/types/src/components/index.d.ts +2 -2
  70. package/dist/types/src/components/index.d.ts.map +1 -1
  71. package/dist/types/src/edge/functions.d.ts +0 -1
  72. package/dist/types/src/edge/functions.d.ts.map +1 -1
  73. package/dist/types/src/meta.d.ts +4 -1
  74. package/dist/types/src/meta.d.ts.map +1 -1
  75. package/dist/types/src/translations.d.ts +0 -2
  76. package/dist/types/src/translations.d.ts.map +1 -1
  77. package/dist/types/src/types/script.d.ts +4 -4
  78. package/dist/types/src/types/types.d.ts +3 -4
  79. package/dist/types/src/types/types.d.ts.map +1 -1
  80. package/package.json +55 -61
  81. package/src/ScriptPlugin.tsx +38 -22
  82. package/src/bundler/bundler.test.ts +2 -12
  83. package/src/components/{DebugPanel/DebugPanel.tsx → DebugPanel.tsx} +41 -48
  84. package/src/components/{FrameContainer → ScriptBlock/FrameContainer}/FrameContainer.tsx +1 -1
  85. package/src/components/ScriptBlock/ScriptBlock.stories.tsx +3 -4
  86. package/src/components/ScriptBlock/ScriptBlock.tsx +36 -10
  87. package/src/components/ScriptBlock/Splitter/Splitter.stories.tsx +37 -0
  88. package/src/components/ScriptBlock/Splitter/Splitter.tsx +52 -0
  89. package/src/components/{Toolbar → ScriptBlock/Splitter}/index.ts +1 -1
  90. package/src/components/ScriptEditor.tsx +46 -47
  91. package/src/components/{Toolbar/Toolbar.stories.tsx → Toolbar.stories.tsx} +1 -10
  92. package/src/components/Toolbar.tsx +147 -0
  93. package/src/components/{TypescriptEditor/TypescriptEditor.stories.tsx → TypescriptEditor.stories.tsx} +28 -7
  94. package/src/components/{TypescriptEditor/TypescriptEditor.tsx → TypescriptEditor.tsx} +3 -1
  95. package/src/components/index.ts +2 -3
  96. package/src/edge/functions.ts +0 -1
  97. package/src/meta.tsx +6 -2
  98. package/src/translations.ts +0 -2
  99. package/src/types/types.ts +5 -9
  100. package/dist/lib/browser/ScriptContainer-AGDWRBHJ.mjs.map +0 -7
  101. package/dist/lib/browser/chunk-G6FWCTGT.mjs.map +0 -7
  102. package/dist/lib/browser/chunk-MDX7ACIK.mjs.map +0 -7
  103. package/dist/lib/node/ScriptContainer-5R3NWYKS.cjs +0 -668
  104. package/dist/lib/node/ScriptContainer-5R3NWYKS.cjs.map +0 -7
  105. package/dist/lib/node/chunk-ACLCRWDB.cjs.map +0 -7
  106. package/dist/lib/node/chunk-OJ77BZRH.cjs.map +0 -7
  107. package/dist/lib/node/chunk-UZ3ZXEBF.cjs.map +0 -7
  108. package/dist/lib/node-esm/ScriptContainer-ZY2XG3GH.mjs +0 -666
  109. package/dist/lib/node-esm/ScriptContainer-ZY2XG3GH.mjs.map +0 -7
  110. package/dist/lib/node-esm/chunk-2NX3HWPM.mjs +0 -245
  111. package/dist/lib/node-esm/chunk-2NX3HWPM.mjs.map +0 -7
  112. package/dist/lib/node-esm/chunk-7BZDZF7Z.mjs +0 -47
  113. package/dist/lib/node-esm/chunk-7BZDZF7Z.mjs.map +0 -7
  114. package/dist/lib/node-esm/chunk-LDLNTVAK.mjs +0 -280
  115. package/dist/lib/node-esm/chunk-LDLNTVAK.mjs.map +0 -7
  116. package/dist/lib/node-esm/chunk-TZ3Z4SII.mjs +0 -20
  117. package/dist/lib/node-esm/chunk-TZ3Z4SII.mjs.map +0 -7
  118. package/dist/lib/node-esm/edge/index.mjs +0 -22
  119. package/dist/lib/node-esm/index.mjs +0 -310
  120. package/dist/lib/node-esm/index.mjs.map +0 -7
  121. package/dist/lib/node-esm/meta.json +0 -1
  122. package/dist/lib/node-esm/meta.mjs +0 -10
  123. package/dist/lib/node-esm/meta.mjs.map +0 -7
  124. package/dist/lib/node-esm/types/index.mjs +0 -13
  125. package/dist/lib/node-esm/types/index.mjs.map +0 -7
  126. package/dist/types/src/components/DebugPanel/DebugPanel.d.ts.map +0 -1
  127. package/dist/types/src/components/DebugPanel/index.d.ts +0 -2
  128. package/dist/types/src/components/DebugPanel/index.d.ts.map +0 -1
  129. package/dist/types/src/components/FrameContainer/FrameContainer.d.ts.map +0 -1
  130. package/dist/types/src/components/FrameContainer/frame.d.ts.map +0 -1
  131. package/dist/types/src/components/FrameContainer/index.d.ts.map +0 -1
  132. package/dist/types/src/components/ScriptContainer.d.ts +0 -5
  133. package/dist/types/src/components/ScriptContainer.d.ts.map +0 -1
  134. package/dist/types/src/components/ScriptSettings/ScriptSettings.d.ts +0 -6
  135. package/dist/types/src/components/ScriptSettings/ScriptSettings.d.ts.map +0 -1
  136. package/dist/types/src/components/ScriptSettings/index.d.ts +0 -2
  137. package/dist/types/src/components/ScriptSettings/index.d.ts.map +0 -1
  138. package/dist/types/src/components/Toolbar/Toolbar.d.ts +0 -23
  139. package/dist/types/src/components/Toolbar/Toolbar.d.ts.map +0 -1
  140. package/dist/types/src/components/Toolbar/Toolbar.stories.d.ts +0 -17
  141. package/dist/types/src/components/Toolbar/Toolbar.stories.d.ts.map +0 -1
  142. package/dist/types/src/components/Toolbar/index.d.ts +0 -2
  143. package/dist/types/src/components/Toolbar/index.d.ts.map +0 -1
  144. package/dist/types/src/components/TypescriptEditor/TypescriptEditor.d.ts.map +0 -1
  145. package/dist/types/src/components/TypescriptEditor/TypescriptEditor.stories.d.ts +0 -10
  146. package/dist/types/src/components/TypescriptEditor/TypescriptEditor.stories.d.ts.map +0 -1
  147. package/dist/types/src/components/TypescriptEditor/index.d.ts +0 -2
  148. package/dist/types/src/components/TypescriptEditor/index.d.ts.map +0 -1
  149. package/dist/types/src/templates/chat.d.ts +0 -6
  150. package/dist/types/src/templates/chat.d.ts.map +0 -1
  151. package/dist/types/src/templates/chess.d.ts +0 -6
  152. package/dist/types/src/templates/chess.d.ts.map +0 -1
  153. package/dist/types/src/templates/echo.d.ts +0 -6
  154. package/dist/types/src/templates/echo.d.ts.map +0 -1
  155. package/dist/types/src/templates/email.d.ts +0 -6
  156. package/dist/types/src/templates/email.d.ts.map +0 -1
  157. package/dist/types/src/templates/forex.d.ts +0 -6
  158. package/dist/types/src/templates/forex.d.ts.map +0 -1
  159. package/dist/types/src/templates.d.ts +0 -8
  160. package/dist/types/src/templates.d.ts.map +0 -1
  161. package/src/components/DebugPanel/index.ts +0 -5
  162. package/src/components/ScriptContainer.tsx +0 -22
  163. package/src/components/ScriptSettings/ScriptSettings.tsx +0 -47
  164. package/src/components/ScriptSettings/index.ts +0 -5
  165. package/src/components/Toolbar/Toolbar.tsx +0 -180
  166. package/src/components/TypescriptEditor/index.ts +0 -5
  167. package/src/templates/chat.ts +0 -102
  168. package/src/templates/chess.ts +0 -41
  169. package/src/templates/echo.ts +0 -15
  170. package/src/templates/email.ts +0 -38
  171. package/src/templates/forex.ts +0 -21
  172. package/src/templates.ts +0 -54
  173. /package/dist/lib/{node-esm/edge/index.mjs.map → browser/TypescriptEditor-GPE72Y6I.mjs.map} +0 -0
  174. /package/dist/types/src/components/{DebugPanel/DebugPanel.d.ts → DebugPanel.d.ts} +0 -0
  175. /package/dist/types/src/components/{FrameContainer → ScriptBlock/FrameContainer}/frame.d.ts +0 -0
  176. /package/dist/types/src/components/{FrameContainer → ScriptBlock/FrameContainer}/index.d.ts +0 -0
  177. /package/src/components/{FrameContainer → ScriptBlock/FrameContainer}/frame.html +0 -0
  178. /package/src/components/{FrameContainer → ScriptBlock/FrameContainer}/frame.tsx +0 -0
  179. /package/src/components/{FrameContainer → ScriptBlock/FrameContainer}/index.ts +0 -0
@@ -107,7 +107,6 @@ var publicKeyToDid = (key) => {
107
107
  // packages/plugins/experimental/plugin-script/src/edge/functions.ts
108
108
  var __dxlog_file = "/home/runner/work/dxos/dxos/packages/plugins/experimental/plugin-script/src/edge/functions.ts";
109
109
  var USERFUNCTIONS_META_KEY = "dxos.org/service/function";
110
- var USERFUNCTIONS_PRESET_META_KEY = "dxos.org/service/function-preset";
111
110
  var USERFUNCTIONS_CREDENTIAL_CAPABILITY = "composer:beta";
112
111
  var defaultUserFunctionsBaseUrl = "https://edge-main.dxos.workers.dev/functions";
113
112
  var getBaseUrl = (config) => {
@@ -134,7 +133,7 @@ var uploadWorkerFunction = async ({ clientConfig, halo, name, source, ownerDid,
134
133
  uploadUrl: uploadUrl.toString()
135
134
  }, {
136
135
  F: __dxlog_file,
137
- L: 72,
136
+ L: 71,
138
137
  S: void 0,
139
138
  C: (f, a) => f(...a)
140
139
  });
@@ -158,7 +157,7 @@ var uploadWorkerFunction = async ({ clientConfig, halo, name, source, ownerDid,
158
157
  res
159
158
  }, {
160
159
  F: __dxlog_file,
161
- L: 83,
160
+ L: 82,
162
161
  S: void 0,
163
162
  C: (f, a) => f(...a)
164
163
  });
@@ -207,13 +206,13 @@ var presentationForIdentity = async ({ halo, timeout }) => {
207
206
  credential
208
207
  }, {
209
208
  F: __dxlog_file,
210
- L: 129,
209
+ L: 128,
211
210
  S: void 0,
212
211
  C: (f, a) => f(...a)
213
212
  });
214
213
  invariant(credential.id, "beta credential missing id", {
215
214
  F: __dxlog_file,
216
- L: 131,
215
+ L: 130,
217
216
  S: void 0,
218
217
  A: [
219
218
  "credential.id",
@@ -235,9 +234,8 @@ export {
235
234
  codec,
236
235
  matchServiceCredential,
237
236
  publicKeyToDid,
238
- USERFUNCTIONS_PRESET_META_KEY,
239
237
  uploadWorkerFunction,
240
238
  getUserFunctionUrlInMetadata,
241
239
  setUserFunctionUrlInMetadata
242
240
  };
243
- //# sourceMappingURL=chunk-G6FWCTGT.mjs.map
241
+ //# sourceMappingURL=chunk-DL5XQRQM.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/edge/codec.ts", "../../../src/edge/header-codec.ts", "../../../src/edge/functions.ts", "../../../src/edge/hub-protocol.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { PublicKey } from '@dxos/keys';\n\nimport { HeaderCodec, type EncodedKey } from './header-codec';\n\nexport const codec = new HeaderCodec<PublicKey>({\n isKey: (value: any): value is PublicKey => value instanceof PublicKey,\n encode: (key: PublicKey): EncodedKey => ({ __k: key.toHex() }),\n decode: (value: EncodedKey): PublicKey => PublicKey.fromHex(value.__k),\n});\n", "//\n// Copyright 2024 DXOS.org\n//\n\n// TODO(burdon): Factor out from @dxos/hub-protocol\n\nconst ENCODING = 'base64';\n\nexport type EncodedKey = { __k: string };\n\nexport type EncodedBytes = { __b: string };\n\nexport type EncodedTimestamp = { __t: number };\n\nexport interface KeyCodec<KeyType> {\n isKey(value: any): value is KeyType;\n encode(key: KeyType): EncodedKey;\n decode(value: EncodedKey): KeyType;\n}\n\n// TODO(wittjosiah): Use deepMapValues from @dxos/util -- it handles recursion for you.\nexport class HeaderCodec<Key> {\n constructor(private readonly _keyCodec: KeyCodec<Key>) {}\n\n encode(obj: any): string {\n const objectToEncode = this._prepareForEncoding(obj);\n const encoded = Buffer.from(JSON.stringify(objectToEncode));\n return encoded.toString(ENCODING);\n }\n\n decode<Type>(buffer: string): Type {\n const json = JSON.parse(Buffer.from(buffer, ENCODING).toString());\n return this._decodeRecursive(json);\n }\n\n private _decodeRecursive(obj: any): any {\n return this._recurse(obj, (value) => {\n if (isEncodedBytes(value)) {\n return decodeBytes(value.__b);\n }\n if (isEncodedKey(value)) {\n return this._keyCodec.decode(value);\n }\n if (isEncodedDate(value)) {\n return decodeDate(value);\n }\n return null;\n });\n }\n\n private _prepareForEncoding(obj: any): any {\n return this._recurse(obj, (value) => {\n if (value instanceof Uint8Array) {\n return { __b: encodeBytes(value) };\n }\n if (this._keyCodec.isKey(value)) {\n return this._keyCodec.encode(value);\n }\n if (value instanceof Date) {\n return encodeDate(value);\n }\n return null;\n });\n }\n\n private _recurse(obj: any, handler: (obj: object) => any | null): any {\n if (typeof obj !== 'object') {\n return obj;\n }\n const handled = handler(obj);\n if (handled != null) {\n return handled;\n }\n if (Array.isArray(obj)) {\n const result = [];\n for (const elem of obj) {\n result.push(this._recurse(elem, handler));\n }\n return result;\n }\n const result: any = {};\n for (const [key, value] of Object.entries(obj)) {\n result[key] = this._recurse(value, handler);\n }\n return result;\n }\n}\n\nconst isEncodedKey = (obj: object): obj is EncodedKey => '__k' in obj && typeof obj.__k === 'string';\nconst isEncodedBytes = (obj: object): obj is EncodedBytes => '__b' in obj && typeof obj.__b === 'string';\nconst isEncodedDate = (obj: object): obj is EncodedTimestamp => '__t' in obj && typeof obj.__t === 'number';\n\nconst encodeDate = (date: Date) => ({ __t: date.getTime() });\nconst decodeDate = (timestamp: EncodedTimestamp) => new Date(timestamp.__t);\n\nconst encodeBytes = (bytes: Uint8Array) => Buffer.from(bytes).toString(ENCODING);\nconst decodeBytes = (bytes: string) => Buffer.from(bytes, ENCODING);\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { type DID } from 'iso-did/types';\n\nimport { Trigger } from '@dxos/async';\nimport { type Config } from '@dxos/client';\nimport { type Halo } from '@dxos/client-protocol';\nimport { type ObjectMeta } from '@dxos/echo-schema';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { type Credential } from '@dxos/protocols/proto/dxos/halo/credentials';\n\nimport { codec } from './codec';\nimport { matchServiceCredential } from './hub-protocol';\n\n// TODO: use URL scheme for source?\nconst USERFUNCTIONS_META_KEY = 'dxos.org/service/function';\nconst USERFUNCTIONS_CREDENTIAL_CAPABILITY = 'composer:beta';\n\n// TODO: Synchronize API types with server\nexport type UserFunctionUploadResult = {\n result: 'success' | 'error';\n errorMessage?: string;\n functionId?: string;\n functionVersionNumber?: number;\n};\n\nexport type UploadWorkerProps = {\n clientConfig: Config;\n halo: Halo;\n name?: string;\n source: string;\n functionId?: string;\n ownerDid: DID;\n credentialLoadTimeout?: number; // ms to wait for credentials to load\n};\n\n// TODO(burdon): Config.\nconst defaultUserFunctionsBaseUrl = 'https://edge-main.dxos.workers.dev/functions'; // 'http://localhost:8600';\n\nconst getBaseUrl = (config: Config) => {\n if (config.values.runtime?.services?.edge?.url) {\n const url = new URL('/functions', config.values.runtime?.services?.edge?.url);\n url.protocol = 'https';\n return url.toString();\n } else {\n return defaultUserFunctionsBaseUrl;\n }\n};\n\nexport const uploadWorkerFunction = async ({\n clientConfig,\n halo,\n name,\n source,\n ownerDid,\n functionId,\n credentialLoadTimeout,\n}: UploadWorkerProps) => {\n const identity = halo.identity.get();\n if (!identity) {\n throw new Error('Identity not available');\n }\n const userFunctionsBaseUrl = getBaseUrl(clientConfig);\n\n // TODO: codify naming convention\n const uploadUrl = `${userFunctionsBaseUrl}/${ownerDid}` + (functionId ? `/${functionId}` : '');\n\n log('Upload', { functionId, source, name, identityKey: identity.identityKey, uploadUrl: uploadUrl.toString() });\n const response = await fetch(uploadUrl, {\n method: 'PUT',\n body: JSON.stringify({ script: source, name }),\n headers: await presentationForIdentity({ halo, timeout: credentialLoadTimeout }),\n });\n if (!response.ok) {\n return (await response.json()) as UserFunctionUploadResult;\n }\n\n const res = await response.json();\n log('Upload response', { status: response.status, res });\n\n return res as UserFunctionUploadResult;\n};\n\nexport const getUserFunctionUrlInMetadata = (meta: ObjectMeta) => {\n return meta.keys.find((key) => key.source === USERFUNCTIONS_META_KEY)?.id;\n};\n\nexport const setUserFunctionUrlInMetadata = (meta: ObjectMeta, functionUrl: string) => {\n const key = meta.keys.find((key) => key.source === USERFUNCTIONS_META_KEY);\n if (key) {\n if (key.id !== functionUrl) {\n throw new Error('Metadata mismatch');\n }\n } else {\n meta.keys.push({ source: USERFUNCTIONS_META_KEY, id: functionUrl });\n }\n};\n\n// TODO: handle team owner\n\nconst presentationForIdentity = async ({ halo, timeout }: { halo: Halo; timeout?: number }) => {\n let credential: Credential | undefined;\n\n if (timeout) {\n const credentialsLoaded = new Trigger();\n halo.credentials.subscribe((c) => {\n credential = c.find(matchServiceCredential([USERFUNCTIONS_CREDENTIAL_CAPABILITY]));\n if (credential) {\n credentialsLoaded.wake();\n }\n });\n await credentialsLoaded.wait({\n timeout,\n });\n } else {\n credential = halo\n .queryCredentials()\n .toSorted((a, b) => b.issuanceDate.getTime() - a.issuanceDate.getTime())\n .find(matchServiceCredential([USERFUNCTIONS_CREDENTIAL_CAPABILITY]));\n }\n\n if (!credential) {\n throw new Error('No credential found');\n }\n log('credential found', { credential });\n // TODO(wittjosiah): If id is required to present credentials, then it should always be present for queried credentials.\n invariant(credential.id, 'beta credential missing id');\n const presentation = await halo.presentCredentials({ ids: [credential.id] });\n\n return { Authorization: `Bearer ${codec.encode(presentation)}` };\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { type DID } from 'iso-did/types';\n\nimport { type Credential } from '@dxos/client/halo';\nimport { type PublicKey } from '@dxos/keys';\n\n// TODO(burdon): Factor out to @dxos/hub-protocol.\n\nexport const matchServiceCredential =\n (capabilities: string[] = []) =>\n (credential: Credential) => {\n if (credential.subject.assertion['@type'] !== 'dxos.halo.credentials.ServiceAccess') {\n return false;\n }\n\n const { capabilities: credentialCapabilities } = credential.subject.assertion;\n return capabilities.every((capability) => credentialCapabilities.includes(capability));\n };\n\n// TODO: reconcile with @dxos/hub-protocol\n\nexport const publicKeyToDid = (key: PublicKey): DID => {\n return `did:key:${key.toHex()}`;\n};\n"],
5
+ "mappings": ";AAIA,SAASA,iBAAiB;;;ACE1B,IAAMC,WAAW;AAeV,IAAMC,cAAN,MAAMA;EACXC,YAA6BC,WAA0B;SAA1BA,YAAAA;EAA2B;EAExDC,OAAOC,KAAkB;AACvB,UAAMC,iBAAiB,KAAKC,oBAAoBF,GAAAA;AAChD,UAAMG,UAAUC,OAAOC,KAAKC,KAAKC,UAAUN,cAAAA,CAAAA;AAC3C,WAAOE,QAAQK,SAASb,QAAAA;EAC1B;EAEAc,OAAaC,QAAsB;AACjC,UAAMC,OAAOL,KAAKM,MAAMR,OAAOC,KAAKK,QAAQf,QAAAA,EAAUa,SAAQ,CAAA;AAC9D,WAAO,KAAKK,iBAAiBF,IAAAA;EAC/B;EAEQE,iBAAiBb,KAAe;AACtC,WAAO,KAAKc,SAASd,KAAK,CAACe,UAAAA;AACzB,UAAIC,eAAeD,KAAAA,GAAQ;AACzB,eAAOE,YAAYF,MAAMG,GAAG;MAC9B;AACA,UAAIC,aAAaJ,KAAAA,GAAQ;AACvB,eAAO,KAAKjB,UAAUW,OAAOM,KAAAA;MAC/B;AACA,UAAIK,cAAcL,KAAAA,GAAQ;AACxB,eAAOM,WAAWN,KAAAA;MACpB;AACA,aAAO;IACT,CAAA;EACF;EAEQb,oBAAoBF,KAAe;AACzC,WAAO,KAAKc,SAASd,KAAK,CAACe,UAAAA;AACzB,UAAIA,iBAAiBO,YAAY;AAC/B,eAAO;UAAEJ,KAAKK,YAAYR,KAAAA;QAAO;MACnC;AACA,UAAI,KAAKjB,UAAU0B,MAAMT,KAAAA,GAAQ;AAC/B,e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AACLc,iBAAapC,KACV6C,iBAAgB,EAChBC,SAAS,CAACC,GAAGC,MAAMA,EAAEC,aAAaC,QAAO,IAAKH,EAAEE,aAAaC,QAAO,CAAA,EACpEpB,KAAKY,uBAAuB;MAACxD;KAAoC,CAAA;EACtE;AAEA,MAAI,CAACkD,YAAY;AACf,UAAM,IAAI5B,MAAM,qBAAA;EAClB;AACAG,MAAI,oBAAoB;IAAEyB;EAAW,GAAA;;;;;;AAErCe,YAAUf,WAAWJ,IAAI,8BAAA;;;;;;;;;AACzB,QAAMoB,eAAe,MAAMpD,KAAKqD,mBAAmB;IAAEC,KAAK;MAAClB,WAAWJ;;EAAI,CAAA;AAE1E,SAAO;IAAEuB,eAAe,UAAUC,MAAMC,OAAOL,YAAAA,CAAAA;EAAgB;AACjE;",
6
+ "names": ["PublicKey", "ENCODING", "HeaderCodec", "constructor", "_keyCodec", "encode", "obj", "objectToEncode", "_prepareForEncoding", "encoded", "Buffer", "from", "JSON", "stringify", "toString", "decode", "buffer", "json", "parse", "_decodeRecursive", "_recurse", "value", "isEncodedBytes", "decodeBytes", "__b", "isEncodedKey", "isEncodedDate", "decodeDate", "Uint8Array", "encodeBytes", "isKey", "Date", "encodeDate", "handler", "handled", "Array", "isArray", "result", "elem", "push", "key", "Object", "entries", "__k", "__t", "date", "getTime", "timestamp", "bytes", "codec", "HeaderCodec", "isKey", "value", "PublicKey", "encode", "key", "__k", "toHex", "decode", "fromHex", "Trigger", "invariant", "log", "matchServiceCredential", "capabilities", "credential", "subject", "assertion", "credentialCapabilities", "every", "capability", "includes", "publicKeyToDid", "key", "toHex", "USERFUNCTIONS_META_KEY", "USERFUNCTIONS_CREDENTIAL_CAPABILITY", "defaultUserFunctionsBaseUrl", "getBaseUrl", "config", "values", "runtime", "services", "edge", "url", "URL", "protocol", "toString", "uploadWorkerFunction", "clientConfig", "halo", "name", "source", "ownerDid", "functionId", "credentialLoadTimeout", "identity", "get", "Error", "userFunctionsBaseUrl", "uploadUrl", "log", "identityKey", "response", "fetch", "method", "body", "JSON", "stringify", "script", "headers", "presentationForIdentity", "timeout", "ok", "json", "res", "status", "getUserFunctionUrlInMetadata", "meta", "keys", "find", "key", "id", "setUserFunctionUrlInMetadata", "functionUrl", "push", "credential", "credentialsLoaded", "Trigger", "credentials", "subscribe", "c", "matchServiceCredential", "wake", "wait", "queryCredentials", "toSorted", "a", "b", "issuanceDate", "getTime", "invariant", "presentation", "presentCredentials", "ids", "Authorization", "codec", "encode"]
7
+ }
@@ -1,18 +1,21 @@
1
1
  // packages/plugins/experimental/plugin-script/src/meta.tsx
2
+ import { Code } from "@phosphor-icons/react";
3
+ import React from "react";
2
4
  import { pluginMeta } from "@dxos/app-framework";
3
5
  var SCRIPT_PLUGIN = "dxos.org/plugin/script";
4
6
  var meta_default = pluginMeta({
5
7
  id: SCRIPT_PLUGIN,
6
8
  name: "Scripts",
7
- description: "Distributed functions.",
9
+ description: "Live code notebooks.",
8
10
  tags: [
9
11
  "experimental"
10
12
  ],
11
- icon: "ph--code--regular"
13
+ iconComponent: (props) => /* @__PURE__ */ React.createElement(Code, props),
14
+ iconSymbol: "ph--code--regular"
12
15
  });
13
16
 
14
17
  export {
15
18
  SCRIPT_PLUGIN,
16
19
  meta_default
17
20
  };
18
- //# sourceMappingURL=chunk-MDX7ACIK.mjs.map
21
+ //# sourceMappingURL=chunk-JBACGDOJ.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/meta.tsx"],
4
+ "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { Code, type IconProps } from '@phosphor-icons/react';\nimport React from 'react';\n\nimport { pluginMeta } from '@dxos/app-framework';\n\nexport const SCRIPT_PLUGIN = 'dxos.org/plugin/script';\n\nexport default pluginMeta({\n id: SCRIPT_PLUGIN,\n name: 'Scripts',\n description: 'Live code notebooks.',\n tags: ['experimental'],\n iconComponent: (props: IconProps) => <Code {...props} />,\n iconSymbol: 'ph--code--regular',\n});\n"],
5
+ "mappings": ";AAIA,SAASA,YAA4B;AACrC,OAAOC,WAAW;AAElB,SAASC,kBAAkB;AAEpB,IAAMC,gBAAgB;AAE7B,IAAA,eAAeC,WAAW;EACxBC,IAAIF;EACJG,MAAM;EACNC,aAAa;EACbC,MAAM;IAAC;;EACPC,eAAe,CAACC,UAAqB,sBAAA,cAACC,MAASD,KAAAA;EAC/CE,YAAY;AACd,CAAA;",
6
+ "names": ["Code", "React", "pluginMeta", "SCRIPT_PLUGIN", "pluginMeta", "id", "name", "description", "tags", "iconComponent", "props", "Code", "iconSymbol"]
7
+ }
@@ -0,0 +1,78 @@
1
+ // packages/plugins/experimental/plugin-script/src/components/TypescriptEditor.tsx
2
+ import { javascript } from "@codemirror/lang-javascript";
3
+ import { tsSync, tsFacet, tsLinter, tsAutocomplete, tsHover } from "@valtown/codemirror-ts";
4
+ import React from "react";
5
+ import { useThemeContext } from "@dxos/react-ui";
6
+ import { autocomplete, createBasicExtensions, createThemeExtensions, editorFullWidth, editorGutter, editorMonospace, InputModeExtensions, useTextEditor } from "@dxos/react-ui-editor";
7
+ import { nonNullable } from "@dxos/util";
8
+ var TypescriptEditor = ({ id, scrollPastEnd, env, className, initialValue, extensions, scrollTo, selection }) => {
9
+ const { themeMode } = useThemeContext();
10
+ const { parentRef, focusAttributes } = useTextEditor(() => ({
11
+ id,
12
+ initialValue,
13
+ extensions: [
14
+ extensions,
15
+ createBasicExtensions({
16
+ highlightActiveLine: true,
17
+ indentWithTab: true,
18
+ lineNumbers: true,
19
+ lineWrapping: false,
20
+ scrollPastEnd
21
+ }),
22
+ createThemeExtensions({
23
+ themeMode,
24
+ syntaxHighlighting: true,
25
+ slots: {
26
+ content: {
27
+ className: editorFullWidth
28
+ }
29
+ }
30
+ }),
31
+ editorGutter,
32
+ // TODO(burdon): Factor out.
33
+ [
34
+ editorMonospace,
35
+ javascript({
36
+ typescript: true
37
+ }),
38
+ // https://github.com/val-town/codemirror-ts
39
+ autocomplete({
40
+ override: env ? [
41
+ tsAutocomplete()
42
+ ] : []
43
+ }),
44
+ env ? [
45
+ tsFacet.of({
46
+ env,
47
+ path: `/src/${id}.ts`
48
+ }),
49
+ tsSync(),
50
+ tsLinter(),
51
+ tsHover()
52
+ ] : [],
53
+ InputModeExtensions.vscode
54
+ ]
55
+ ].filter(nonNullable),
56
+ selection,
57
+ scrollTo
58
+ }), [
59
+ id,
60
+ initialValue,
61
+ extensions,
62
+ themeMode,
63
+ selection,
64
+ scrollTo
65
+ ]);
66
+ return /* @__PURE__ */ React.createElement("div", {
67
+ ref: parentRef,
68
+ className,
69
+ ...focusAttributes
70
+ });
71
+ };
72
+ var TypescriptEditor_default = TypescriptEditor;
73
+
74
+ export {
75
+ TypescriptEditor,
76
+ TypescriptEditor_default
77
+ };
78
+ //# sourceMappingURL=chunk-MRGOT5RF.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/components/TypescriptEditor.tsx"],
4
+ "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { javascript } from '@codemirror/lang-javascript';\nimport { type VirtualTypeScriptEnvironment } from '@typescript/vfs';\nimport { tsSync, tsFacet, tsLinter, tsAutocomplete, tsHover } from '@valtown/codemirror-ts';\nimport React from 'react';\n\nimport { useThemeContext } from '@dxos/react-ui';\nimport {\n autocomplete,\n createBasicExtensions,\n createThemeExtensions,\n editorFullWidth,\n editorGutter,\n editorMonospace,\n InputModeExtensions,\n useTextEditor,\n type UseTextEditorProps,\n} from '@dxos/react-ui-editor';\nimport { nonNullable } from '@dxos/util';\n\nexport type TypescriptEditorProps = {\n id: string;\n scrollPastEnd?: boolean;\n env?: VirtualTypeScriptEnvironment;\n} & Pick<UseTextEditorProps, 'className' | 'initialValue' | 'extensions' | 'scrollTo' | 'selection'>;\n\nexport const TypescriptEditor = ({\n id,\n scrollPastEnd,\n env,\n className,\n initialValue,\n extensions,\n scrollTo,\n selection,\n}: TypescriptEditorProps) => {\n const { themeMode } = useThemeContext();\n const { parentRef, focusAttributes } = useTextEditor(\n () => ({\n id,\n initialValue,\n extensions: [\n extensions,\n createBasicExtensions({\n highlightActiveLine: true,\n indentWithTab: true,\n lineNumbers: true,\n lineWrapping: false,\n scrollPastEnd,\n }),\n createThemeExtensions({\n themeMode,\n syntaxHighlighting: true,\n slots: {\n content: { className: editorFullWidth },\n },\n }),\n editorGutter,\n // TODO(burdon): Factor out.\n [\n editorMonospace,\n javascript({ typescript: true }),\n // https://github.com/val-town/codemirror-ts\n autocomplete({ override: env ? [tsAutocomplete()] : [] }),\n env ? [tsFacet.of({ env, path: `/src/${id}.ts` }), tsSync(), tsLinter(), tsHover()] : [],\n InputModeExtensions.vscode,\n ],\n ].filter(nonNullable),\n selection,\n scrollTo,\n }),\n [id, initialValue, extensions, themeMode, selection, scrollTo],\n );\n\n return <div ref={parentRef} className={className} {...focusAttributes} />;\n};\n\nexport default TypescriptEditor;\n"],
5
+ "mappings": ";AAIA,SAASA,kBAAkB;AAE3B,SAASC,QAAQC,SAASC,UAAUC,gBAAgBC,eAAe;AACnE,OAAOC,WAAW;AAElB,SAASC,uBAAuB;AAChC,SACEC,cACAC,uBACAC,uBACAC,iBACAC,cACAC,iBACAC,qBACAC,qBAEK;AACP,SAASC,mBAAmB;AAQrB,IAAMC,mBAAmB,CAAC,EAC/BC,IACAC,eACAC,KACAC,WACAC,cACAC,YACAC,UACAC,UAAS,MACa;AACtB,QAAM,EAAEC,UAAS,IAAKC,gBAAAA;AACtB,QAAM,EAAEC,WAAWC,gBAAe,IAAKC,cACrC,OAAO;IACLZ;IACAI;IACAC,YAAY;MACVA;MACAQ,sBAAsB;QACpBC,qBAAqB;QACrBC,eAAe;QACfC,aAAa;QACbC,cAAc;QACdhB;MACF,CAAA;MACAiB,sBAAsB;QACpBV;QACAW,oBAAoB;QACpBC,OAAO;UACLC,SAAS;YAAElB,WAAWmB;UAAgB;QACxC;MACF,CAAA;MACAC;;MAEA;QACEC;QACAC,WAAW;UAAEC,YAAY;QAAK,CAAA;;QAE9BC,aAAa;UAAEC,UAAU1B,MAAM;YAAC2B,eAAAA;cAAoB,CAAA;QAAG,CAAA;QACvD3B,MAAM;UAAC4B,QAAQC,GAAG;YAAE7B;YAAK8B,MAAM,QAAQhC,EAAAA;UAAQ,CAAA;UAAIiC,OAAAA;UAAUC,SAAAA;UAAYC,QAAAA;YAAa,CAAA;QACtFC,oBAAoBC;;MAEtBC,OAAOC,WAAAA;IACThC;IACAD;EACF,IACA;IAACN;IAAII;IAAcC;IAAYG;IAAWD;IAAWD;GAAS;AAGhE,SAAO,sBAAA,cAACkC,OAAAA;IAAIC,KAAK/B;IAAWP;IAAuB,GAAGQ;;AACxD;AAEA,IAAA,2BAAeZ;",
6
+ "names": ["javascript", "tsSync", "tsFacet", "tsLinter", "tsAutocomplete", "tsHover", "React", "useThemeContext", "autocomplete", "createBasicExtensions", "createThemeExtensions", "editorFullWidth", "editorGutter", "editorMonospace", "InputModeExtensions", "useTextEditor", "nonNullable", "TypescriptEditor", "id", "scrollPastEnd", "env", "className", "initialValue", "extensions", "scrollTo", "selection", "themeMode", "useThemeContext", "parentRef", "focusAttributes", "useTextEditor", "createBasicExtensions", "highlightActiveLine", "indentWithTab", "lineNumbers", "lineWrapping", "createThemeExtensions", "syntaxHighlighting", "slots", "content", "editorFullWidth", "editorGutter", "editorMonospace", "javascript", "typescript", "autocomplete", "override", "tsAutocomplete", "tsFacet", "of", "path", "tsSync", "tsLinter", "tsHover", "InputModeExtensions", "vscode", "filter", "nonNullable", "div", "ref"]
7
+ }
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  SCRIPT_PLUGIN
3
- } from "./chunk-MDX7ACIK.mjs";
3
+ } from "./chunk-JBACGDOJ.mjs";
4
4
 
5
5
  // packages/plugins/experimental/plugin-script/src/types/script.ts
6
6
  import { ref, S, TypedObject } from "@dxos/echo-schema";
@@ -43,4 +43,4 @@ export {
43
43
  FunctionType,
44
44
  ScriptAction
45
45
  };
46
- //# sourceMappingURL=chunk-CAEANETO.mjs.map
46
+ //# sourceMappingURL=chunk-O4LWBX6A.mjs.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/types/script.ts", "../../../src/types/types.ts"],
4
- "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { ref, S, TypedObject } from '@dxos/echo-schema';\nimport { TextType } from '@dxos/plugin-markdown/types';\n\n// TODO(burdon): Which is the outer type? I.e., in the navbar?\n\n/**\n * Source script.\n */\nexport class ScriptType extends TypedObject({ typename: 'dxos.org/type/Script', version: '0.1.0' })({\n // TODO(burdon): Change to URI?\n name: S.optional(S.String),\n description: S.optional(S.String),\n source: ref(TextType),\n // TODO(burdon): Change to has of deployed content.\n // Whether source has changed since last deploy.\n changed: S.optional(S.Boolean),\n}) {}\n\n/**\n * Function deployment.\n */\nexport class FunctionType extends TypedObject({ typename: 'dxos.org/type/Function', version: '0.1.0' })({\n name: S.optional(S.String),\n version: S.Number,\n // Local binding to a function name.\n // TODO(burdon): Move binding to inner type.\n binding: S.optional(S.String),\n // Reference to a source script if it exists within ECHO.\n source: S.optional(ref(ScriptType)),\n}) {}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport type {\n GraphBuilderProvides,\n IntentResolverProvides,\n MetadataRecordsProvides,\n SettingsProvides,\n SurfaceProvides,\n TranslationsProvides,\n} from '@dxos/app-framework';\nimport { type SchemaProvides } from '@dxos/plugin-client';\nimport { type SpaceInitProvides } from '@dxos/plugin-space';\n\nimport { SCRIPT_PLUGIN } from '../meta';\n\nexport enum ScriptAction {\n CREATE = `${SCRIPT_PLUGIN}/create`,\n}\n\nexport type ScriptSettingsProps = {};\n\nexport type ScriptPluginProvides = GraphBuilderProvides &\n IntentResolverProvides &\n MetadataRecordsProvides &\n SchemaProvides &\n SettingsProvides<ScriptSettingsProps> &\n SpaceInitProvides &\n SurfaceProvides &\n TranslationsProvides;\n"],
5
- "mappings": ";;;;;AAIA,SAASA,KAAKC,GAAGC,mBAAmB;AACpC,SAASC,gBAAgB;AAOlB,IAAMC,aAAN,cAAyBC,YAAY;EAAEC,UAAU;EAAwBC,SAAS;AAAQ,CAAA,EAAG;;EAElGC,MAAMC,EAAEC,SAASD,EAAEE,MAAM;EACzBC,aAAaH,EAAEC,SAASD,EAAEE,MAAM;EAChCE,QAAQC,IAAIC,QAAAA;;;EAGZC,SAASP,EAAEC,SAASD,EAAEQ,OAAO;AAC/B,CAAA,EAAA;AAAI;AAKG,IAAMC,eAAN,cAA2Bb,YAAY;EAAEC,UAAU;EAA0BC,SAAS;AAAQ,CAAA,EAAG;EACtGC,MAAMC,EAAEC,SAASD,EAAEE,MAAM;EACzBJ,SAASE,EAAEU;;;EAGXC,SAASX,EAAEC,SAASD,EAAEE,MAAM;;EAE5BE,QAAQJ,EAAEC,SAASI,IAAIV,UAAAA,CAAAA;AACzB,CAAA,EAAA;AAAI;;;;UChBQiB,eAAAA;0CACD,GAAGC,aAAAA,SAAsB,IAAA;GADxBD,iBAAAA,eAAAA,CAAAA,EAAAA;",
4
+ "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { ref, S, TypedObject } from '@dxos/echo-schema';\nimport { TextType } from '@dxos/plugin-markdown/types';\n\n// TODO(burdon): Which is the outer type? I.e., in the navbar?\n\n/**\n * Source script.\n */\nexport class ScriptType extends TypedObject({ typename: 'dxos.org/type/Script', version: '0.1.0' })({\n // TODO(burdon): Change to URI?\n name: S.optional(S.String),\n description: S.optional(S.String),\n source: ref(TextType),\n // TODO(burdon): Change to has of deployed content.\n // Whether source has changed since last deploy.\n changed: S.optional(S.Boolean),\n}) {}\n\n/**\n * Function deployment.\n */\nexport class FunctionType extends TypedObject({ typename: 'dxos.org/type/Function', version: '0.1.0' })({\n name: S.optional(S.String),\n version: S.Number,\n // Local binding to a function name.\n // TODO(burdon): Move binding to inner type.\n binding: S.optional(S.String),\n // Reference to a source script if it exists within ECHO.\n source: S.optional(ref(ScriptType)),\n}) {}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport type {\n GraphBuilderProvides,\n IntentResolverProvides,\n MetadataRecordsProvides,\n SurfaceProvides,\n TranslationsProvides,\n} from '@dxos/app-framework';\nimport { type SchemaProvides } from '@dxos/plugin-client';\nimport { type StackProvides } from '@dxos/plugin-stack';\n\nimport { SCRIPT_PLUGIN } from '../meta';\n\nexport enum ScriptAction {\n CREATE = `${SCRIPT_PLUGIN}/create`,\n}\n\nexport type ScriptPluginProvides = SurfaceProvides &\n IntentResolverProvides &\n GraphBuilderProvides &\n MetadataRecordsProvides &\n TranslationsProvides &\n SchemaProvides &\n StackProvides;\n"],
5
+ "mappings": ";;;;;AAIA,SAASA,KAAKC,GAAGC,mBAAmB;AACpC,SAASC,gBAAgB;AAOlB,IAAMC,aAAN,cAAyBC,YAAY;EAAEC,UAAU;EAAwBC,SAAS;AAAQ,CAAA,EAAG;;EAElGC,MAAMC,EAAEC,SAASD,EAAEE,MAAM;EACzBC,aAAaH,EAAEC,SAASD,EAAEE,MAAM;EAChCE,QAAQC,IAAIC,QAAAA;;;EAGZC,SAASP,EAAEC,SAASD,EAAEQ,OAAO;AAC/B,CAAA,EAAA;AAAI;AAKG,IAAMC,eAAN,cAA2Bb,YAAY;EAAEC,UAAU;EAA0BC,SAAS;AAAQ,CAAA,EAAG;EACtGC,MAAMC,EAAEC,SAASD,EAAEE,MAAM;EACzBJ,SAASE,EAAEU;;;EAGXC,SAASX,EAAEC,SAASD,EAAEE,MAAM;;EAE5BE,QAAQJ,EAAEC,SAASI,IAAIV,UAAAA,CAAAA;AACzB,CAAA,EAAA;AAAI;;;;UCjBQiB,eAAAA;0CACD,GAAGC,aAAAA,SAAsB,IAAA;GADxBD,iBAAAA,eAAAA,CAAAA,EAAAA;",
6
6
  "names": ["ref", "S", "TypedObject", "TextType", "ScriptType", "TypedObject", "typename", "version", "name", "S", "optional", "String", "description", "source", "ref", "TextType", "changed", "Boolean", "FunctionType", "Number", "binding", "ScriptAction", "SCRIPT_PLUGIN"]
7
7
  }
@@ -222,57 +222,8 @@ var httpPlugin = {
222
222
  }
223
223
  };
224
224
 
225
- // raw-loader:./templates/chat.ts?raw
226
- var chat_default = "//\n// Copyright 2024 DXOS.org\n//\n\n// @ts-ignore\nimport { transformServerSentEvents } from 'https://esm.sh/@dxos/script-toolbox';\n\n/**\n * Chatbot that answers questions based on the context data.\n */\nexport default async ({\n event: {\n data: { request },\n },\n context: { space, ai },\n}: any) => {\n const textBody = await request.text();\n let parsedRequest: any;\n try {\n parsedRequest = JSON.parse(textBody);\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 ${textBody}\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 === ChainInputType.VALUE) {\n value = String(input.value);\n } else if (input.type === ChainInputType.RETRIEVER) {\n value = await getContext({ space });\n } else if (input.type === ChainInputType.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 ChainInputType {\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";
227
-
228
- // raw-loader:./templates/chess.ts?raw
229
- var chess_default = "//\n// Copyright 2024 DXOS.org\n//\n\n// @ts-ignore\nimport { Chess } from 'https://esm.sh/chess.js@0.13.1';\n\n/**\n * Plays a random move in a chess game.\n */\nexport default async ({\n event: {\n data: { request },\n },\n context: { space },\n}: any) => {\n const {\n data: {\n objects: [gameId],\n player = 'b',\n },\n } = await request.json();\n\n const { pgn } = await space.crud.query({ id: gameId }).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.crud.update({ id: gameId }, { pgn: newPgn });\n return new Response(game.ascii());\n};\n";
230
-
231
- // raw-loader:./templates/echo.ts?raw
232
- var echo_default = "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Echos the request data.\n */\nexport default async ({\n event: {\n data: { request },\n },\n}: any) => {\n const data = await request.json();\n return new Response(JSON.stringify(data ?? {}), { headers: { 'Content-Type': 'application/json' } });\n};\n";
233
-
234
- // raw-loader:./templates/email.ts?raw
235
- var email_default = "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Stores a message into ECHO Mailbox object.\n */\nexport default async ({\n event: {\n data: { request },\n },\n context: { space },\n}: any) => {\n const {\n data: {\n objects: [message],\n },\n } = await request.json();\n\n const mailbox = await space.crud.query({ __typename: 'dxos.org/type/MailboxType' }).first();\n if (!mailbox) {\n return new Response('Mailbox not found.', { status: 500 });\n }\n\n await space.crud.push(\n { id: mailbox.id },\n {\n sender: { email: message.from },\n timestamp: new Date(message.created).toISOString(),\n text: message.body,\n properties: {\n subject: message.subject,\n to: [{ email: message.to }],\n },\n },\n );\n return new Response(JSON.stringify(message));\n};\n";
236
-
237
- // raw-loader:./templates/forex.ts?raw
238
- var forex_default = "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Returns the exchange rate between two currencies.\n */\nexport default async ({\n event: {\n data: { request },\n },\n}: any) => {\n const { args: [from = 'EUR', to = 'USD'] = [] } = await request.json();\n\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 new Response(rates[to].toString());\n};\n";
239
-
240
- // packages/plugins/experimental/plugin-script/src/templates.ts
241
- var removeHeader = (str) => str.split("\n").slice(4).join("\n");
242
- var templates = [
243
- {
244
- id: "dxos.org/script/echo",
245
- name: "Echo",
246
- source: removeHeader(echo_default)
247
- },
248
- {
249
- id: "dxos.org/script/forex",
250
- name: "Forex",
251
- source: removeHeader(forex_default)
252
- },
253
- {
254
- id: "dxos.org/script/gpt",
255
- name: "Gpt",
256
- source: removeHeader(chat_default),
257
- presetId: "dxos.org/function/gpt"
258
- },
259
- {
260
- id: "dxos.org/script/chess",
261
- name: "Chess",
262
- source: removeHeader(chess_default),
263
- presetId: "dxos.org/function/chess"
264
- },
265
- {
266
- id: "dxos.org/script/email",
267
- name: "Email",
268
- source: removeHeader(email_default),
269
- presetId: "dxos.org/function/email"
270
- }
271
- ];
272
-
273
225
  export {
274
226
  initializeBundler,
275
- Bundler,
276
- templates
227
+ Bundler
277
228
  };
278
- //# sourceMappingURL=chunk-G6H56WFS.mjs.map
229
+ //# sourceMappingURL=chunk-RHEZ5LUU.mjs.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../src/bundler/bundler.ts", "raw-loader:./templates/chat.ts?raw", "raw-loader:./templates/chess.ts?raw", "raw-loader:./templates/echo.ts?raw", "raw-loader:./templates/email.ts?raw", "raw-loader:./templates/forex.ts?raw", "../../../src/templates.ts"],
4
- "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { type BuildOptions } from 'esbuild';\nimport { build, initialize, type BuildResult, type Plugin } from 'esbuild-wasm';\n\nimport { subtleCrypto } from '@dxos/crypto';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\n\nexport type Import = {\n moduleUrl: string;\n defaultImport: boolean;\n namedImports: string[];\n};\n\nexport type BundlerResult = {\n timestamp: number;\n sourceHash: Buffer;\n imports?: Import[];\n bundle?: string;\n error?: any;\n};\n\nexport type BundlerOptions = {\n platform: BuildOptions['platform'];\n sandboxedModules: string[];\n remoteModules: Record<string, string>;\n};\n\nlet initialized: Promise<void>;\nexport const initializeBundler = async (options: { wasmUrl: string }) => {\n await (initialized ??= initialize({\n wasmURL: options.wasmUrl,\n }));\n};\n\n/**\n * ESBuild bundler.\n */\nexport class Bundler {\n constructor(private readonly _options: BundlerOptions) {}\n\n async bundle(source: string): Promise<BundlerResult> {\n const { sandboxedModules: providedModules, ...options } = this._options;\n\n const createResult = async (result?: Partial<BundlerResult>) => {\n return {\n timestamp: Date.now(),\n sourceHash: Buffer.from(await subtleCrypto.digest('SHA-256', Buffer.from(source))),\n ...result,\n };\n };\n\n if (this._options.platform === 'browser') {\n invariant(initialized, 'Compiler not initialized.');\n await initialized;\n }\n\n const imports = analyzeSourceFileImports(source);\n\n // https://esbuild.github.io/api/#build\n try {\n const result = await build({\n platform: options.platform,\n conditions: ['workerd', 'browser'],\n metafile: true,\n write: false,\n entryPoints: ['memory:main.tsx'],\n bundle: true,\n format: 'esm',\n plugins: [\n {\n name: 'memory',\n setup: (build) => {\n build.onResolve({ filter: /^\\.\\/runtime\\.js$/ }, ({ path }) => {\n return { path, external: true };\n });\n\n build.onResolve({ filter: /^memory:/ }, ({ path }) => {\n return { path: path.split(':')[1], namespace: 'memory' };\n });\n\n build.onLoad({ filter: /.*/, namespace: 'memory' }, ({ path }) => {\n if (path === 'main.tsx') {\n return {\n contents: source,\n loader: 'tsx',\n };\n }\n });\n\n for (const module of providedModules) {\n build.onResolve({ filter: new RegExp(`^${module}$`) }, ({ path }) => {\n return { path, namespace: 'injected-module' };\n });\n }\n\n build.onLoad({ filter: /.*/, namespace: 'injected-module' }, ({ path }) => {\n const namedImports = imports.find((entry) => entry.moduleIdentifier === path)?.namedImports ?? [];\n return {\n contents: `\n const { ${namedImports.join(',')} } = window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}];\n export { ${namedImports.join(',')} };\n export default window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}].default;\n `,\n loader: 'tsx',\n };\n });\n },\n },\n httpPlugin,\n ],\n });\n\n log('compile complete', result.metafile);\n\n return await createResult({\n imports: this.analyzeImports(result),\n bundle: result.outputFiles![0].text,\n });\n } catch (err) {\n return await createResult({ error: err });\n }\n }\n\n // TODO(dmaretskyi): In the future we can replace the compiler with SWC with plugins running in WASM.\n analyzeImports(result: BuildResult): Import[] {\n invariant(result.outputFiles);\n\n // TODO(dmaretskyi): Support import aliases and wildcard imports.\n const parsedImports = allMatches(IMPORT_REGEX, result.outputFiles[0].text);\n return Object.values(result.metafile!.outputs)[0].imports.map((entry): Import => {\n const namedImports: string[] = [];\n\n const parsedImport = parsedImports.find((capture) => capture?.[4] === entry.path);\n if (parsedImport?.[2]) {\n NAMED_IMPORTS_REGEX.lastIndex = 0;\n const namedImportsMatch = NAMED_IMPORTS_REGEX.exec(parsedImport[2]);\n if (namedImportsMatch) {\n namedImportsMatch[1].split(',').forEach((importName) => {\n namedImports.push(importName.trim());\n });\n }\n }\n\n return {\n moduleUrl: entry.path,\n defaultImport: !!parsedImport?.[1],\n namedImports,\n };\n });\n }\n\n analyzeSourceFileImports(code: string) {\n // TODO(dmaretskyi): Support import aliases and wildcard imports.\n const parsedImports = allMatches(IMPORT_REGEX, code);\n return parsedImports.map((capture) => {\n return {\n defaultImportName: capture[1],\n namedImports: capture[2]?.split(',').map((importName) => importName.trim()),\n wildcardImportName: capture[3],\n moduleIdentifier: capture[4],\n quotes: capture[5],\n };\n });\n }\n}\n\n// https://regex101.com/r/FEN5ks/1\n// https://stackoverflow.com/a/73265022\n// $1 = default import name (can be non-existent)\n// $2 = destructured exports (can be non-existent)\n// $3 = wildcard import name (can be non-existent)\n// $4 = module identifier\n// $5 = quotes used (either ' or \")\nconst IMPORT_REGEX =\n /import(?:(?:(?:[ \\n\\t]+([^ *\\n\\t{},]+)[ \\n\\t]*(?:,|[ \\n\\t]+))?([ \\n\\t]*{(?:[ \\n\\t]*[^ \\n\\t\"'{}]+[ \\n\\t]*,?)+})?[ \\n\\t]*)|[ \\n\\t]*\\*[ \\n\\t]*as[ \\n\\t]+([^ \\n\\t{}]+)[ \\n\\t]+)from[ \\n\\t]*(?:['\"])([^'\"\\n]+)(['\"])/gm;\n\nconst NAMED_IMPORTS_REGEX = /[ \\n\\t]*{((?:[ \\n\\t]*[^ \\n\\t\"'{}]+[ \\n\\t]*,?)+)}[ \\n\\t]*/gm;\n\nconst allMatches = (regex: RegExp, str: string) => {\n regex.lastIndex = 0;\n\n let match;\n const matches = [];\n while ((match = regex.exec(str))) {\n matches.push(match);\n }\n\n return matches;\n};\n\ntype ParsedImport = {\n defaultImportName?: string;\n namedImports: string[];\n wildcardImportName?: string;\n moduleIdentifier: string;\n quotes: string;\n};\n\nconst analyzeSourceFileImports = (code: string): ParsedImport[] => {\n // TODO(dmaretskyi): Support import aliases and wildcard imports.\n const parsedImports = allMatches(IMPORT_REGEX, code);\n return parsedImports.map((capture) => {\n return {\n defaultImportName: capture[1],\n namedImports: capture[2]\n ?.trim()\n .slice(1, -1)\n .split(',')\n .map((importName) => importName.trim()),\n wildcardImportName: capture[3],\n moduleIdentifier: capture[4],\n quotes: capture[5],\n };\n });\n};\n\nconst httpPlugin: Plugin = {\n name: 'http',\n setup: (build) => {\n // Intercept import paths starting with \"http:\" and \"https:\" so esbuild doesn't attempt to map them to a file system location.\n // Tag them with the \"http-url\" namespace to associate them with this plugin.\n build.onResolve({ filter: /^https?:\\/\\// }, (args) => ({\n path: args.path,\n namespace: 'http-url',\n }));\n\n // We also want to intercept all import paths inside downloaded files and resolve them against the original URL.\n // All of these files will be in the \"http-url\" namespace.\n // Make sure to keep the newly resolved URL in the \"http-url\" namespace so imports inside it will also be resolved as URLs recursively.\n build.onResolve({ filter: /.*/, namespace: 'http-url' }, (args) => ({\n path: new URL(args.path, args.importer).toString(),\n namespace: 'http-url',\n }));\n\n // When a URL is loaded, we want to actually download the content from the internet.\n // This has just enough logic to be able to handle the example import from unpkg.com but in reality this would probably need to be more complex.\n build.onLoad({ filter: /.*/, namespace: 'http-url' }, async (args) => {\n const response = await fetch(args.path);\n return { contents: await response.text(), loader: 'jsx' };\n });\n },\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\n// @ts-ignore\nimport { transformServerSentEvents } from 'https://esm.sh/@dxos/script-toolbox';\n\n/**\n * Chatbot that answers questions based on the context data.\n */\nexport default async ({\n event: {\n data: { request },\n },\n context: { space, ai },\n}: any) => {\n const textBody = await request.text();\n let parsedRequest: any;\n try {\n parsedRequest = JSON.parse(textBody);\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 ${textBody}\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 === ChainInputType.VALUE) {\n value = String(input.value);\n } else if (input.type === ChainInputType.RETRIEVER) {\n value = await getContext({ space });\n } else if (input.type === ChainInputType.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 ChainInputType {\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 2024 DXOS.org\n//\n\n// @ts-ignore\nimport { Chess } from 'https://esm.sh/chess.js@0.13.1';\n\n/**\n * Plays a random move in a chess game.\n */\nexport default async ({\n event: {\n data: { request },\n },\n context: { space },\n}: any) => {\n const {\n data: {\n objects: [gameId],\n player = 'b',\n },\n } = await request.json();\n\n const { pgn } = await space.crud.query({ id: gameId }).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.crud.update({ id: gameId }, { pgn: newPgn });\n return new Response(game.ascii());\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Echos the request data.\n */\nexport default async ({\n event: {\n data: { request },\n },\n}: any) => {\n const data = await request.json();\n return new Response(JSON.stringify(data ?? {}), { headers: { 'Content-Type': 'application/json' } });\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Stores a message into ECHO Mailbox object.\n */\nexport default async ({\n event: {\n data: { request },\n },\n context: { space },\n}: any) => {\n const {\n data: {\n objects: [message],\n },\n } = await request.json();\n\n const mailbox = await space.crud.query({ __typename: 'dxos.org/type/MailboxType' }).first();\n if (!mailbox) {\n return new Response('Mailbox not found.', { status: 500 });\n }\n\n await space.crud.push(\n { id: mailbox.id },\n {\n sender: { email: message.from },\n timestamp: new Date(message.created).toISOString(),\n text: message.body,\n properties: {\n subject: message.subject,\n to: [{ email: message.to }],\n },\n },\n );\n return new Response(JSON.stringify(message));\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Returns the exchange rate between two currencies.\n */\nexport default async ({\n event: {\n data: { request },\n },\n}: any) => {\n const { args: [from = 'EUR', to = 'USD'] = [] } = await request.json();\n\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 new Response(rates[to].toString());\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\n// @ts-ignore\nimport chat from './templates/chat.ts?raw';\n// @ts-ignore\nimport chess from './templates/chess.ts?raw';\n// @ts-ignore\nimport echo from './templates/echo.ts?raw';\n// @ts-ignore\nimport email from './templates/email.ts?raw';\n// @ts-ignore\nimport forex from './templates/forex.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/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"],
5
- "mappings": ";AAKA,SAASA,OAAOC,kBAAiD;AAEjE,SAASC,oBAAoB;AAC7B,SAASC,iBAAiB;AAC1B,SAASC,WAAW;;AAsBpB,IAAIC;AACG,IAAMC,oBAAoB,OAAOC,YAAAA;AACtC,SAAOF,gBAAgBJ,WAAW;IAChCO,SAASD,QAAQE;EACnB,CAAA;AACF;AAKO,IAAMC,UAAN,MAAMA;EACXC,YAA6BC,UAA0B;SAA1BA,WAAAA;EAA2B;EAExD,MAAMC,OAAOC,QAAwC;AACnD,UAAM,EAAEC,kBAAkBC,iBAAiB,GAAGT,QAAAA,IAAY,KAAKK;AAE/D,UAAMK,eAAe,OAAOC,WAAAA;AAC1B,aAAO;QACLC,WAAWC,KAAKC,IAAG;QACnBC,YAAYC,OAAOC,KAAK,MAAMtB,aAAauB,OAAO,WAAWF,OAAOC,KAAKV,MAAAA,CAAAA,CAAAA;QACzE,GAAGI;MACL;IACF;AAEA,QAAI,KAAKN,SAASc,aAAa,WAAW;AACxCvB,gBAAUE,aAAa,6BAAA;;;;;;;;;AACvB,YAAMA;IACR;AAEA,UAAMsB,UAAUC,yBAAyBd,MAAAA;AAGzC,QAAI;AACF,YAAMI,SAAS,MAAMlB,MAAM;QACzB0B,UAAUnB,QAAQmB;QAClBG,YAAY;UAAC;UAAW;;QACxBC,UAAU;QACVC,OAAO;QACPC,aAAa;UAAC;;QACdnB,QAAQ;QACRoB,QAAQ;QACRC,SAAS;UACP;YACEC,MAAM;YACNC,OAAO,CAACpC,WAAAA;AACNA,cAAAA,OAAMqC,UAAU;gBAAEC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AA;EACF;AACF;;;ACrPA;;;ACAA;;;ACAA;;;ACAA;;;ACAA;;;ACeA,IAAMkD,eAAe,CAACC,QAAgBA,IAAIC,MAAM,IAAA,EAAMC,MAAM,CAAA,EAAGC,KAAK,IAAA;AAS7D,IAAMC,YAAwB;EACnC;IACEC,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAaS,YAAAA;EACvB;EACA;IACEH,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAaU,aAAAA;EACvB;EACA;IACEJ,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAaW,YAAAA;IACrBC,UAAU;EACZ;EACA;IACEN,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAaa,aAAAA;IACrBD,UAAU;EACZ;EACA;IACEN,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAac,aAAAA;IACrBF,UAAU;EACZ;;",
6
- "names": ["build", "initialize", "subtleCrypto", "invariant", "log", "initialized", "initializeBundler", "options", "wasmURL", "wasmUrl", "Bundler", "constructor", "_options", "bundle", "source", "sandboxedModules", "providedModules", "createResult", "result", "timestamp", "Date", "now", "sourceHash", "Buffer", "from", "digest", "platform", "imports", "analyzeSourceFileImports", "conditions", "metafile", "write", "entryPoints", "format", "plugins", "name", "setup", "onResolve", "filter", "path", "external", "split", "namespace", "onLoad", "contents", "loader", "module", "RegExp", "namedImports", "find", "entry", "moduleIdentifier", "join", "JSON", "stringify", "httpPlugin", "analyzeImports", "outputFiles", "text", "err", "error", "parsedImports", "allMatches", "IMPORT_REGEX", "Object", "values", "outputs", "map", "parsedImport", "capture", "NAMED_IMPORTS_REGEX", "lastIndex", "namedImportsMatch", "exec", "forEach", "importName", "push", "trim", "moduleUrl", "defaultImport", "code", "defaultImportName", "wildcardImportName", "quotes", "regex", "str", "match", "matches", "slice", "args", "URL", "importer", "toString", "response", "fetch", "removeHeader", "str", "split", "slice", "join", "templates", "id", "name", "source", "echo", "forex", "chat", "presetId", "chess", "email"]
3
+ "sources": ["../../../src/bundler/bundler.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { type BuildOptions } from 'esbuild';\nimport { build, initialize, type BuildResult, type Plugin } from 'esbuild-wasm';\n\nimport { subtleCrypto } from '@dxos/crypto';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\n\nexport type Import = {\n moduleUrl: string;\n defaultImport: boolean;\n namedImports: string[];\n};\n\nexport type BundlerResult = {\n timestamp: number;\n sourceHash: Buffer;\n imports?: Import[];\n bundle?: string;\n error?: any;\n};\n\nexport type BundlerOptions = {\n platform: BuildOptions['platform'];\n sandboxedModules: string[];\n remoteModules: Record<string, string>;\n};\n\nlet initialized: Promise<void>;\nexport const initializeBundler = async (options: { wasmUrl: string }) => {\n await (initialized ??= initialize({\n wasmURL: options.wasmUrl,\n }));\n};\n\n/**\n * ESBuild bundler.\n */\nexport class Bundler {\n constructor(private readonly _options: BundlerOptions) {}\n\n async bundle(source: string): Promise<BundlerResult> {\n const { sandboxedModules: providedModules, ...options } = this._options;\n\n const createResult = async (result?: Partial<BundlerResult>) => {\n return {\n timestamp: Date.now(),\n sourceHash: Buffer.from(await subtleCrypto.digest('SHA-256', Buffer.from(source))),\n ...result,\n };\n };\n\n if (this._options.platform === 'browser') {\n invariant(initialized, 'Compiler not initialized.');\n await initialized;\n }\n\n const imports = analyzeSourceFileImports(source);\n\n // https://esbuild.github.io/api/#build\n try {\n const result = await build({\n platform: options.platform,\n conditions: ['workerd', 'browser'],\n metafile: true,\n write: false,\n entryPoints: ['memory:main.tsx'],\n bundle: true,\n format: 'esm',\n plugins: [\n {\n name: 'memory',\n setup: (build) => {\n build.onResolve({ filter: /^\\.\\/runtime\\.js$/ }, ({ path }) => {\n return { path, external: true };\n });\n\n build.onResolve({ filter: /^memory:/ }, ({ path }) => {\n return { path: path.split(':')[1], namespace: 'memory' };\n });\n\n build.onLoad({ filter: /.*/, namespace: 'memory' }, ({ path }) => {\n if (path === 'main.tsx') {\n return {\n contents: source,\n loader: 'tsx',\n };\n }\n });\n\n for (const module of providedModules) {\n build.onResolve({ filter: new RegExp(`^${module}$`) }, ({ path }) => {\n return { path, namespace: 'injected-module' };\n });\n }\n\n build.onLoad({ filter: /.*/, namespace: 'injected-module' }, ({ path }) => {\n const namedImports = imports.find((entry) => entry.moduleIdentifier === path)?.namedImports ?? [];\n return {\n contents: `\n const { ${namedImports.join(',')} } = window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}];\n export { ${namedImports.join(',')} };\n export default window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}].default;\n `,\n loader: 'tsx',\n };\n });\n },\n },\n httpPlugin,\n ],\n });\n\n log('compile complete', result.metafile);\n\n return await createResult({\n imports: this.analyzeImports(result),\n bundle: result.outputFiles![0].text,\n });\n } catch (err) {\n return await createResult({ error: err });\n }\n }\n\n // TODO(dmaretskyi): In the future we can replace the compiler with SWC with plugins running in WASM.\n analyzeImports(result: BuildResult): Import[] {\n invariant(result.outputFiles);\n\n // TODO(dmaretskyi): Support import aliases and wildcard imports.\n const parsedImports = allMatches(IMPORT_REGEX, result.outputFiles[0].text);\n return Object.values(result.metafile!.outputs)[0].imports.map((entry): Import => {\n const namedImports: string[] = [];\n\n const parsedImport = parsedImports.find((capture) => capture?.[4] === entry.path);\n if (parsedImport?.[2]) {\n NAMED_IMPORTS_REGEX.lastIndex = 0;\n const namedImportsMatch = NAMED_IMPORTS_REGEX.exec(parsedImport[2]);\n if (namedImportsMatch) {\n namedImportsMatch[1].split(',').forEach((importName) => {\n namedImports.push(importName.trim());\n });\n }\n }\n\n return {\n moduleUrl: entry.path,\n defaultImport: !!parsedImport?.[1],\n namedImports,\n };\n });\n }\n\n analyzeSourceFileImports(code: string) {\n // TODO(dmaretskyi): Support import aliases and wildcard imports.\n const parsedImports = allMatches(IMPORT_REGEX, code);\n return parsedImports.map((capture) => {\n return {\n defaultImportName: capture[1],\n namedImports: capture[2]?.split(',').map((importName) => importName.trim()),\n wildcardImportName: capture[3],\n moduleIdentifier: capture[4],\n quotes: capture[5],\n };\n });\n }\n}\n\n// https://regex101.com/r/FEN5ks/1\n// https://stackoverflow.com/a/73265022\n// $1 = default import name (can be non-existent)\n// $2 = destructured exports (can be non-existent)\n// $3 = wildcard import name (can be non-existent)\n// $4 = module identifier\n// $5 = quotes used (either ' or \")\nconst IMPORT_REGEX =\n /import(?:(?:(?:[ \\n\\t]+([^ *\\n\\t{},]+)[ \\n\\t]*(?:,|[ \\n\\t]+))?([ \\n\\t]*{(?:[ \\n\\t]*[^ \\n\\t\"'{}]+[ \\n\\t]*,?)+})?[ \\n\\t]*)|[ \\n\\t]*\\*[ \\n\\t]*as[ \\n\\t]+([^ \\n\\t{}]+)[ \\n\\t]+)from[ \\n\\t]*(?:['\"])([^'\"\\n]+)(['\"])/gm;\n\nconst NAMED_IMPORTS_REGEX = /[ \\n\\t]*{((?:[ \\n\\t]*[^ \\n\\t\"'{}]+[ \\n\\t]*,?)+)}[ \\n\\t]*/gm;\n\nconst allMatches = (regex: RegExp, str: string) => {\n regex.lastIndex = 0;\n\n let match;\n const matches = [];\n while ((match = regex.exec(str))) {\n matches.push(match);\n }\n\n return matches;\n};\n\ntype ParsedImport = {\n defaultImportName?: string;\n namedImports: string[];\n wildcardImportName?: string;\n moduleIdentifier: string;\n quotes: string;\n};\n\nconst analyzeSourceFileImports = (code: string): ParsedImport[] => {\n // TODO(dmaretskyi): Support import aliases and wildcard imports.\n const parsedImports = allMatches(IMPORT_REGEX, code);\n return parsedImports.map((capture) => {\n return {\n defaultImportName: capture[1],\n namedImports: capture[2]\n ?.trim()\n .slice(1, -1)\n .split(',')\n .map((importName) => importName.trim()),\n wildcardImportName: capture[3],\n moduleIdentifier: capture[4],\n quotes: capture[5],\n };\n });\n};\n\nconst httpPlugin: Plugin = {\n name: 'http',\n setup: (build) => {\n // Intercept import paths starting with \"http:\" and \"https:\" so esbuild doesn't attempt to map them to a file system location.\n // Tag them with the \"http-url\" namespace to associate them with this plugin.\n build.onResolve({ filter: /^https?:\\/\\// }, (args) => ({\n path: args.path,\n namespace: 'http-url',\n }));\n\n // We also want to intercept all import paths inside downloaded files and resolve them against the original URL.\n // All of these files will be in the \"http-url\" namespace.\n // Make sure to keep the newly resolved URL in the \"http-url\" namespace so imports inside it will also be resolved as URLs recursively.\n build.onResolve({ filter: /.*/, namespace: 'http-url' }, (args) => ({\n path: new URL(args.path, args.importer).toString(),\n namespace: 'http-url',\n }));\n\n // When a URL is loaded, we want to actually download the content from the internet.\n // This has just enough logic to be able to handle the example import from unpkg.com but in reality this would probably need to be more complex.\n build.onLoad({ filter: /.*/, namespace: 'http-url' }, async (args) => {\n const response = await fetch(args.path);\n return { contents: await response.text(), loader: 'jsx' };\n });\n },\n};\n"],
5
+ "mappings": ";AAKA,SAASA,OAAOC,kBAAiD;AAEjE,SAASC,oBAAoB;AAC7B,SAASC,iBAAiB;AAC1B,SAASC,WAAW;;AAsBpB,IAAIC;AACG,IAAMC,oBAAoB,OAAOC,YAAAA;AACtC,SAAOF,gBAAgBJ,WAAW;IAChCO,SAASD,QAAQE;EACnB,CAAA;AACF;AAKO,IAAMC,UAAN,MAAMA;EACXC,YAA6BC,UAA0B;SAA1BA,WAAAA;EAA2B;EAExD,MAAMC,OAAOC,QAAwC;AACnD,UAAM,EAAEC,kBAAkBC,iBAAiB,GAAGT,QAAAA,IAAY,KAAKK;AAE/D,UAAMK,eAAe,OAAOC,WAAAA;AAC1B,aAAO;QACLC,WAAWC,KAAKC,IAAG;QACnBC,YAAYC,OAAOC,KAAK,MAAMtB,aAAauB,OAAO,WAAWF,OAAOC,KAAKV,MAAAA,CAAAA,CAAAA;QACzE,GAAGI;MACL;IACF;AAEA,QAAI,KAAKN,SAASc,aAAa,WAAW;AACxCvB,gBAAUE,aAAa,6BAAA;;;;;;;;;AACvB,YAAMA;IACR;AAEA,UAAMsB,UAAUC,yBAAyBd,MAAAA;AAGzC,QAAI;AACF,YAAMI,SAAS,MAAMlB,MAAM;QACzB0B,UAAUnB,QAAQ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AAM2C,OAAO;MAAEL,QAAQ;MAAMI,WAAW;IAAW,GAAG,OAAO+C,SAAAA;AAC3D,YAAMI,WAAW,MAAMC,MAAML,KAAKlD,IAAI;AACtC,aAAO;QAAEK,UAAU,MAAMiD,SAASnC,KAAI;QAAIb,QAAQ;MAAM;IAC1D,CAAA;EACF;AACF;",
6
+ "names": ["build", "initialize", "subtleCrypto", "invariant", "log", "initialized", "initializeBundler", "options", "wasmURL", "wasmUrl", "Bundler", "constructor", "_options", "bundle", "source", "sandboxedModules", "providedModules", "createResult", "result", "timestamp", "Date", "now", "sourceHash", "Buffer", "from", "digest", "platform", "imports", "analyzeSourceFileImports", "conditions", "metafile", "write", "entryPoints", "format", "plugins", "name", "setup", "onResolve", "filter", "path", "external", "split", "namespace", "onLoad", "contents", "loader", "module", "RegExp", "namedImports", "find", "entry", "moduleIdentifier", "join", "JSON", "stringify", "httpPlugin", "analyzeImports", "outputFiles", "text", "err", "error", "parsedImports", "allMatches", "IMPORT_REGEX", "Object", "values", "outputs", "map", "parsedImport", "capture", "NAMED_IMPORTS_REGEX", "lastIndex", "namedImportsMatch", "exec", "forEach", "importName", "push", "trim", "moduleUrl", "defaultImport", "code", "defaultImportName", "wildcardImportName", "quotes", "regex", "str", "match", "matches", "slice", "args", "URL", "importer", "toString", "response", "fetch"]
7
7
  }
@@ -1,16 +1,14 @@
1
1
  import {
2
2
  HeaderCodec,
3
- USERFUNCTIONS_PRESET_META_KEY,
4
3
  codec,
5
4
  getUserFunctionUrlInMetadata,
6
5
  matchServiceCredential,
7
6
  publicKeyToDid,
8
7
  setUserFunctionUrlInMetadata,
9
8
  uploadWorkerFunction
10
- } from "../chunk-G6FWCTGT.mjs";
9
+ } from "../chunk-DL5XQRQM.mjs";
11
10
  export {
12
11
  HeaderCodec,
13
- USERFUNCTIONS_PRESET_META_KEY,
14
12
  codec,
15
13
  getUserFunctionUrlInMetadata,
16
14
  matchServiceCredential,