@dxos/functions 0.7.0 → 0.7.1-staging.7f6f91c

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 (51) hide show
  1. package/dist/lib/browser/{chunk-7QJNOQ6N.mjs → chunk-FWIFI2MH.mjs} +57 -32
  2. package/dist/lib/browser/chunk-FWIFI2MH.mjs.map +7 -0
  3. package/dist/lib/browser/{chunk-L7H5DE53.mjs → chunk-QX2SGAWR.mjs} +28 -21
  4. package/dist/lib/browser/chunk-QX2SGAWR.mjs.map +7 -0
  5. package/dist/lib/browser/index.mjs +9 -5
  6. package/dist/lib/browser/index.mjs.map +1 -1
  7. package/dist/lib/browser/meta.json +1 -1
  8. package/dist/lib/browser/testing/index.mjs +6 -6
  9. package/dist/lib/browser/testing/index.mjs.map +3 -3
  10. package/dist/lib/browser/types.mjs +9 -5
  11. package/dist/lib/node/{chunk-TNG3Z74V.cjs → chunk-GKDHAWCP.cjs} +61 -34
  12. package/dist/lib/node/chunk-GKDHAWCP.cjs.map +7 -0
  13. package/dist/lib/node/{chunk-3KJEM5VR.cjs → chunk-OKV7IWWB.cjs} +41 -34
  14. package/dist/lib/node/chunk-OKV7IWWB.cjs.map +7 -0
  15. package/dist/lib/node/index.cjs +17 -13
  16. package/dist/lib/node/index.cjs.map +1 -1
  17. package/dist/lib/node/meta.json +1 -1
  18. package/dist/lib/node/testing/index.cjs +13 -13
  19. package/dist/lib/node/testing/index.cjs.map +2 -2
  20. package/dist/lib/node/types.cjs +11 -7
  21. package/dist/lib/node/types.cjs.map +2 -2
  22. package/dist/lib/node-esm/{chunk-DMTGUST2.mjs → chunk-SPHZ5SOR.mjs} +28 -21
  23. package/dist/lib/node-esm/chunk-SPHZ5SOR.mjs.map +7 -0
  24. package/dist/lib/node-esm/{chunk-SLC6ICH2.mjs → chunk-YSKH6PBN.mjs} +57 -32
  25. package/dist/lib/node-esm/chunk-YSKH6PBN.mjs.map +7 -0
  26. package/dist/lib/node-esm/index.mjs +9 -5
  27. package/dist/lib/node-esm/index.mjs.map +1 -1
  28. package/dist/lib/node-esm/meta.json +1 -1
  29. package/dist/lib/node-esm/testing/index.mjs +6 -6
  30. package/dist/lib/node-esm/testing/index.mjs.map +3 -3
  31. package/dist/lib/node-esm/types.mjs +9 -5
  32. package/dist/types/src/trigger/trigger-registry.d.ts +3 -3
  33. package/dist/types/src/trigger/trigger-registry.d.ts.map +1 -1
  34. package/dist/types/src/types.d.ts +137 -72
  35. package/dist/types/src/types.d.ts.map +1 -1
  36. package/package.json +17 -16
  37. package/schema/functions.json +2 -2
  38. package/src/runtime/scheduler.test.ts +1 -1
  39. package/src/runtime/scheduler.ts +1 -1
  40. package/src/testing/functions-integration.test.ts +1 -1
  41. package/src/testing/util.ts +2 -2
  42. package/src/trigger/trigger-registry.test.ts +7 -9
  43. package/src/trigger/trigger-registry.ts +7 -8
  44. package/src/trigger/type/subscription-trigger.ts +2 -2
  45. package/src/types.ts +70 -36
  46. package/dist/lib/browser/chunk-7QJNOQ6N.mjs.map +0 -7
  47. package/dist/lib/browser/chunk-L7H5DE53.mjs.map +0 -7
  48. package/dist/lib/node/chunk-3KJEM5VR.cjs.map +0 -7
  49. package/dist/lib/node/chunk-TNG3Z74V.cjs.map +0 -7
  50. package/dist/lib/node-esm/chunk-DMTGUST2.mjs.map +0 -7
  51. package/dist/lib/node-esm/chunk-SLC6ICH2.mjs.map +0 -7
package/src/types.ts CHANGED
@@ -2,25 +2,36 @@
2
2
  // Copyright 2023 DXOS.org
3
3
  //
4
4
 
5
- import { RawObject, S, TypedObject } from '@dxos/echo-schema';
5
+ import { AST, RawObject, S, TypedObject } from '@dxos/echo-schema';
6
6
 
7
7
  /**
8
- * Type discriminator for TriggerSpec.
9
- * Every spec has a type field of type FunctionTriggerType that we can use to understand which
10
- * type we're working with.
8
+ * Type discriminator for TriggerType.
9
+ * Every spec has a type field of type TriggerKind that we can use to understand which type we're working with.
11
10
  * https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions
12
11
  */
13
- export type FunctionTriggerType = 'subscription' | 'timer' | 'webhook' | 'websocket';
12
+ export type TriggerKind = 'timer' | 'webhook' | 'websocket' | 'subscription';
14
13
 
14
+ // TODO(burdon): Rename prop kind.
15
+ const typeLiteralAnnotations = { [AST.TitleAnnotationId]: 'Type' };
16
+
17
+ /**
18
+ * Cron timer.
19
+ */
15
20
  const TimerTriggerSchema = S.Struct({
16
- type: S.Literal('timer'),
17
- cron: S.String,
21
+ type: S.Literal('timer').annotations(typeLiteralAnnotations),
22
+ cron: S.NonEmptyString.annotations({
23
+ [AST.TitleAnnotationId]: 'Cron',
24
+ [AST.ExamplesAnnotationId]: '0 0 * * *',
25
+ }),
18
26
  }).pipe(S.mutable);
19
27
 
20
28
  export type TimerTrigger = S.Schema.Type<typeof TimerTriggerSchema>;
21
29
 
30
+ /**
31
+ * Webhook.
32
+ */
22
33
  const WebhookTriggerSchema = S.Struct({
23
- type: S.Literal('webhook'),
34
+ type: S.Literal('webhook').annotations(typeLiteralAnnotations),
24
35
  method: S.String,
25
36
  // Assigned port.
26
37
  port: S.optional(S.Number),
@@ -28,47 +39,86 @@ const WebhookTriggerSchema = S.Struct({
28
39
 
29
40
  export type WebhookTrigger = S.Schema.Type<typeof WebhookTriggerSchema>;
30
41
 
42
+ /**
43
+ * Websocket.
44
+ * @deprecated
45
+ */
31
46
  const WebsocketTriggerSchema = S.Struct({
32
- type: S.Literal('websocket'),
47
+ type: S.Literal('websocket').annotations(typeLiteralAnnotations),
33
48
  url: S.String,
34
49
  init: S.optional(S.Record({ key: S.String, value: S.Any })),
35
50
  }).pipe(S.mutable);
36
51
 
37
52
  export type WebsocketTrigger = S.Schema.Type<typeof WebsocketTriggerSchema>;
38
53
 
54
+ // TODO(burdon): Use ECHO definition (from https://github.com/dxos/dxos/pull/8233).
39
55
  const QuerySchema = S.Struct({
40
- type: S.String,
56
+ type: S.optional(S.String.annotations({ [AST.TitleAnnotationId]: 'Type' })),
41
57
  props: S.optional(S.Record({ key: S.String, value: S.Any })),
42
- });
58
+ }).annotations({ [AST.TitleAnnotationId]: 'Query' });
43
59
 
60
+ /**
61
+ * Subscription.
62
+ */
44
63
  const SubscriptionTriggerSchema = S.Struct({
45
- type: S.Literal('subscription'),
64
+ type: S.Literal('subscription').annotations(typeLiteralAnnotations),
46
65
  // TODO(burdon): Define query DSL (from ECHO). Reconcile with Table.Query.
47
- filter: S.Array(QuerySchema),
66
+ filter: QuerySchema,
48
67
  options: S.optional(
49
68
  S.Struct({
50
69
  // Watch changes to object (not just creation).
51
- deep: S.optional(S.Boolean),
70
+ deep: S.optional(S.Boolean.annotations({ [AST.TitleAnnotationId]: 'Nested' })),
52
71
  // Debounce changes (delay in ms).
53
- delay: S.optional(S.Number),
54
- }),
72
+ delay: S.optional(S.Number.annotations({ [AST.TitleAnnotationId]: 'Delay' })),
73
+ }).annotations({ [AST.TitleAnnotationId]: 'Options' }),
55
74
  ),
56
75
  }).pipe(S.mutable);
57
76
 
58
77
  export type SubscriptionTrigger = S.Schema.Type<typeof SubscriptionTriggerSchema>;
59
78
 
60
- const TriggerSpecSchema = S.Union(
79
+ /**
80
+ * Trigger schema (discriminated union).
81
+ */
82
+ export const TriggerSchema = S.Union(
61
83
  TimerTriggerSchema,
62
84
  WebhookTriggerSchema,
63
85
  WebsocketTriggerSchema,
64
86
  SubscriptionTriggerSchema,
65
- );
87
+ ).annotations({ [AST.TitleAnnotationId]: 'Trigger' });
88
+
89
+ export type TriggerType = S.Schema.Type<typeof TriggerSchema>;
90
+
91
+ /**
92
+ * Function trigger.
93
+ */
94
+ export const FunctionTriggerSchema = S.Struct({
95
+ // TODO(burdon): What type does this reference.
96
+ function: S.optional(S.String.annotations({ [AST.TitleAnnotationId]: 'Function' })),
97
+ enabled: S.optional(S.Boolean.annotations({ [AST.TitleAnnotationId]: 'Enabled' })),
98
+
99
+ // TODO(burdon): Flatten?
100
+ spec: S.optional(TriggerSchema),
101
+
102
+ // TODO(burdon): Get meta from function.
103
+ // The `meta` property is merged into the event data passed to the function.
104
+ meta: S.optional(S.mutable(S.Record({ key: S.String, value: S.Any }))),
105
+ });
106
+
107
+ export type FunctionTriggerType = S.Schema.Type<typeof FunctionTriggerSchema>;
66
108
 
67
- export type TriggerSpec = TimerTrigger | WebhookTrigger | WebsocketTrigger | SubscriptionTrigger;
109
+ /**
110
+ * Function trigger.
111
+ */
112
+ export class FunctionTrigger extends TypedObject({
113
+ typename: 'dxos.org/type/FunctionTrigger',
114
+ version: '0.1.0',
115
+ })(FunctionTriggerSchema.fields) {}
68
116
 
69
117
  /**
70
118
  * Function definition.
119
+ * @deprecated (Use dxos.org/type/Function)
71
120
  */
121
+ // TODO(burdon): Reconcile with FunctionType.
72
122
  export class FunctionDef extends TypedObject({
73
123
  typename: 'dxos.org/type/FunctionDef',
74
124
  version: '0.1.0',
@@ -79,21 +129,6 @@ export class FunctionDef extends TypedObject({
79
129
  handler: S.String,
80
130
  }) {}
81
131
 
82
- /**
83
- * Function trigger.
84
- */
85
- export class FunctionTrigger extends TypedObject({
86
- typename: 'dxos.org/type/FunctionTrigger',
87
- version: '0.1.0',
88
- })({
89
- name: S.optional(S.String),
90
- enabled: S.optional(S.Boolean),
91
- function: S.String.pipe(S.annotations({ description: 'Function URI.' })),
92
- // The `meta` property is merged into the event data passed to the function.
93
- meta: S.optional(S.mutable(S.Record({ key: S.String, value: S.Any }))),
94
- spec: TriggerSpecSchema,
95
- }) {}
96
-
97
132
  /**
98
133
  * Function manifest file.
99
134
  */
@@ -104,5 +139,4 @@ export const FunctionManifestSchema = S.Struct({
104
139
 
105
140
  export type FunctionManifest = S.Schema.Type<typeof FunctionManifestSchema>;
106
141
 
107
- // TODO(burdon): Standards?
108
- export const FUNCTION_SCHEMA = [FunctionDef, FunctionTrigger];
142
+ export const FUNCTION_TYPES = [FunctionDef, FunctionTrigger];
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../src/types.ts"],
4
- "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { RawObject, S, TypedObject } from '@dxos/echo-schema';\n\n/**\n * Type discriminator for TriggerSpec.\n * Every spec has a type field of type FunctionTriggerType that we can use to understand which\n * type we're working with.\n * https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions\n */\nexport type FunctionTriggerType = 'subscription' | 'timer' | 'webhook' | 'websocket';\n\nconst TimerTriggerSchema = S.Struct({\n type: S.Literal('timer'),\n cron: S.String,\n}).pipe(S.mutable);\n\nexport type TimerTrigger = S.Schema.Type<typeof TimerTriggerSchema>;\n\nconst WebhookTriggerSchema = S.Struct({\n type: S.Literal('webhook'),\n method: S.String,\n // Assigned port.\n port: S.optional(S.Number),\n}).pipe(S.mutable);\n\nexport type WebhookTrigger = S.Schema.Type<typeof WebhookTriggerSchema>;\n\nconst WebsocketTriggerSchema = S.Struct({\n type: S.Literal('websocket'),\n url: S.String,\n init: S.optional(S.Record({ key: S.String, value: S.Any })),\n}).pipe(S.mutable);\n\nexport type WebsocketTrigger = S.Schema.Type<typeof WebsocketTriggerSchema>;\n\nconst QuerySchema = S.Struct({\n type: S.String,\n props: S.optional(S.Record({ key: S.String, value: S.Any })),\n});\n\nconst SubscriptionTriggerSchema = S.Struct({\n type: S.Literal('subscription'),\n // TODO(burdon): Define query DSL (from ECHO). Reconcile with Table.Query.\n filter: S.Array(QuerySchema),\n options: S.optional(\n S.Struct({\n // Watch changes to object (not just creation).\n deep: S.optional(S.Boolean),\n // Debounce changes (delay in ms).\n delay: S.optional(S.Number),\n }),\n ),\n}).pipe(S.mutable);\n\nexport type SubscriptionTrigger = S.Schema.Type<typeof SubscriptionTriggerSchema>;\n\nconst TriggerSpecSchema = S.Union(\n TimerTriggerSchema,\n WebhookTriggerSchema,\n WebsocketTriggerSchema,\n SubscriptionTriggerSchema,\n);\n\nexport type TriggerSpec = TimerTrigger | WebhookTrigger | WebsocketTrigger | SubscriptionTrigger;\n\n/**\n * Function definition.\n */\nexport class FunctionDef extends TypedObject({\n typename: 'dxos.org/type/FunctionDef',\n version: '0.1.0',\n})({\n uri: S.String,\n description: S.optional(S.String),\n route: S.String,\n handler: S.String,\n}) {}\n\n/**\n * Function trigger.\n */\nexport class FunctionTrigger extends TypedObject({\n typename: 'dxos.org/type/FunctionTrigger',\n version: '0.1.0',\n})({\n name: S.optional(S.String),\n enabled: S.optional(S.Boolean),\n function: S.String.pipe(S.annotations({ description: 'Function URI.' })),\n // The `meta` property is merged into the event data passed to the function.\n meta: S.optional(S.mutable(S.Record({ key: S.String, value: S.Any }))),\n spec: TriggerSpecSchema,\n}) {}\n\n/**\n * Function manifest file.\n */\nexport const FunctionManifestSchema = S.Struct({\n functions: S.optional(S.mutable(S.Array(RawObject(FunctionDef)))),\n triggers: S.optional(S.mutable(S.Array(RawObject(FunctionTrigger)))),\n});\n\nexport type FunctionManifest = S.Schema.Type<typeof FunctionManifestSchema>;\n\n// TODO(burdon): Standards?\nexport const FUNCTION_SCHEMA = [FunctionDef, FunctionTrigger];\n"],
5
- "mappings": ";;;;;;;;;AAIA,SAASA,WAAWC,GAAGC,mBAAmB;AAU1C,IAAMC,qBAAqBC,EAAEC,OAAO;EAClCC,MAAMF,EAAEG,QAAQ,OAAA;EAChBC,MAAMJ,EAAEK;AACV,CAAA,EAAGC,KAAKN,EAAEO,OAAO;AAIjB,IAAMC,uBAAuBR,EAAEC,OAAO;EACpCC,MAAMF,EAAEG,QAAQ,SAAA;EAChBM,QAAQT,EAAEK;;EAEVK,MAAMV,EAAEW,SAASX,EAAEY,MAAM;AAC3B,CAAA,EAAGN,KAAKN,EAAEO,OAAO;AAIjB,IAAMM,yBAAyBb,EAAEC,OAAO;EACtCC,MAAMF,EAAEG,QAAQ,WAAA;EAChBW,KAAKd,EAAEK;EACPU,MAAMf,EAAEW,SAASX,EAAEgB,OAAO;IAAEC,KAAKjB,EAAEK;IAAQa,OAAOlB,EAAEmB;EAAI,CAAA,CAAA;AAC1D,CAAA,EAAGb,KAAKN,EAAE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AAO;EAC7C8C,WAAW/C,EAAEW,SAASX,EAAEO,QAAQP,EAAEwB,MAAMwB,UAAUjB,WAAAA,CAAAA,CAAAA,CAAAA;EAClDkB,UAAUjD,EAAEW,SAASX,EAAEO,QAAQP,EAAEwB,MAAMwB,UAAUT,eAAAA,CAAAA,CAAAA,CAAAA;AACnD,CAAA;AAKO,IAAMW,kBAAkB;EAACnB;EAAaQ;;",
6
- "names": ["RawObject", "S", "TypedObject", "TimerTriggerSchema", "S", "Struct", "type", "Literal", "cron", "String", "pipe", "mutable", "WebhookTriggerSchema", "method", "port", "optional", "Number", "WebsocketTriggerSchema", "url", "init", "Record", "key", "value", "Any", "QuerySchema", "props", "SubscriptionTriggerSchema", "filter", "Array", "options", "deep", "Boolean", "delay", "TriggerSpecSchema", "Union", "FunctionDef", "TypedObject", "typename", "version", "uri", "description", "route", "handler", "FunctionTrigger", "name", "enabled", "function", "annotations", "meta", "spec", "FunctionManifestSchema", "functions", "RawObject", "triggers", "FUNCTION_SCHEMA"]
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../src/function/function-registry.ts", "../../../src/trigger/type/subscription-trigger.ts", "../../../src/trigger/type/timer-trigger.ts", "../../../src/trigger/type/websocket-trigger.ts", "../../../src/trigger/trigger-registry.ts"],
4
- "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { Event } from '@dxos/async';\nimport { type Client } from '@dxos/client';\nimport { create, Filter, type Space } from '@dxos/client/echo';\nimport { type Context, Resource } from '@dxos/context';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { ComplexMap, diff } from '@dxos/util';\n\nimport { FunctionDef, type FunctionManifest } from '../types';\n\nexport type FunctionsRegisteredEvent = {\n space: Space;\n added: FunctionDef[];\n};\n\nexport class FunctionRegistry extends Resource {\n private readonly _functionBySpaceKey = new ComplexMap<PublicKey, FunctionDef[]>(PublicKey.hash);\n\n public readonly registered = new Event<FunctionsRegisteredEvent>();\n\n constructor(private readonly _client: Client) {\n super();\n }\n\n public getFunctions(space: Space): FunctionDef[] {\n return this._functionBySpaceKey.get(space.key) ?? [];\n }\n\n public getUniqueByUri(): FunctionDef[] {\n const uniqueByUri = [...this._functionBySpaceKey.values()]\n .flatMap((defs) => defs)\n .reduce((acc, v) => {\n acc.set(v.uri, v);\n return acc;\n }, new Map<string, FunctionDef>());\n return [...uniqueByUri.values()];\n }\n\n /**\n * Loads function definitions from the manifest into the space.\n * We first load all the definitions from the space to deduplicate by functionId.\n */\n public async register(space: Space, functions: FunctionManifest['functions']): Promise<void> {\n log('register', { space: space.key, functions: functions?.length ?? 0 });\n if (!functions?.length) {\n return;\n }\n if (!space.db.graph.schemaRegistry.hasSchema(FunctionDef)) {\n space.db.graph.schemaRegistry.addSchema([FunctionDef]);\n }\n\n // Sync definitions.\n const { objects: existing } = await space.db.query(Filter.schema(FunctionDef)).run();\n const { added } = diff(existing, functions, (a, b) => a.uri === b.uri);\n // TODO(burdon): Update existing templates.\n added.forEach((def) => space.db.add(create(FunctionDef, def)));\n\n if (added.length > 0) {\n await space.db.flush({ indexes: true, updates: true });\n }\n }\n\n protected override async _open(): Promise<void> {\n log.info('opening...');\n const spacesSubscription = this._client.spaces.subscribe(async (spaces) => {\n for (const space of spaces) {\n if (this._functionBySpaceKey.has(space.key)) {\n continue;\n }\n\n const registered: FunctionDef[] = [];\n this._functionBySpaceKey.set(space.key, registered);\n await space.waitUntilReady();\n if (this._ctx.disposed) {\n break;\n }\n\n // Subscribe to updates.\n this._ctx.onDispose(\n space.db.query(Filter.schema(FunctionDef)).subscribe(({ objects }) => {\n const { added } = diff(registered, objects, (a, b) => a.uri === b.uri);\n // TODO(burdon): Update and remove.\n if (added.length > 0) {\n registered.push(...added);\n this.registered.emit({ space, added });\n }\n }),\n );\n }\n });\n\n // TODO(burdon): API: Normalize unsubscribe methods.\n this._ctx.onDispose(() => spacesSubscription.unsubscribe());\n }\n\n protected override async _close(_: Context): Promise<void> {\n log.info('closing...');\n this._functionBySpaceKey.clear();\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { debounce, UpdateScheduler } from '@dxos/async';\nimport { Filter, type Space } from '@dxos/client/echo';\nimport { type Context } from '@dxos/context';\nimport { createSubscription, type Query } from '@dxos/echo-db';\nimport { log } from '@dxos/log';\n\nimport type { SubscriptionTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerFactory } from '../trigger-registry';\n\nexport const createSubscriptionTrigger: TriggerFactory<SubscriptionTrigger> = async (\n ctx: Context,\n space: Space,\n spec: SubscriptionTrigger,\n callback: TriggerCallback,\n) => {\n const objectIds = new Set<string>();\n const task = new UpdateScheduler(\n ctx,\n async () => {\n if (objectIds.size > 0) {\n const objects = Array.from(objectIds);\n objectIds.clear();\n await callback({ objects });\n }\n },\n { maxFrequency: 4 },\n );\n\n // TODO(burdon): Factor out diff.\n // TODO(burdon): Don't fire initially?\n // TODO(burdon): Create queue. Only allow one invocation per trigger at a time?\n const subscriptions: (() => void)[] = [];\n const subscription = createSubscription(({ added, updated }) => {\n const sizeBefore = objectIds.size;\n for (const object of added) {\n objectIds.add(object.id);\n }\n for (const object of updated) {\n objectIds.add(object.id);\n }\n if (objectIds.size > sizeBefore) {\n log.info('updated', { added: added.length, updated: updated.length });\n task.trigger();\n }\n });\n\n subscriptions.push(() => subscription.unsubscribe());\n\n // TODO(burdon): Disable trigger if keeps failing.\n const { filter, options: { deep, delay } = {} } = spec;\n const update = ({ objects }: Query) => {\n log.info('update', { objects: objects.length });\n subscription.update(objects);\n\n // TODO(burdon): Hack to monitor changes to Document's text object.\n if (deep) {\n // TODO(dmaretskyi): Removed to not have dependency on markdown-plugin.\n // for (const object of objects) {\n // const content = object.content;\n // if (content instanceof TextType) {\n // subscriptions.push(getObjectCore(content).updates.on(debounce(() => subscription.update([object]), 1_000)));\n // }\n // }\n }\n };\n\n // TODO(burdon): OR not working.\n // TODO(burdon): [Bug]: all callbacks are fired on the first mutation.\n // TODO(burdon): [Bug]: not updated when document is deleted (either top or hierarchically).\n log.info('subscription', { filter });\n // const query = triggerCtx.space.db.query(Filter.or(filter.map(({ type, props }) => Filter.typename(type, props))));\n if (filter) {\n const query = space.db.query(Filter.typename(filter[0].type, filter[0].props));\n subscriptions.push(query.subscribe(delay ? debounce(update, delay) : update));\n }\n\n ctx.onDispose(() => {\n subscriptions.forEach((unsubscribe) => unsubscribe());\n });\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { CronJob } from 'cron';\n\nimport { DeferredTask } from '@dxos/async';\nimport { type Space } from '@dxos/client/echo';\nimport { type Context } from '@dxos/context';\nimport { log } from '@dxos/log';\n\nimport type { TimerTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerFactory } from '../trigger-registry';\n\nexport const createTimerTrigger: TriggerFactory<TimerTrigger> = async (\n ctx: Context,\n space: Space,\n spec: TimerTrigger,\n callback: TriggerCallback,\n) => {\n const task = new DeferredTask(ctx, async () => {\n await callback({});\n });\n\n let last = 0;\n let run = 0;\n // https://www.npmjs.com/package/cron#constructor\n const job = CronJob.from({\n cronTime: spec.cron,\n runOnInit: false,\n onTick: () => {\n // TODO(burdon): Check greater than 30s (use cron-parser).\n const now = Date.now();\n const delta = last ? now - last : 0;\n last = now;\n\n run++;\n log.info('tick', { space: space.key.truncate(), count: run, delta });\n task.schedule();\n },\n });\n\n job.start();\n ctx.onDispose(() => job.stop());\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { sleep, Trigger } from '@dxos/async';\nimport { type Space } from '@dxos/client/echo';\nimport { type Context } from '@dxos/context';\nimport { log } from '@dxos/log';\n\nimport { type WebsocketTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerFactory } from '../trigger-registry';\n\ninterface WebsocketTriggerOptions {\n retryDelay: number;\n maxAttempts: number;\n}\n\n/**\n * Websocket.\n * NOTE: The port must be unique, so the same hook cannot be used for multiple spaces.\n */\nexport const createWebsocketTrigger: TriggerFactory<WebsocketTrigger, WebsocketTriggerOptions> = async (\n ctx: Context,\n space: Space,\n spec: WebsocketTrigger,\n callback: TriggerCallback,\n options: WebsocketTriggerOptions = { retryDelay: 2, maxAttempts: 5 },\n) => {\n const { url, init } = spec;\n\n let wasOpen = false;\n let ws: WebSocket;\n for (let attempt = 1; attempt <= options.maxAttempts; attempt++) {\n const open = new Trigger<boolean>();\n\n ws = await createWebSocket(url);\n Object.assign(ws, {\n onopen: () => {\n log.info('opened', { url });\n if (spec.init) {\n ws.send(new TextEncoder().encode(JSON.stringify(init)));\n }\n\n open.wake(true);\n },\n\n onclose: (event) => {\n log.info('closed', { url, code: event.code });\n // Reconnect if server closes (e.g., CF restart).\n // https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code\n if (event.code === 1006 && wasOpen && !ctx.disposed) {\n setTimeout(async () => {\n log.info(`reconnecting in ${options.retryDelay}s...`, { url });\n await createWebsocketTrigger(ctx, space, spec, callback, options);\n }, options.retryDelay * 1_000);\n }\n open.wake(false);\n },\n\n onerror: (event) => {\n log.catch((event as any).error ?? new Error('Unspecified ws error.'), { url });\n open.wake(false);\n },\n\n onmessage: async (event) => {\n try {\n log.info('message');\n let data;\n if (event.data && 'text' in event.data) {\n data = JSON.parse(await (event.data as Blob).text());\n } else {\n data = JSON.parse(new TextDecoder().decode(event.data as Uint8Array));\n }\n await callback({ data });\n } catch (err) {\n log.catch(err, { url, data: event.data });\n }\n },\n } satisfies Partial<WebSocket>);\n\n const isOpen = await open.wait();\n if (ctx.disposed) {\n break;\n }\n if (isOpen) {\n wasOpen = true;\n break;\n }\n const wait = Math.pow(attempt, 2) * options.retryDelay;\n if (attempt < options.maxAttempts) {\n log.warn(`failed to connect; trying again in ${wait}s`, { attempt });\n await sleep(wait * 1_000);\n }\n }\n\n ctx.onDispose(() => {\n ws?.close();\n });\n};\n\nconst createNodeWebSocket = async (url: string) => {\n // eslint-disable-next-line no-new-func\n const importESM = Function('path', 'return import(path)');\n const {\n default: { WebSocket },\n } = await importESM('ws');\n return new WebSocket(url);\n};\n\nexport const createWebSocket = async (url: string): Promise<WebSocket> => {\n return typeof (globalThis as any).WebSocket === 'undefined' ? await createNodeWebSocket(url) : new WebSocket(url);\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { Event } from '@dxos/async';\nimport { type Client } from '@dxos/client';\nimport { create, Filter, getMeta, type Space } from '@dxos/client/echo';\nimport { Context, Resource } from '@dxos/context';\nimport { compareForeignKeys, ECHO_ATTR_META, foreignKey } from '@dxos/echo-schema';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { ComplexMap, diff } from '@dxos/util';\n\nimport { createSubscriptionTrigger, createTimerTrigger, createWebsocketTrigger } from './type';\nimport { type FunctionManifest, FunctionTrigger, type FunctionTriggerType, type TriggerSpec } from '../types';\n\ntype ResponseCode = number;\n\nexport type TriggerCallback = (args: object) => Promise<ResponseCode>;\n\n// TODO(burdon): Make object?\nexport type TriggerFactory<Spec extends TriggerSpec, Options = any> = (\n ctx: Context,\n space: Space,\n spec: Spec,\n callback: TriggerCallback,\n options?: Options,\n) => Promise<void>;\n\nexport type TriggerFactoryMap = Record<FunctionTriggerType, TriggerFactory<any>>;\n\nconst triggerFactory: TriggerFactoryMap = {\n subscription: createSubscriptionTrigger,\n timer: createTimerTrigger,\n // TODO(burdon): Cannot use in browser.\n // webhook: createWebhookTrigger,\n webhook: null as any,\n websocket: createWebsocketTrigger,\n};\n\nexport type TriggerEvent = {\n space: Space;\n triggers: FunctionTrigger[];\n};\n\ntype RegisteredTrigger = {\n activationCtx?: Context;\n trigger: FunctionTrigger;\n};\n\nexport class TriggerRegistry extends Resource {\n private readonly _triggersBySpaceKey = new ComplexMap<PublicKey, RegisteredTrigger[]>(PublicKey.hash);\n\n public readonly registered = new Event<TriggerEvent>();\n public readonly removed = new Event<TriggerEvent>();\n\n constructor(\n private readonly _client: Client,\n private readonly _options?: TriggerFactoryMap,\n ) {\n super();\n }\n\n public getActiveTriggers(space: Space): FunctionTrigger[] {\n return this._getTriggers(space, (t) => t.activationCtx != null);\n }\n\n public getInactiveTriggers(space: Space): FunctionTrigger[] {\n return this._getTriggers(space, (t) => t.activationCtx == null);\n }\n\n /**\n * Set callback for trigger.\n */\n public async activate(space: Space, trigger: FunctionTrigger, callback: TriggerCallback): Promise<void> {\n log('activate', { space: space.key, trigger });\n\n const activationCtx = new Context({ name: `FunctionTrigger-${trigger.function}` });\n this._ctx.onDispose(() => activationCtx.dispose());\n const registeredTrigger = this._triggersBySpaceKey.get(space.key)?.find((reg) => reg.trigger.id === trigger.id);\n invariant(registeredTrigger, `Trigger is not registered: ${trigger.function}`);\n registeredTrigger.activationCtx = activationCtx;\n\n try {\n // Create trigger.\n const options = this._options?.[trigger.spec.type];\n const createTrigger = triggerFactory[trigger.spec.type];\n invariant(createTrigger, `Trigger factory not found: ${trigger.spec.type}`);\n await createTrigger(activationCtx, space, trigger.spec, callback, options);\n } catch (err) {\n delete registeredTrigger.activationCtx;\n throw err;\n }\n }\n\n /**\n * Loads triggers from the manifest into the space.\n */\n public async register(space: Space, manifest: FunctionManifest): Promise<void> {\n log('register', { space: space.key });\n if (!manifest.triggers?.length) {\n return;\n }\n\n if (!space.db.graph.schemaRegistry.hasSchema(FunctionTrigger)) {\n space.db.graph.schemaRegistry.addSchema([FunctionTrigger]);\n }\n\n // Create FK to enable syncing if none are set (NOTE: Possible collision).\n const manifestTriggers = manifest.triggers.map((trigger) => {\n let keys = trigger[ECHO_ATTR_META]?.keys;\n delete trigger[ECHO_ATTR_META];\n if (!keys?.length) {\n keys = [foreignKey('manifest', [trigger.function, trigger.spec.type].join(':'))];\n }\n\n return create(FunctionTrigger, trigger, { keys });\n });\n\n // Sync triggers.\n const { objects: existing } = await space.db.query(Filter.schema(FunctionTrigger)).run();\n const { added } = diff(existing, manifestTriggers, compareForeignKeys);\n\n // TODO(burdon): Update existing.\n added.forEach((trigger) => {\n space.db.add(trigger);\n log.info('added', { meta: getMeta(trigger) });\n });\n\n if (added.length > 0) {\n await space.db.flush();\n }\n }\n\n protected override async _open(): Promise<void> {\n log.info('open...');\n const spaceListSubscription = this._client.spaces.subscribe(async (spaces) => {\n for (const space of spaces) {\n if (this._triggersBySpaceKey.has(space.key)) {\n continue;\n }\n\n const registered: RegisteredTrigger[] = [];\n this._triggersBySpaceKey.set(space.key, registered);\n await space.waitUntilReady();\n if (this._ctx.disposed) {\n break;\n }\n\n // Subscribe to updates.\n this._ctx.onDispose(\n space.db.query(Filter.schema(FunctionTrigger)).subscribe(async ({ objects: current }) => {\n log.info('update', { space: space.key, registered: registered.length, current: current.length });\n await this._handleRemovedTriggers(space, current, registered);\n this._handleNewTriggers(space, current, registered);\n }),\n );\n }\n });\n\n this._ctx.onDispose(() => spaceListSubscription.unsubscribe());\n log.info('opened');\n }\n\n protected override async _close(_: Context): Promise<void> {\n log.info('close...');\n this._triggersBySpaceKey.clear();\n log.info('closed');\n }\n\n private _handleNewTriggers(space: Space, current: FunctionTrigger[], registered: RegisteredTrigger[]) {\n const added = current.filter((candidate) => {\n return candidate.enabled && registered.find((reg) => reg.trigger.id === candidate.id) == null;\n });\n\n if (added.length > 0) {\n const newRegisteredTriggers: RegisteredTrigger[] = added.map((trigger) => ({ trigger }));\n registered.push(...newRegisteredTriggers);\n log.info('added', () => ({\n spaceKey: space.key,\n triggers: added.map((trigger) => trigger.function),\n }));\n\n this.registered.emit({ space, triggers: added });\n }\n }\n\n private async _handleRemovedTriggers(\n space: Space,\n current: FunctionTrigger[],\n registered: RegisteredTrigger[],\n ): Promise<void> {\n const removed: FunctionTrigger[] = [];\n for (let i = registered.length - 1; i >= 0; i--) {\n const wasRemoved =\n current.filter((trigger) => trigger.enabled).find((trigger) => trigger.id === registered[i].trigger.id) == null;\n if (wasRemoved) {\n const unregistered = registered.splice(i, 1)[0];\n await unregistered.activationCtx?.dispose();\n removed.push(unregistered.trigger);\n }\n }\n\n if (removed.length > 0) {\n log.info('removed', () => ({\n spaceKey: space.key,\n triggers: removed.map((trigger) => trigger.function),\n }));\n\n this.removed.emit({ space, triggers: removed });\n }\n }\n\n private _getTriggers(space: Space, predicate: (trigger: RegisteredTrigger) => boolean): FunctionTrigger[] {\n const allSpaceTriggers = this._triggersBySpaceKey.get(space.key) ?? [];\n return allSpaceTriggers.filter(predicate).map((trigger) => trigger.trigger);\n }\n}\n"],
5
- "mappings": ";;;;;;;AAIA,SAASA,aAAa;AAEtB,SAASC,QAAQC,cAA0B;AAC3C,SAAuBC,gBAAgB;AACvC,SAASC,iBAAiB;AAC1B,SAASC,WAAW;AACpB,SAASC,YAAYC,YAAY;;AAS1B,IAAMC,mBAAN,cAA+BC,SAAAA;EAKpCC,YAA6BC,SAAiB;AAC5C,UAAK;SADsBA,UAAAA;SAJZC,sBAAsB,IAAIC,WAAqCC,UAAUC,IAAI;SAE9EC,aAAa,IAAIC,MAAAA;EAIjC;EAEOC,aAAaC,OAA6B;AAC/C,WAAO,KAAKP,oBAAoBQ,IAAID,MAAME,GAAG,KAAK,CAAA;EACpD;EAEOC,iBAAgC;AACrC,UAAMC,cAAc;SAAI,KAAKX,oBAAoBY,OAAM;MACpDC,QAAQ,CAACC,SAASA,IAAAA,EAClBC,OAAO,CAACC,KAAKC,MAAAA;AACZD,UAAIE,IAAID,EAAEE,KAAKF,CAAAA;AACf,aAAOD;IACT,GAAG,oBAAII,IAAAA,CAAAA;AACT,WAAO;SAAIT,YAAYC,OAAM;;EAC/B;;;;;EAMA,MAAaS,SAASd,OAAce,WAAyD;AAC3FC,QAAI,YAAY;MAAEhB,OAAOA,MAAME;MAAKa,WAAWA,WAAWE,UAAU;IAAE,GAAA;;;;;;AACtE,QAAI,CAACF,WAAWE,QAAQ;AACtB;IACF;AACA,QAAI,CAACjB,MAAMkB,GAAGC,MAAMC,eAAeC,UAAUC,WAAAA,GAAc;AACzDtB,YAAMkB,GAAGC,MAAMC,eAAeG,UAAU;QAACD;OAAY;IACvD;AAGA,UAAM,EAAEE,SAASC,SAAQ,IAAK,MAAMzB,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EAAW/C,IAAI,CAAChC,YAAYA,QAAQA,OAAO;EAC5E;AACF;",
6
- "names": ["Event", "create", "Filter", "Resource", "PublicKey", "log", "ComplexMap", "diff", "FunctionRegistry", "Resource", "constructor", "_client", "_functionBySpaceKey", "ComplexMap", "PublicKey", "hash", "registered", "Event", "getFunctions", "space", "get", "key", "getUniqueByUri", "uniqueByUri", "values", "flatMap", "defs", "reduce", "acc", "v", "set", "uri", "Map", "register", "functions", "log", "length", "db", "graph", "schemaRegistry", "hasSchema", "FunctionDef", "addSchema", "objects", "existing", "query", "Filter", "schema", "run", "added", "diff", "a", "b", "forEach", "def", "add", "create", "flush", "indexes", "updates", "_open", "info", "spacesSubscription", "spaces", "subscribe", "has", "waitUntilReady", "_ctx", "disposed", "onDispose", "push", "emit", "unsubscribe", "_close", "_", "clear", "debounce", "UpdateScheduler", "Filter", "createSubscription", "log", "createSubscriptionTrigger", "ctx", "space", "spec", "callback", "objectIds", "Set", "task", "size", "objects", "Array", "from", "clear", "maxFrequency", "subscriptions", "subscription", "added", "updated", "sizeBefore", "object", "add", "id", "info", "length", "trigger", "push", "unsubscribe", "filter", "options", "deep", "delay", "update", "query", "db", "typename", "type", "props", "subscribe", "onDispose", "forEach", "CronJob", "DeferredTask", "log", "createTimerTrigger", "ctx", "space", "spec", "callback", "task", "last", "run", "job", "from", "cronTime", "cron", "runOnInit", "onTick", "now", "Date", "delta", "info", "key", "truncate", "count", "schedule", "start", "onDispose", "stop", "sleep", "Trigger", "log", "createWebsocketTrigger", "ctx", "space", "spec", "callback", "options", "retryDelay", "maxAttempts", "url", "init", "wasOpen", "ws", "attempt", "open", "createWebSocket", "Object", "assign", "onopen", "info", "send", "TextEncoder", "encode", "JSON", "stringify", "wake", "onclose", "event", "code", "disposed", "setTimeout", "onerror", "catch", "error", "Error", "onmessage", "data", "parse", "text", "TextDecoder", "decode", "err", "isOpen", "wait", "Math", "pow", "warn", "onDispose", "close", "createNodeWebSocket", "importESM", "Function", "default", "WebSocket", "globalThis", "Event", "create", "Filter", "getMeta", "Context", "Resource", "compareForeignKeys", "ECHO_ATTR_META", "foreignKey", "invariant", "PublicKey", "log", "ComplexMap", "diff", "triggerFactory", "subscription", "createSubscriptionTrigger", "timer", "createTimerTrigger", "webhook", "websocket", "createWebsocketTrigger", "TriggerRegistry", "Resource", "constructor", "_client", "_options", "_triggersBySpaceKey", "ComplexMap", "PublicKey", "hash", "registered", "Event", "removed", "getActiveTriggers", "space", "_getTriggers", "t", "activationCtx", "getInactiveTriggers", "activate", "trigger", "callback", "log", "key", "Context", "name", "function", "_ctx", "onDispose", "dispose", "registeredTrigger", "get", "find", "reg", "id", "invariant", "options", "spec", "type", "createTrigger", "err", "register", "manifest", "triggers", "length", "db", "graph", "schemaRegistry", "hasSchema", "FunctionTrigger", "addSchema", "manifestTriggers", "map", "keys", "ECHO_ATTR_META", "foreignKey", "join", "create", "objects", "existing", "query", "Filter", "schema", "run", "added", "diff", "compareForeignKeys", "forEach", "add", "info", "meta", "getMeta", "flush", "_open", "spaceListSubscription", "spaces", "subscribe", "has", "set", "waitUntilReady", "disposed", "current", "_handleRemovedTriggers", "_handleNewTriggers", "unsubscribe", "_close", "_", "clear", "filter", "candidate", "enabled", "newRegisteredTriggers", "push", "spaceKey", "emit", "i", "wasRemoved", "unregistered", "splice", "predicate", "allSpaceTriggers"]
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../src/function/function-registry.ts", "../../../src/trigger/type/subscription-trigger.ts", "../../../src/trigger/type/timer-trigger.ts", "../../../src/trigger/type/websocket-trigger.ts", "../../../src/trigger/trigger-registry.ts"],
4
- "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { Event } from '@dxos/async';\nimport { type Client } from '@dxos/client';\nimport { create, Filter, type Space } from '@dxos/client/echo';\nimport { type Context, Resource } from '@dxos/context';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { ComplexMap, diff } from '@dxos/util';\n\nimport { FunctionDef, type FunctionManifest } from '../types';\n\nexport type FunctionsRegisteredEvent = {\n space: Space;\n added: FunctionDef[];\n};\n\nexport class FunctionRegistry extends Resource {\n private readonly _functionBySpaceKey = new ComplexMap<PublicKey, FunctionDef[]>(PublicKey.hash);\n\n public readonly registered = new Event<FunctionsRegisteredEvent>();\n\n constructor(private readonly _client: Client) {\n super();\n }\n\n public getFunctions(space: Space): FunctionDef[] {\n return this._functionBySpaceKey.get(space.key) ?? [];\n }\n\n public getUniqueByUri(): FunctionDef[] {\n const uniqueByUri = [...this._functionBySpaceKey.values()]\n .flatMap((defs) => defs)\n .reduce((acc, v) => {\n acc.set(v.uri, v);\n return acc;\n }, new Map<string, FunctionDef>());\n return [...uniqueByUri.values()];\n }\n\n /**\n * Loads function definitions from the manifest into the space.\n * We first load all the definitions from the space to deduplicate by functionId.\n */\n public async register(space: Space, functions: FunctionManifest['functions']): Promise<void> {\n log('register', { space: space.key, functions: functions?.length ?? 0 });\n if (!functions?.length) {\n return;\n }\n if (!space.db.graph.schemaRegistry.hasSchema(FunctionDef)) {\n space.db.graph.schemaRegistry.addSchema([FunctionDef]);\n }\n\n // Sync definitions.\n const { objects: existing } = await space.db.query(Filter.schema(FunctionDef)).run();\n const { added } = diff(existing, functions, (a, b) => a.uri === b.uri);\n // TODO(burdon): Update existing templates.\n added.forEach((def) => space.db.add(create(FunctionDef, def)));\n\n if (added.length > 0) {\n await space.db.flush({ indexes: true, updates: true });\n }\n }\n\n protected override async _open(): Promise<void> {\n log.info('opening...');\n const spacesSubscription = this._client.spaces.subscribe(async (spaces) => {\n for (const space of spaces) {\n if (this._functionBySpaceKey.has(space.key)) {\n continue;\n }\n\n const registered: FunctionDef[] = [];\n this._functionBySpaceKey.set(space.key, registered);\n await space.waitUntilReady();\n if (this._ctx.disposed) {\n break;\n }\n\n // Subscribe to updates.\n this._ctx.onDispose(\n space.db.query(Filter.schema(FunctionDef)).subscribe(({ objects }) => {\n const { added } = diff(registered, objects, (a, b) => a.uri === b.uri);\n // TODO(burdon): Update and remove.\n if (added.length > 0) {\n registered.push(...added);\n this.registered.emit({ space, added });\n }\n }),\n );\n }\n });\n\n // TODO(burdon): API: Normalize unsubscribe methods.\n this._ctx.onDispose(() => spacesSubscription.unsubscribe());\n }\n\n protected override async _close(_: Context): Promise<void> {\n log.info('closing...');\n this._functionBySpaceKey.clear();\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { debounce, UpdateScheduler } from '@dxos/async';\nimport { Filter, type Space } from '@dxos/client/echo';\nimport { type Context } from '@dxos/context';\nimport { createSubscription, type Query } from '@dxos/echo-db';\nimport { log } from '@dxos/log';\n\nimport type { SubscriptionTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerFactory } from '../trigger-registry';\n\nexport const createSubscriptionTrigger: TriggerFactory<SubscriptionTrigger> = async (\n ctx: Context,\n space: Space,\n spec: SubscriptionTrigger,\n callback: TriggerCallback,\n) => {\n const objectIds = new Set<string>();\n const task = new UpdateScheduler(\n ctx,\n async () => {\n if (objectIds.size > 0) {\n const objects = Array.from(objectIds);\n objectIds.clear();\n await callback({ objects });\n }\n },\n { maxFrequency: 4 },\n );\n\n // TODO(burdon): Factor out diff.\n // TODO(burdon): Don't fire initially?\n // TODO(burdon): Create queue. Only allow one invocation per trigger at a time?\n const subscriptions: (() => void)[] = [];\n const subscription = createSubscription(({ added, updated }) => {\n const sizeBefore = objectIds.size;\n for (const object of added) {\n objectIds.add(object.id);\n }\n for (const object of updated) {\n objectIds.add(object.id);\n }\n if (objectIds.size > sizeBefore) {\n log.info('updated', { added: added.length, updated: updated.length });\n task.trigger();\n }\n });\n\n subscriptions.push(() => subscription.unsubscribe());\n\n // TODO(burdon): Disable trigger if keeps failing.\n const { filter, options: { deep, delay } = {} } = spec;\n const update = ({ objects }: Query) => {\n log.info('update', { objects: objects.length });\n subscription.update(objects);\n\n // TODO(burdon): Hack to monitor changes to Document's text object.\n if (deep) {\n // TODO(dmaretskyi): Removed to not have dependency on markdown-plugin.\n // for (const object of objects) {\n // const content = object.content;\n // if (content instanceof TextType) {\n // subscriptions.push(getObjectCore(content).updates.on(debounce(() => subscription.update([object]), 1_000)));\n // }\n // }\n }\n };\n\n // TODO(burdon): OR not working.\n // TODO(burdon): [Bug]: all callbacks are fired on the first mutation.\n // TODO(burdon): [Bug]: not updated when document is deleted (either top or hierarchically).\n log.info('subscription', { filter });\n // const query = triggerCtx.space.db.query(Filter.or(filter.map(({ type, props }) => Filter.typename(type, props))));\n if (filter) {\n const query = space.db.query(Filter.typename(filter[0].type, filter[0].props));\n subscriptions.push(query.subscribe(delay ? debounce(update, delay) : update));\n }\n\n ctx.onDispose(() => {\n subscriptions.forEach((unsubscribe) => unsubscribe());\n });\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { CronJob } from 'cron';\n\nimport { DeferredTask } from '@dxos/async';\nimport { type Space } from '@dxos/client/echo';\nimport { type Context } from '@dxos/context';\nimport { log } from '@dxos/log';\n\nimport type { TimerTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerFactory } from '../trigger-registry';\n\nexport const createTimerTrigger: TriggerFactory<TimerTrigger> = async (\n ctx: Context,\n space: Space,\n spec: TimerTrigger,\n callback: TriggerCallback,\n) => {\n const task = new DeferredTask(ctx, async () => {\n await callback({});\n });\n\n let last = 0;\n let run = 0;\n // https://www.npmjs.com/package/cron#constructor\n const job = CronJob.from({\n cronTime: spec.cron,\n runOnInit: false,\n onTick: () => {\n // TODO(burdon): Check greater than 30s (use cron-parser).\n const now = Date.now();\n const delta = last ? now - last : 0;\n last = now;\n\n run++;\n log.info('tick', { space: space.key.truncate(), count: run, delta });\n task.schedule();\n },\n });\n\n job.start();\n ctx.onDispose(() => job.stop());\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { sleep, Trigger } from '@dxos/async';\nimport { type Space } from '@dxos/client/echo';\nimport { type Context } from '@dxos/context';\nimport { log } from '@dxos/log';\n\nimport { type WebsocketTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerFactory } from '../trigger-registry';\n\ninterface WebsocketTriggerOptions {\n retryDelay: number;\n maxAttempts: number;\n}\n\n/**\n * Websocket.\n * NOTE: The port must be unique, so the same hook cannot be used for multiple spaces.\n */\nexport const createWebsocketTrigger: TriggerFactory<WebsocketTrigger, WebsocketTriggerOptions> = async (\n ctx: Context,\n space: Space,\n spec: WebsocketTrigger,\n callback: TriggerCallback,\n options: WebsocketTriggerOptions = { retryDelay: 2, maxAttempts: 5 },\n) => {\n const { url, init } = spec;\n\n let wasOpen = false;\n let ws: WebSocket;\n for (let attempt = 1; attempt <= options.maxAttempts; attempt++) {\n const open = new Trigger<boolean>();\n\n ws = await createWebSocket(url);\n Object.assign(ws, {\n onopen: () => {\n log.info('opened', { url });\n if (spec.init) {\n ws.send(new TextEncoder().encode(JSON.stringify(init)));\n }\n\n open.wake(true);\n },\n\n onclose: (event) => {\n log.info('closed', { url, code: event.code });\n // Reconnect if server closes (e.g., CF restart).\n // https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code\n if (event.code === 1006 && wasOpen && !ctx.disposed) {\n setTimeout(async () => {\n log.info(`reconnecting in ${options.retryDelay}s...`, { url });\n await createWebsocketTrigger(ctx, space, spec, callback, options);\n }, options.retryDelay * 1_000);\n }\n open.wake(false);\n },\n\n onerror: (event) => {\n log.catch((event as any).error ?? new Error('Unspecified ws error.'), { url });\n open.wake(false);\n },\n\n onmessage: async (event) => {\n try {\n log.info('message');\n let data;\n if (event.data && 'text' in event.data) {\n data = JSON.parse(await (event.data as Blob).text());\n } else {\n data = JSON.parse(new TextDecoder().decode(event.data as Uint8Array));\n }\n await callback({ data });\n } catch (err) {\n log.catch(err, { url, data: event.data });\n }\n },\n } satisfies Partial<WebSocket>);\n\n const isOpen = await open.wait();\n if (ctx.disposed) {\n break;\n }\n if (isOpen) {\n wasOpen = true;\n break;\n }\n const wait = Math.pow(attempt, 2) * options.retryDelay;\n if (attempt < options.maxAttempts) {\n log.warn(`failed to connect; trying again in ${wait}s`, { attempt });\n await sleep(wait * 1_000);\n }\n }\n\n ctx.onDispose(() => {\n ws?.close();\n });\n};\n\nconst createNodeWebSocket = async (url: string) => {\n // eslint-disable-next-line no-new-func\n const importESM = Function('path', 'return import(path)');\n const {\n default: { WebSocket },\n } = await importESM('ws');\n return new WebSocket(url);\n};\n\nexport const createWebSocket = async (url: string): Promise<WebSocket> => {\n return typeof (globalThis as any).WebSocket === 'undefined' ? await createNodeWebSocket(url) : new WebSocket(url);\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { Event } from '@dxos/async';\nimport { type Client } from '@dxos/client';\nimport { create, Filter, getMeta, type Space } from '@dxos/client/echo';\nimport { Context, Resource } from '@dxos/context';\nimport { compareForeignKeys, ECHO_ATTR_META, foreignKey } from '@dxos/echo-schema';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { ComplexMap, diff } from '@dxos/util';\n\nimport { createSubscriptionTrigger, createTimerTrigger, createWebsocketTrigger } from './type';\nimport { type FunctionManifest, FunctionTrigger, type FunctionTriggerType, type TriggerSpec } from '../types';\n\ntype ResponseCode = number;\n\nexport type TriggerCallback = (args: object) => Promise<ResponseCode>;\n\n// TODO(burdon): Make object?\nexport type TriggerFactory<Spec extends TriggerSpec, Options = any> = (\n ctx: Context,\n space: Space,\n spec: Spec,\n callback: TriggerCallback,\n options?: Options,\n) => Promise<void>;\n\nexport type TriggerFactoryMap = Record<FunctionTriggerType, TriggerFactory<any>>;\n\nconst triggerFactory: TriggerFactoryMap = {\n subscription: createSubscriptionTrigger,\n timer: createTimerTrigger,\n // TODO(burdon): Cannot use in browser.\n // webhook: createWebhookTrigger,\n webhook: null as any,\n websocket: createWebsocketTrigger,\n};\n\nexport type TriggerEvent = {\n space: Space;\n triggers: FunctionTrigger[];\n};\n\ntype RegisteredTrigger = {\n activationCtx?: Context;\n trigger: FunctionTrigger;\n};\n\nexport class TriggerRegistry extends Resource {\n private readonly _triggersBySpaceKey = new ComplexMap<PublicKey, RegisteredTrigger[]>(PublicKey.hash);\n\n public readonly registered = new Event<TriggerEvent>();\n public readonly removed = new Event<TriggerEvent>();\n\n constructor(\n private readonly _client: Client,\n private readonly _options?: TriggerFactoryMap,\n ) {\n super();\n }\n\n public getActiveTriggers(space: Space): FunctionTrigger[] {\n return this._getTriggers(space, (t) => t.activationCtx != null);\n }\n\n public getInactiveTriggers(space: Space): FunctionTrigger[] {\n return this._getTriggers(space, (t) => t.activationCtx == null);\n }\n\n /**\n * Set callback for trigger.\n */\n public async activate(space: Space, trigger: FunctionTrigger, callback: TriggerCallback): Promise<void> {\n log('activate', { space: space.key, trigger });\n\n const activationCtx = new Context({ name: `FunctionTrigger-${trigger.function}` });\n this._ctx.onDispose(() => activationCtx.dispose());\n const registeredTrigger = this._triggersBySpaceKey.get(space.key)?.find((reg) => reg.trigger.id === trigger.id);\n invariant(registeredTrigger, `Trigger is not registered: ${trigger.function}`);\n registeredTrigger.activationCtx = activationCtx;\n\n try {\n // Create trigger.\n const options = this._options?.[trigger.spec.type];\n const createTrigger = triggerFactory[trigger.spec.type];\n invariant(createTrigger, `Trigger factory not found: ${trigger.spec.type}`);\n await createTrigger(activationCtx, space, trigger.spec, callback, options);\n } catch (err) {\n delete registeredTrigger.activationCtx;\n throw err;\n }\n }\n\n /**\n * Loads triggers from the manifest into the space.\n */\n public async register(space: Space, manifest: FunctionManifest): Promise<void> {\n log('register', { space: space.key });\n if (!manifest.triggers?.length) {\n return;\n }\n\n if (!space.db.graph.schemaRegistry.hasSchema(FunctionTrigger)) {\n space.db.graph.schemaRegistry.addSchema([FunctionTrigger]);\n }\n\n // Create FK to enable syncing if none are set (NOTE: Possible collision).\n const manifestTriggers = manifest.triggers.map((trigger) => {\n let keys = trigger[ECHO_ATTR_META]?.keys;\n delete trigger[ECHO_ATTR_META];\n if (!keys?.length) {\n keys = [foreignKey('manifest', [trigger.function, trigger.spec.type].join(':'))];\n }\n\n return create(FunctionTrigger, trigger, { keys });\n });\n\n // Sync triggers.\n const { objects: existing } = await space.db.query(Filter.schema(FunctionTrigger)).run();\n const { added } = diff(existing, manifestTriggers, compareForeignKeys);\n\n // TODO(burdon): Update existing.\n added.forEach((trigger) => {\n space.db.add(trigger);\n log.info('added', { meta: getMeta(trigger) });\n });\n\n if (added.length > 0) {\n await space.db.flush();\n }\n }\n\n protected override async _open(): Promise<void> {\n log.info('open...');\n const spaceListSubscription = this._client.spaces.subscribe(async (spaces) => {\n for (const space of spaces) {\n if (this._triggersBySpaceKey.has(space.key)) {\n continue;\n }\n\n const registered: RegisteredTrigger[] = [];\n this._triggersBySpaceKey.set(space.key, registered);\n await space.waitUntilReady();\n if (this._ctx.disposed) {\n break;\n }\n\n // Subscribe to updates.\n this._ctx.onDispose(\n space.db.query(Filter.schema(FunctionTrigger)).subscribe(async ({ objects: current }) => {\n log.info('update', { space: space.key, registered: registered.length, current: current.length });\n await this._handleRemovedTriggers(space, current, registered);\n this._handleNewTriggers(space, current, registered);\n }),\n );\n }\n });\n\n this._ctx.onDispose(() => spaceListSubscription.unsubscribe());\n log.info('opened');\n }\n\n protected override async _close(_: Context): Promise<void> {\n log.info('close...');\n this._triggersBySpaceKey.clear();\n log.info('closed');\n }\n\n private _handleNewTriggers(space: Space, current: FunctionTrigger[], registered: RegisteredTrigger[]) {\n const added = current.filter((candidate) => {\n return candidate.enabled && registered.find((reg) => reg.trigger.id === candidate.id) == null;\n });\n\n if (added.length > 0) {\n const newRegisteredTriggers: RegisteredTrigger[] = added.map((trigger) => ({ trigger }));\n registered.push(...newRegisteredTriggers);\n log.info('added', () => ({\n spaceKey: space.key,\n triggers: added.map((trigger) => trigger.function),\n }));\n\n this.registered.emit({ space, triggers: added });\n }\n }\n\n private async _handleRemovedTriggers(\n space: Space,\n current: FunctionTrigger[],\n registered: RegisteredTrigger[],\n ): Promise<void> {\n const removed: FunctionTrigger[] = [];\n for (let i = registered.length - 1; i >= 0; i--) {\n const wasRemoved =\n current.filter((trigger) => trigger.enabled).find((trigger) => trigger.id === registered[i].trigger.id) == null;\n if (wasRemoved) {\n const unregistered = registered.splice(i, 1)[0];\n await unregistered.activationCtx?.dispose();\n removed.push(unregistered.trigger);\n }\n }\n\n if (removed.length > 0) {\n log.info('removed', () => ({\n spaceKey: space.key,\n triggers: removed.map((trigger) => trigger.function),\n }));\n\n this.removed.emit({ space, triggers: removed });\n }\n }\n\n private _getTriggers(space: Space, predicate: (trigger: RegisteredTrigger) => boolean): FunctionTrigger[] {\n const allSpaceTriggers = this._triggersBySpaceKey.get(space.key) ?? [];\n return allSpaceTriggers.filter(predicate).map((trigger) => trigger.trigger);\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,mBAAsB;AAEtB,kBAA2C;AAC3C,qBAAuC;AACvC,kBAA0B;AAC1B,iBAAoB;AACpB,kBAAiC;ACNjC,IAAAA,gBAA0C;AAC1C,IAAAC,eAAmC;AAEnC,qBAA+C;AAC/C,IAAAC,cAAoB;ACJpB,kBAAwB;AAExB,IAAAF,gBAA6B;AAG7B,IAAAE,cAAoB;ACLpB,IAAAF,gBAA+B;AAG/B,IAAAE,cAAoB;ACHpB,IAAAF,gBAAsB;AAEtB,IAAAC,eAAoD;AACpD,IAAAE,kBAAkC;AAClC,yBAA+D;AAC/D,uBAA0B;AAC1B,IAAAC,eAA0B;AAC1B,IAAAF,cAAoB;AACpB,IAAAG,eAAiC;;AJO1B,IAAMC,mBAAN,cAA+BC,wBAAAA;EAKpCC,YAA6BC,SAAiB;AAC5C,UAAK;SADsBA,UAAAA;SAJZC,sBAAsB,IAAIC,uBAAqCC,sBAAUC,IAAI;SAE9EC,aAAa,IAAIC,mBAAAA;EAIjC;EAEOC,aAAaC,OAA6B;AAC/C,WAAO,KAAKP,oBAAoBQ,IAAID,MAAME,GAAG,KAAK,CAAA;EACpD;EAEOC,iBAAgC;AACrC,UAAMC,cAAc;SAAI,KAAKX,oBAAoBY,OAAM;MACpDC,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I,SAAS,GAAG;AACtBD,kBAAAA,IAAI0B,KAAK,WAAW,OAAO;QACzBuJ,UAAUjM,MAAME;QAChB6K,UAAUjB,QAAQoB,IAAI,CAACtG,YAAYA,QAAQ2F,QAAQ;MACrD,IAAA;;;;;;AAEA,WAAKT,QAAQ1G,KAAK;QAAEpD;QAAO+K,UAAUjB;MAAQ,CAAA;IAC/C;EACF;EAEQE,aAAahK,OAAcsM,WAAuE;AACxG,UAAMC,mBAAmB,KAAK1C,oBAAoB5J,IAAID,MAAME,GAAG,KAAK,CAAA;AACpE,WAAOqM,iBAAiB1H,OAAOyH,SAAAA,EAAWpB,IAAI,CAACtG,YAAYA,QAAQA,OAAO;EAC5E;AACF;",
6
- "names": ["import_async", "import_echo", "import_log", "import_context", "import_keys", "import_util", "FunctionRegistry", "Resource", "constructor", "_client", "_functionBySpaceKey", "ComplexMap", "PublicKey", "hash", "registered", "Event", "getFunctions", "space", "get", "key", "getUniqueByUri", "uniqueByUri", "values", "flatMap", "defs", "reduce", "acc", "v", "set", "uri", "Map", "register", "functions", "log", "length", "db", "graph", "schemaRegistry", "hasSchema", "FunctionDef", "addSchema", "objects", "existing", "query", "Filter", "schema", "run", "added", "diff", "a", "b", "forEach", "def", "add", "create", "flush", "indexes", "updates", "_open", "info", "spacesSubscription", "spaces", "subscribe", "has", "waitUntilReady", "_ctx", "disposed", "onDispose", "push", "emit", "unsubscribe", "_close", "_", "clear", "createSubscriptionTrigger", "ctx", "spec", "callback", "objectIds", "Set", "task", "UpdateScheduler", "size", "Array", "from", "maxFrequency", "subscriptions", "subscription", "createSubscription", "updated", "sizeBefore", "object", "id", "trigger", "filter", "options", "deep", "delay", "update", "typename", "type", "props", "debounce", "createTimerTrigger", "DeferredTask", "last", "job", "CronJob", "cronTime", "cron", "runOnInit", "onTick", "now", "Date", "delta", "truncate", "count", "schedule", "start", "stop", "createWebsocketTrigger", "retryDelay", "maxAttempts", "url", "init", "wasOpen", "ws", "attempt", "open", "Trigger", "createWebSocket", "Object", "assign", "onopen", "send", "TextEncoder", "encode", "JSON", "stringify", "wake", "onclose", "event", "code", "setTimeout", "onerror", "catch", "error", "Error", "onmessage", "data", "parse", "text", "TextDecoder", "decode", "err", "isOpen", "wait", "Math", "pow", "warn", "sleep", "close", "createNodeWebSocket", "importESM", "Function", "default", "WebSocket", "globalThis", "triggerFactory", "timer", "webhook", "websocket", "TriggerRegistry", "_options", "_triggersBySpaceKey", "removed", "getActiveTriggers", "_getTriggers", "t", "activationCtx", "getInactiveTriggers", "activate", "Context", "name", "function", "dispose", "registeredTrigger", "find", "reg", "invariant", "createTrigger", "manifest", "triggers", "FunctionTrigger", "manifestTriggers", "map", "keys", "ECHO_ATTR_META", "foreignKey", "join", "compareForeignKeys", "meta", "getMeta", "spaceListSubscription", "current", "_handleRemovedTriggers", "_handleNewTriggers", "candidate", "enabled", "newRegisteredTriggers", "spaceKey", "i", "wasRemoved", "unregistered", "splice", "predicate", "allSpaceTriggers"]
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../src/types.ts"],
4
- "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { RawObject, S, TypedObject } from '@dxos/echo-schema';\n\n/**\n * Type discriminator for TriggerSpec.\n * Every spec has a type field of type FunctionTriggerType that we can use to understand which\n * type we're working with.\n * https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions\n */\nexport type FunctionTriggerType = 'subscription' | 'timer' | 'webhook' | 'websocket';\n\nconst TimerTriggerSchema = S.Struct({\n type: S.Literal('timer'),\n cron: S.String,\n}).pipe(S.mutable);\n\nexport type TimerTrigger = S.Schema.Type<typeof TimerTriggerSchema>;\n\nconst WebhookTriggerSchema = S.Struct({\n type: S.Literal('webhook'),\n method: S.String,\n // Assigned port.\n port: S.optional(S.Number),\n}).pipe(S.mutable);\n\nexport type WebhookTrigger = S.Schema.Type<typeof WebhookTriggerSchema>;\n\nconst WebsocketTriggerSchema = S.Struct({\n type: S.Literal('websocket'),\n url: S.String,\n init: S.optional(S.Record({ key: S.String, value: S.Any })),\n}).pipe(S.mutable);\n\nexport type WebsocketTrigger = S.Schema.Type<typeof WebsocketTriggerSchema>;\n\nconst QuerySchema = S.Struct({\n type: S.String,\n props: S.optional(S.Record({ key: S.String, value: S.Any })),\n});\n\nconst SubscriptionTriggerSchema = S.Struct({\n type: S.Literal('subscription'),\n // TODO(burdon): Define query DSL (from ECHO). Reconcile with Table.Query.\n filter: S.Array(QuerySchema),\n options: S.optional(\n S.Struct({\n // Watch changes to object (not just creation).\n deep: S.optional(S.Boolean),\n // Debounce changes (delay in ms).\n delay: S.optional(S.Number),\n }),\n ),\n}).pipe(S.mutable);\n\nexport type SubscriptionTrigger = S.Schema.Type<typeof SubscriptionTriggerSchema>;\n\nconst TriggerSpecSchema = S.Union(\n TimerTriggerSchema,\n WebhookTriggerSchema,\n WebsocketTriggerSchema,\n SubscriptionTriggerSchema,\n);\n\nexport type TriggerSpec = TimerTrigger | WebhookTrigger | WebsocketTrigger | SubscriptionTrigger;\n\n/**\n * Function definition.\n */\nexport class FunctionDef extends TypedObject({\n typename: 'dxos.org/type/FunctionDef',\n version: '0.1.0',\n})({\n uri: S.String,\n description: S.optional(S.String),\n route: S.String,\n handler: S.String,\n}) {}\n\n/**\n * Function trigger.\n */\nexport class FunctionTrigger extends TypedObject({\n typename: 'dxos.org/type/FunctionTrigger',\n version: '0.1.0',\n})({\n name: S.optional(S.String),\n enabled: S.optional(S.Boolean),\n function: S.String.pipe(S.annotations({ description: 'Function URI.' })),\n // The `meta` property is merged into the event data passed to the function.\n meta: S.optional(S.mutable(S.Record({ key: S.String, value: S.Any }))),\n spec: TriggerSpecSchema,\n}) {}\n\n/**\n * Function manifest file.\n */\nexport const FunctionManifestSchema = S.Struct({\n functions: S.optional(S.mutable(S.Array(RawObject(FunctionDef)))),\n triggers: S.optional(S.mutable(S.Array(RawObject(FunctionTrigger)))),\n});\n\nexport type FunctionManifest = S.Schema.Type<typeof Function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AAMsB,oBAAoB7B,qBAAE8B,MAC1B/B,oBACAS,sBACAK,wBACAS,yBAAAA;AAQK,IAAMS,cAAN,kBAA0BC,gCAAY;EAC3CC,UAAU;EACVC,SAAS;AACX,CAAA,EAAG;EACDC,KAAKnC,qBAAEK;EACP+B,aAAapC,qBAAEW,SAASX,qBAAEK,MAAM;EAChCgC,OAAOrC,qBAAEK;EACTiC,SAAStC,qBAAEK;AACb,CAAA,EAAA;AAAI;AAKG,IAAMkC,kBAAN,kBAA8BP,gCAAY;EAC/CC,UAAU;EACVC,SAAS;AACX,CAAA,EAAG;EACDM,MAAMxC,qBAAEW,SAASX,qBAAEK,MAAM;EACzBoC,SAASzC,qBAAEW,SAASX,qBAAE2B,OAAO;EAC7Be,UAAU1C,qBAAEK,OAAOC,KAAKN,qBAAE2C,YAAY;IAAEP,aAAa;EAAgB,CAAA,CAAA;;EAErEQ,MAAM5C,qBAAEW,SAASX,qBAAEO,QAAQP,qBAAEgB,OAAO;IAAEC,KAAKjB,qBAAEK;IAAQa,OAAOlB,qBAAEmB;EAAI,CAAA,CAAA,CAAA;EAClE0B,MAAMhB;AACR,CAAA,EAAA;AAAI;AAKG,IAAMiB,yBAAyB9C,qBAAEC,OAAO;EAC7C8C,WAAW/C,qBAAEW,SAASX,qBAAEO,QAAQP,qBAAEwB,UAAMwB,8BAAUjB,WAAAA,CAAAA,CAAAA,CAAAA;EAClDkB,UAAUjD,qBAAEW,SAASX,qBAAEO,QAAQP,qBAAEwB,UAAMwB,8BAAUT,eAAAA,CAAAA,CAAAA,CAAAA;AACnD,CAAA;AAKO,IAAMW,kBAAkB;EAACnB;EAAaQ;;",
6
- "names": ["TimerTriggerSchema", "S", "Struct", "type", "Literal", "cron", "String", "pipe", "mutable", "WebhookTriggerSchema", "method", "port", "optional", "Number", "WebsocketTriggerSchema", "url", "init", "Record", "key", "value", "Any", "QuerySchema", "props", "SubscriptionTriggerSchema", "filter", "Array", "options", "deep", "Boolean", "delay", "TriggerSpecSchema", "Union", "FunctionDef", "TypedObject", "typename", "version", "uri", "description", "route", "handler", "FunctionTrigger", "name", "enabled", "function", "annotations", "meta", "spec", "FunctionManifestSchema", "functions", "RawObject", "triggers", "FUNCTION_SCHEMA"]
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../src/function/function-registry.ts", "../../../src/trigger/type/subscription-trigger.ts", "../../../src/trigger/type/timer-trigger.ts", "../../../src/trigger/type/websocket-trigger.ts", "../../../src/trigger/trigger-registry.ts"],
4
- "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { Event } from '@dxos/async';\nimport { type Client } from '@dxos/client';\nimport { create, Filter, type Space } from '@dxos/client/echo';\nimport { type Context, Resource } from '@dxos/context';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { ComplexMap, diff } from '@dxos/util';\n\nimport { FunctionDef, type FunctionManifest } from '../types';\n\nexport type FunctionsRegisteredEvent = {\n space: Space;\n added: FunctionDef[];\n};\n\nexport class FunctionRegistry extends Resource {\n private readonly _functionBySpaceKey = new ComplexMap<PublicKey, FunctionDef[]>(PublicKey.hash);\n\n public readonly registered = new Event<FunctionsRegisteredEvent>();\n\n constructor(private readonly _client: Client) {\n super();\n }\n\n public getFunctions(space: Space): FunctionDef[] {\n return this._functionBySpaceKey.get(space.key) ?? [];\n }\n\n public getUniqueByUri(): FunctionDef[] {\n const uniqueByUri = [...this._functionBySpaceKey.values()]\n .flatMap((defs) => defs)\n .reduce((acc, v) => {\n acc.set(v.uri, v);\n return acc;\n }, new Map<string, FunctionDef>());\n return [...uniqueByUri.values()];\n }\n\n /**\n * Loads function definitions from the manifest into the space.\n * We first load all the definitions from the space to deduplicate by functionId.\n */\n public async register(space: Space, functions: FunctionManifest['functions']): Promise<void> {\n log('register', { space: space.key, functions: functions?.length ?? 0 });\n if (!functions?.length) {\n return;\n }\n if (!space.db.graph.schemaRegistry.hasSchema(FunctionDef)) {\n space.db.graph.schemaRegistry.addSchema([FunctionDef]);\n }\n\n // Sync definitions.\n const { objects: existing } = await space.db.query(Filter.schema(FunctionDef)).run();\n const { added } = diff(existing, functions, (a, b) => a.uri === b.uri);\n // TODO(burdon): Update existing templates.\n added.forEach((def) => space.db.add(create(FunctionDef, def)));\n\n if (added.length > 0) {\n await space.db.flush({ indexes: true, updates: true });\n }\n }\n\n protected override async _open(): Promise<void> {\n log.info('opening...');\n const spacesSubscription = this._client.spaces.subscribe(async (spaces) => {\n for (const space of spaces) {\n if (this._functionBySpaceKey.has(space.key)) {\n continue;\n }\n\n const registered: FunctionDef[] = [];\n this._functionBySpaceKey.set(space.key, registered);\n await space.waitUntilReady();\n if (this._ctx.disposed) {\n break;\n }\n\n // Subscribe to updates.\n this._ctx.onDispose(\n space.db.query(Filter.schema(FunctionDef)).subscribe(({ objects }) => {\n const { added } = diff(registered, objects, (a, b) => a.uri === b.uri);\n // TODO(burdon): Update and remove.\n if (added.length > 0) {\n registered.push(...added);\n this.registered.emit({ space, added });\n }\n }),\n );\n }\n });\n\n // TODO(burdon): API: Normalize unsubscribe methods.\n this._ctx.onDispose(() => spacesSubscription.unsubscribe());\n }\n\n protected override async _close(_: Context): Promise<void> {\n log.info('closing...');\n this._functionBySpaceKey.clear();\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { debounce, UpdateScheduler } from '@dxos/async';\nimport { Filter, type Space } from '@dxos/client/echo';\nimport { type Context } from '@dxos/context';\nimport { createSubscription, type Query } from '@dxos/echo-db';\nimport { log } from '@dxos/log';\n\nimport type { SubscriptionTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerFactory } from '../trigger-registry';\n\nexport const createSubscriptionTrigger: TriggerFactory<SubscriptionTrigger> = async (\n ctx: Context,\n space: Space,\n spec: SubscriptionTrigger,\n callback: TriggerCallback,\n) => {\n const objectIds = new Set<string>();\n const task = new UpdateScheduler(\n ctx,\n async () => {\n if (objectIds.size > 0) {\n const objects = Array.from(objectIds);\n objectIds.clear();\n await callback({ objects });\n }\n },\n { maxFrequency: 4 },\n );\n\n // TODO(burdon): Factor out diff.\n // TODO(burdon): Don't fire initially?\n // TODO(burdon): Create queue. Only allow one invocation per trigger at a time?\n const subscriptions: (() => void)[] = [];\n const subscription = createSubscription(({ added, updated }) => {\n const sizeBefore = objectIds.size;\n for (const object of added) {\n objectIds.add(object.id);\n }\n for (const object of updated) {\n objectIds.add(object.id);\n }\n if (objectIds.size > sizeBefore) {\n log.info('updated', { added: added.length, updated: updated.length });\n task.trigger();\n }\n });\n\n subscriptions.push(() => subscription.unsubscribe());\n\n // TODO(burdon): Disable trigger if keeps failing.\n const { filter, options: { deep, delay } = {} } = spec;\n const update = ({ objects }: Query) => {\n log.info('update', { objects: objects.length });\n subscription.update(objects);\n\n // TODO(burdon): Hack to monitor changes to Document's text object.\n if (deep) {\n // TODO(dmaretskyi): Removed to not have dependency on markdown-plugin.\n // for (const object of objects) {\n // const content = object.content;\n // if (content instanceof TextType) {\n // subscriptions.push(getObjectCore(content).updates.on(debounce(() => subscription.update([object]), 1_000)));\n // }\n // }\n }\n };\n\n // TODO(burdon): OR not working.\n // TODO(burdon): [Bug]: all callbacks are fired on the first mutation.\n // TODO(burdon): [Bug]: not updated when document is deleted (either top or hierarchically).\n log.info('subscription', { filter });\n // const query = triggerCtx.space.db.query(Filter.or(filter.map(({ type, props }) => Filter.typename(type, props))));\n if (filter) {\n const query = space.db.query(Filter.typename(filter[0].type, filter[0].props));\n subscriptions.push(query.subscribe(delay ? debounce(update, delay) : update));\n }\n\n ctx.onDispose(() => {\n subscriptions.forEach((unsubscribe) => unsubscribe());\n });\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { CronJob } from 'cron';\n\nimport { DeferredTask } from '@dxos/async';\nimport { type Space } from '@dxos/client/echo';\nimport { type Context } from '@dxos/context';\nimport { log } from '@dxos/log';\n\nimport type { TimerTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerFactory } from '../trigger-registry';\n\nexport const createTimerTrigger: TriggerFactory<TimerTrigger> = async (\n ctx: Context,\n space: Space,\n spec: TimerTrigger,\n callback: TriggerCallback,\n) => {\n const task = new DeferredTask(ctx, async () => {\n await callback({});\n });\n\n let last = 0;\n let run = 0;\n // https://www.npmjs.com/package/cron#constructor\n const job = CronJob.from({\n cronTime: spec.cron,\n runOnInit: false,\n onTick: () => {\n // TODO(burdon): Check greater than 30s (use cron-parser).\n const now = Date.now();\n const delta = last ? now - last : 0;\n last = now;\n\n run++;\n log.info('tick', { space: space.key.truncate(), count: run, delta });\n task.schedule();\n },\n });\n\n job.start();\n ctx.onDispose(() => job.stop());\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { sleep, Trigger } from '@dxos/async';\nimport { type Space } from '@dxos/client/echo';\nimport { type Context } from '@dxos/context';\nimport { log } from '@dxos/log';\n\nimport { type WebsocketTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerFactory } from '../trigger-registry';\n\ninterface WebsocketTriggerOptions {\n retryDelay: number;\n maxAttempts: number;\n}\n\n/**\n * Websocket.\n * NOTE: The port must be unique, so the same hook cannot be used for multiple spaces.\n */\nexport const createWebsocketTrigger: TriggerFactory<WebsocketTrigger, WebsocketTriggerOptions> = async (\n ctx: Context,\n space: Space,\n spec: WebsocketTrigger,\n callback: TriggerCallback,\n options: WebsocketTriggerOptions = { retryDelay: 2, maxAttempts: 5 },\n) => {\n const { url, init } = spec;\n\n let wasOpen = false;\n let ws: WebSocket;\n for (let attempt = 1; attempt <= options.maxAttempts; attempt++) {\n const open = new Trigger<boolean>();\n\n ws = await createWebSocket(url);\n Object.assign(ws, {\n onopen: () => {\n log.info('opened', { url });\n if (spec.init) {\n ws.send(new TextEncoder().encode(JSON.stringify(init)));\n }\n\n open.wake(true);\n },\n\n onclose: (event) => {\n log.info('closed', { url, code: event.code });\n // Reconnect if server closes (e.g., CF restart).\n // https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code\n if (event.code === 1006 && wasOpen && !ctx.disposed) {\n setTimeout(async () => {\n log.info(`reconnecting in ${options.retryDelay}s...`, { url });\n await createWebsocketTrigger(ctx, space, spec, callback, options);\n }, options.retryDelay * 1_000);\n }\n open.wake(false);\n },\n\n onerror: (event) => {\n log.catch((event as any).error ?? new Error('Unspecified ws error.'), { url });\n open.wake(false);\n },\n\n onmessage: async (event) => {\n try {\n log.info('message');\n let data;\n if (event.data && 'text' in event.data) {\n data = JSON.parse(await (event.data as Blob).text());\n } else {\n data = JSON.parse(new TextDecoder().decode(event.data as Uint8Array));\n }\n await callback({ data });\n } catch (err) {\n log.catch(err, { url, data: event.data });\n }\n },\n } satisfies Partial<WebSocket>);\n\n const isOpen = await open.wait();\n if (ctx.disposed) {\n break;\n }\n if (isOpen) {\n wasOpen = true;\n break;\n }\n const wait = Math.pow(attempt, 2) * options.retryDelay;\n if (attempt < options.maxAttempts) {\n log.warn(`failed to connect; trying again in ${wait}s`, { attempt });\n await sleep(wait * 1_000);\n }\n }\n\n ctx.onDispose(() => {\n ws?.close();\n });\n};\n\nconst createNodeWebSocket = async (url: string) => {\n // eslint-disable-next-line no-new-func\n const importESM = Function('path', 'return import(path)');\n const {\n default: { WebSocket },\n } = await importESM('ws');\n return new WebSocket(url);\n};\n\nexport const createWebSocket = async (url: string): Promise<WebSocket> => {\n return typeof (globalThis as any).WebSocket === 'undefined' ? await createNodeWebSocket(url) : new WebSocket(url);\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { Event } from '@dxos/async';\nimport { type Client } from '@dxos/client';\nimport { create, Filter, getMeta, type Space } from '@dxos/client/echo';\nimport { Context, Resource } from '@dxos/context';\nimport { compareForeignKeys, ECHO_ATTR_META, foreignKey } from '@dxos/echo-schema';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { ComplexMap, diff } from '@dxos/util';\n\nimport { createSubscriptionTrigger, createTimerTrigger, createWebsocketTrigger } from './type';\nimport { type FunctionManifest, FunctionTrigger, type FunctionTriggerType, type TriggerSpec } from '../types';\n\ntype ResponseCode = number;\n\nexport type TriggerCallback = (args: object) => Promise<ResponseCode>;\n\n// TODO(burdon): Make object?\nexport type TriggerFactory<Spec extends TriggerSpec, Options = any> = (\n ctx: Context,\n space: Space,\n spec: Spec,\n callback: TriggerCallback,\n options?: Options,\n) => Promise<void>;\n\nexport type TriggerFactoryMap = Record<FunctionTriggerType, TriggerFactory<any>>;\n\nconst triggerFactory: TriggerFactoryMap = {\n subscription: createSubscriptionTrigger,\n timer: createTimerTrigger,\n // TODO(burdon): Cannot use in browser.\n // webhook: createWebhookTrigger,\n webhook: null as any,\n websocket: createWebsocketTrigger,\n};\n\nexport type TriggerEvent = {\n space: Space;\n triggers: FunctionTrigger[];\n};\n\ntype RegisteredTrigger = {\n activationCtx?: Context;\n trigger: FunctionTrigger;\n};\n\nexport class TriggerRegistry extends Resource {\n private readonly _triggersBySpaceKey = new ComplexMap<PublicKey, RegisteredTrigger[]>(PublicKey.hash);\n\n public readonly registered = new Event<TriggerEvent>();\n public readonly removed = new Event<TriggerEvent>();\n\n constructor(\n private readonly _client: Client,\n private readonly _options?: TriggerFactoryMap,\n ) {\n super();\n }\n\n public getActiveTriggers(space: Space): FunctionTrigger[] {\n return this._getTriggers(space, (t) => t.activationCtx != null);\n }\n\n public getInactiveTriggers(space: Space): FunctionTrigger[] {\n return this._getTriggers(space, (t) => t.activationCtx == null);\n }\n\n /**\n * Set callback for trigger.\n */\n public async activate(space: Space, trigger: FunctionTrigger, callback: TriggerCallback): Promise<void> {\n log('activate', { space: space.key, trigger });\n\n const activationCtx = new Context({ name: `FunctionTrigger-${trigger.function}` });\n this._ctx.onDispose(() => activationCtx.dispose());\n const registeredTrigger = this._triggersBySpaceKey.get(space.key)?.find((reg) => reg.trigger.id === trigger.id);\n invariant(registeredTrigger, `Trigger is not registered: ${trigger.function}`);\n registeredTrigger.activationCtx = activationCtx;\n\n try {\n // Create trigger.\n const options = this._options?.[trigger.spec.type];\n const createTrigger = triggerFactory[trigger.spec.type];\n invariant(createTrigger, `Trigger factory not found: ${trigger.spec.type}`);\n await createTrigger(activationCtx, space, trigger.spec, callback, options);\n } catch (err) {\n delete registeredTrigger.activationCtx;\n throw err;\n }\n }\n\n /**\n * Loads triggers from the manifest into the space.\n */\n public async register(space: Space, manifest: FunctionManifest): Promise<void> {\n log('register', { space: space.key });\n if (!manifest.triggers?.length) {\n return;\n }\n\n if (!space.db.graph.schemaRegistry.hasSchema(FunctionTrigger)) {\n space.db.graph.schemaRegistry.addSchema([FunctionTrigger]);\n }\n\n // Create FK to enable syncing if none are set (NOTE: Possible collision).\n const manifestTriggers = manifest.triggers.map((trigger) => {\n let keys = trigger[ECHO_ATTR_META]?.keys;\n delete trigger[ECHO_ATTR_META];\n if (!keys?.length) {\n keys = [foreignKey('manifest', [trigger.function, trigger.spec.type].join(':'))];\n }\n\n return create(FunctionTrigger, trigger, { keys });\n });\n\n // Sync triggers.\n const { objects: existing } = await space.db.query(Filter.schema(FunctionTrigger)).run();\n const { added } = diff(existing, manifestTriggers, compareForeignKeys);\n\n // TODO(burdon): Update existing.\n added.forEach((trigger) => {\n space.db.add(trigger);\n log.info('added', { meta: getMeta(trigger) });\n });\n\n if (added.length > 0) {\n await space.db.flush();\n }\n }\n\n protected override async _open(): Promise<void> {\n log.info('open...');\n const spaceListSubscription = this._client.spaces.subscribe(async (spaces) => {\n for (const space of spaces) {\n if (this._triggersBySpaceKey.has(space.key)) {\n continue;\n }\n\n const registered: RegisteredTrigger[] = [];\n this._triggersBySpaceKey.set(space.key, registered);\n await space.waitUntilReady();\n if (this._ctx.disposed) {\n break;\n }\n\n // Subscribe to updates.\n this._ctx.onDispose(\n space.db.query(Filter.schema(FunctionTrigger)).subscribe(async ({ objects: current }) => {\n log.info('update', { space: space.key, registered: registered.length, current: current.length });\n await this._handleRemovedTriggers(space, current, registered);\n this._handleNewTriggers(space, current, registered);\n }),\n );\n }\n });\n\n this._ctx.onDispose(() => spaceListSubscription.unsubscribe());\n log.info('opened');\n }\n\n protected override async _close(_: Context): Promise<void> {\n log.info('close...');\n this._triggersBySpaceKey.clear();\n log.info('closed');\n }\n\n private _handleNewTriggers(space: Space, current: FunctionTrigger[], registered: RegisteredTrigger[]) {\n const added = current.filter((candidate) => {\n return candidate.enabled && registered.find((reg) => reg.trigger.id === candidate.id) == null;\n });\n\n if (added.length > 0) {\n const newRegisteredTriggers: RegisteredTrigger[] = added.map((trigger) => ({ trigger }));\n registered.push(...newRegisteredTriggers);\n log.info('added', () => ({\n spaceKey: space.key,\n triggers: added.map((trigger) => trigger.function),\n }));\n\n this.registered.emit({ space, triggers: added });\n }\n }\n\n private async _handleRemovedTriggers(\n space: Space,\n current: FunctionTrigger[],\n registered: RegisteredTrigger[],\n ): Promise<void> {\n const removed: FunctionTrigger[] = [];\n for (let i = registered.length - 1; i >= 0; i--) {\n const wasRemoved =\n current.filter((trigger) => trigger.enabled).find((trigger) => trigger.id === registered[i].trigger.id) == null;\n if (wasRemoved) {\n const unregistered = registered.splice(i, 1)[0];\n await unregistered.activationCtx?.dispose();\n removed.push(unregistered.trigger);\n }\n }\n\n if (removed.length > 0) {\n log.info('removed', () => ({\n spaceKey: space.key,\n triggers: removed.map((trigger) => trigger.function),\n }));\n\n this.removed.emit({ space, triggers: removed });\n }\n }\n\n private _getTriggers(space: Space, predicate: (trigger: RegisteredTrigger) => boolean): FunctionTrigger[] {\n const allSpaceTriggers = this._triggersBySpaceKey.get(space.key) ?? [];\n return allSpaceTriggers.filter(predicate).map((trigger) => trigger.trigger);\n }\n}\n"],
5
- "mappings": ";;;;;;;AAIA,SAASA,aAAa;AAEtB,SAASC,QAAQC,cAA0B;AAC3C,SAAuBC,gBAAgB;AACvC,SAASC,iBAAiB;AAC1B,SAASC,WAAW;AACpB,SAASC,YAAYC,YAAY;;AAS1B,IAAMC,mBAAN,cAA+BC,SAAAA;EAKpCC,YAA6BC,SAAiB;AAC5C,UAAK;SADsBA,UAAAA;SAJZC,sBAAsB,IAAIC,WAAq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,GAAGmD,KAAK,GAAGA,KAAK;AAC/C,YAAMC,aACJf,QAAQO,OAAO,CAACpE,YAAYA,QAAQsE,OAAO,EAAE1D,KAAK,CAACZ,YAAYA,QAAQc,OAAOxB,WAAWqF,CAAAA,EAAG3E,QAAQc,EAAE,KAAK;AAC7G,UAAI8D,YAAY;AACd,cAAMC,eAAevF,WAAWwF,OAAOH,GAAG,CAAA,EAAG,CAAA;AAC7C,cAAME,aAAahF,eAAeY,QAAAA;AAClCjB,gBAAQgF,KAAKK,aAAa7E,OAAO;MACnC;IACF;AAEA,QAAIR,QAAQgC,SAAS,GAAG;AACtBtB,MAAAA,KAAI+C,KAAK,WAAW,OAAO;QACzBwB,UAAU/E,MAAMS;QAChBoB,UAAU/B,QAAQwC,IAAI,CAAChC,YAAYA,QAAQM,QAAQ;MACrD,IAAA;;;;;;AAEA,WAAKd,QAAQkF,KAAK;QAAEhF;QAAO6B,UAAU/B;MAAQ,CAAA;IAC/C;EACF;EAEQG,aAAaD,OAAcqF,WAAuE;AACxG,UAAMC,mBAAmB,KAAK9F,oBAAoByB,IAAIjB,MAAMS,GAAG,KAAK,CAAA;AACpE,WAAO6E,iBAAiBZ,OAAOW,SAAAA,EAAW/C,IAAI,CAAChC,YAAYA,QAAQA,OAAO;EAC5E;AACF;",
6
- "names": ["Event", "create", "Filter", "Resource", "PublicKey", "log", "ComplexMap", "diff", "FunctionRegistry", "Resource", "constructor", "_client", "_functionBySpaceKey", "ComplexMap", "PublicKey", "hash", "registered", "Event", "getFunctions", "space", "get", "key", "getUniqueByUri", "uniqueByUri", "values", "flatMap", "defs", "reduce", "acc", "v", "set", "uri", "Map", "register", "functions", "log", "length", "db", "graph", "schemaRegistry", "hasSchema", "FunctionDef", "addSchema", "objects", "existing", "query", "Filter", "schema", "run", "added", "diff", "a", "b", "forEach", "def", "add", "create", "flush", "indexes", "updates", "_open", "info", "spacesSubscription", "spaces", "subscribe", "has", "waitUntilReady", "_ctx", "disposed", "onDispose", "push", "emit", "unsubscribe", "_close", "_", "clear", "debounce", "UpdateScheduler", "Filter", "createSubscription", "log", "createSubscriptionTrigger", "ctx", "space", "spec", "callback", "objectIds", "Set", "task", "size", "objects", "Array", "from", "clear", "maxFrequency", "subscriptions", "subscription", "added", "updated", "sizeBefore", "object", "add", "id", "info", "length", "trigger", "push", "unsubscribe", "filter", "options", "deep", "delay", "update", "query", "db", "typename", "type", "props", "subscribe", "onDispose", "forEach", "CronJob", "DeferredTask", "log", "createTimerTrigger", "ctx", "space", "spec", "callback", "task", "last", "run", "job", "from", "cronTime", "cron", "runOnInit", "onTick", "now", "Date", "delta", "info", "key", "truncate", "count", "schedule", "start", "onDispose", "stop", "sleep", "Trigger", "log", "createWebsocketTrigger", "ctx", "space", "spec", "callback", "options", "retryDelay", "maxAttempts", "url", "init", "wasOpen", "ws", "attempt", "open", "createWebSocket", "Object", "assign", "onopen", "info", "send", "TextEncoder", "encode", "JSON", "stringify", "wake", "onclose", "event", "code", "disposed", "setTimeout", "onerror", "catch", "error", "Error", "onmessage", "data", "parse", "text", "TextDecoder", "decode", "err", "isOpen", "wait", "Math", "pow", "warn", "onDispose", "close", "createNodeWebSocket", "importESM", "Function", "default", "WebSocket", "globalThis", "Event", "create", "Filter", "getMeta", "Context", "Resource", "compareForeignKeys", "ECHO_ATTR_META", "foreignKey", "invariant", "PublicKey", "log", "ComplexMap", "diff", "triggerFactory", "subscription", "createSubscriptionTrigger", "timer", "createTimerTrigger", "webhook", "websocket", "createWebsocketTrigger", "TriggerRegistry", "Resource", "constructor", "_client", "_options", "_triggersBySpaceKey", "ComplexMap", "PublicKey", "hash", "registered", "Event", "removed", "getActiveTriggers", "space", "_getTriggers", "t", "activationCtx", "getInactiveTriggers", "activate", "trigger", "callback", "log", "key", "Context", "name", "function", "_ctx", "onDispose", "dispose", "registeredTrigger", "get", "find", "reg", "id", "invariant", "options", "spec", "type", "createTrigger", "err", "register", "manifest", "triggers", "length", "db", "graph", "schemaRegistry", "hasSchema", "FunctionTrigger", "addSchema", "manifestTriggers", "map", "keys", "ECHO_ATTR_META", "foreignKey", "join", "create", "objects", "existing", "query", "Filter", "schema", "run", "added", "diff", "compareForeignKeys", "forEach", "add", "info", "meta", "getMeta", "flush", "_open", "spaceListSubscription", "spaces", "subscribe", "has", "set", "waitUntilReady", "disposed", "current", "_handleRemovedTriggers", "_handleNewTriggers", "unsubscribe", "_close", "_", "clear", "filter", "candidate", "enabled", "newRegisteredTriggers", "push", "spaceKey", "emit", "i", "wasRemoved", "unregistered", "splice", "predicate", "allSpaceTriggers"]
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../src/types.ts"],
4
- "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { RawObject, S, TypedObject } from '@dxos/echo-schema';\n\n/**\n * Type discriminator for TriggerSpec.\n * Every spec has a type field of type FunctionTriggerType that we can use to understand which\n * type we're working with.\n * https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions\n */\nexport type FunctionTriggerType = 'subscription' | 'timer' | 'webhook' | 'websocket';\n\nconst TimerTriggerSchema = S.Struct({\n type: S.Literal('timer'),\n cron: S.String,\n}).pipe(S.mutable);\n\nexport type TimerTrigger = S.Schema.Type<typeof TimerTriggerSchema>;\n\nconst WebhookTriggerSchema = S.Struct({\n type: S.Literal('webhook'),\n method: S.String,\n // Assigned port.\n port: S.optional(S.Number),\n}).pipe(S.mutable);\n\nexport type WebhookTrigger = S.Schema.Type<typeof WebhookTriggerSchema>;\n\nconst WebsocketTriggerSchema = S.Struct({\n type: S.Literal('websocket'),\n url: S.String,\n init: S.optional(S.Record({ key: S.String, value: S.Any })),\n}).pipe(S.mutable);\n\nexport type WebsocketTrigger = S.Schema.Type<typeof WebsocketTriggerSchema>;\n\nconst QuerySchema = S.Struct({\n type: S.String,\n props: S.optional(S.Record({ key: S.String, value: S.Any })),\n});\n\nconst SubscriptionTriggerSchema = S.Struct({\n type: S.Literal('subscription'),\n // TODO(burdon): Define query DSL (from ECHO). Reconcile with Table.Query.\n filter: S.Array(QuerySchema),\n options: S.optional(\n S.Struct({\n // Watch changes to object (not just creation).\n deep: S.optional(S.Boolean),\n // Debounce changes (delay in ms).\n delay: S.optional(S.Number),\n }),\n ),\n}).pipe(S.mutable);\n\nexport type SubscriptionTrigger = S.Schema.Type<typeof SubscriptionTriggerSchema>;\n\nconst TriggerSpecSchema = S.Union(\n TimerTriggerSchema,\n WebhookTriggerSchema,\n WebsocketTriggerSchema,\n SubscriptionTriggerSchema,\n);\n\nexport type TriggerSpec = TimerTrigger | WebhookTrigger | WebsocketTrigger | SubscriptionTrigger;\n\n/**\n * Function definition.\n */\nexport class FunctionDef extends TypedObject({\n typename: 'dxos.org/type/FunctionDef',\n version: '0.1.0',\n})({\n uri: S.String,\n description: S.optional(S.String),\n route: S.String,\n handler: S.String,\n}) {}\n\n/**\n * Function trigger.\n */\nexport class FunctionTrigger extends TypedObject({\n typename: 'dxos.org/type/FunctionTrigger',\n version: '0.1.0',\n})({\n name: S.optional(S.String),\n enabled: S.optional(S.Boolean),\n function: S.String.pipe(S.annotations({ description: 'Function URI.' })),\n // The `meta` property is merged into the event data passed to the function.\n meta: S.optional(S.mutable(S.Record({ key: S.String, value: S.Any }))),\n spec: TriggerSpecSchema,\n}) {}\n\n/**\n * Function manifest file.\n */\nexport const FunctionManifestSchema = S.Struct({\n functions: S.optional(S.mutable(S.Array(RawObject(FunctionDef)))),\n triggers: S.optional(S.mutable(S.Array(RawObject(FunctionTrigger)))),\n});\n\nexport type FunctionManifest = S.Schema.Type<typeof FunctionManifestSchema>;\n\n// TODO(burdon): Standards?\nexport const FUNCTION_SCHEMA = [FunctionDef, FunctionTrigger];\n"],
5
- "mappings": ";;;;;;;;;AAIA,SAASA,WAAWC,GAAGC,mBAAmB;AAU1C,IAAMC,qBAAqBC,EAAEC,OAAO;EAClCC,MAAMF,EAAEG,QAAQ,OAAA;EAChBC,MAAMJ,EAAEK;AACV,CAAA,EAAGC,KAAKN,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AAY;EAC/CC,UAAU;EACVC,SAAS;AACX,CAAA,EAAG;EACDM,MAAMxC,EAAEW,SAASX,EAAEK,MAAM;EACzBoC,SAASzC,EAAEW,SAASX,EAAE2B,OAAO;EAC7Be,UAAU1C,EAAEK,OAAOC,KAAKN,EAAE2C,YAAY;IAAEP,aAAa;EAAgB,CAAA,CAAA;;EAErEQ,MAAM5C,EAAEW,SAASX,EAAEO,QAAQP,EAAEgB,OAAO;IAAEC,KAAKjB,EAAEK;IAAQa,OAAOlB,EAAEmB;EAAI,CAAA,CAAA,CAAA;EAClE0B,MAAMhB;AACR,CAAA,EAAA;AAAI;AAKG,IAAMiB,yBAAyB9C,EAAEC,OAAO;EAC7C8C,WAAW/C,EAAEW,SAASX,EAAEO,QAAQP,EAAEwB,MAAMwB,UAAUjB,WAAAA,CAAAA,CAAAA,CAAAA;EAClDkB,UAAUjD,EAAEW,SAASX,EAAEO,QAAQP,EAAEwB,MAAMwB,UAAUT,eAAAA,CAAAA,CAAAA,CAAAA;AACnD,CAAA;AAKO,IAAMW,kBAAkB;EAACnB;EAAaQ;;",
6
- "names": ["RawObject", "S", "TypedObject", "TimerTriggerSchema", "S", "Struct", "type", "Literal", "cron", "String", "pipe", "mutable", "WebhookTriggerSchema", "method", "port", "optional", "Number", "WebsocketTriggerSchema", "url", "init", "Record", "key", "value", "Any", "QuerySchema", "props", "SubscriptionTriggerSchema", "filter", "Array", "options", "deep", "Boolean", "delay", "TriggerSpecSchema", "Union", "FunctionDef", "TypedObject", "typename", "version", "uri", "description", "route", "handler", "FunctionTrigger", "name", "enabled", "function", "annotations", "meta", "spec", "FunctionManifestSchema", "functions", "RawObject", "triggers", "FUNCTION_SCHEMA"]
7
- }