@rimori/client 1.0.2 → 1.0.4

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 (135) hide show
  1. package/README.md +51 -0
  2. package/dist/components/CRUDModal.js +0 -1
  3. package/dist/components/ai/Assistant.d.ts +9 -0
  4. package/dist/components/ai/Assistant.js +59 -0
  5. package/dist/components/ai/Avatar.d.ts +11 -0
  6. package/dist/components/ai/Avatar.js +39 -0
  7. package/dist/components/ai/EmbeddedAssistent/AudioInputField.d.ts +7 -0
  8. package/dist/components/ai/EmbeddedAssistent/AudioInputField.js +38 -0
  9. package/dist/components/ai/EmbeddedAssistent/CircleAudioAvatar.d.ts +7 -0
  10. package/dist/components/ai/EmbeddedAssistent/CircleAudioAvatar.js +59 -0
  11. package/dist/components/ai/EmbeddedAssistent/TTS/MessageSender.d.ts +19 -0
  12. package/dist/components/ai/EmbeddedAssistent/TTS/MessageSender.js +86 -0
  13. package/dist/components/ai/EmbeddedAssistent/TTS/Player.d.ts +25 -0
  14. package/dist/components/ai/EmbeddedAssistent/TTS/Player.js +180 -0
  15. package/dist/components/ai/EmbeddedAssistent/VoiceRecoder.d.ts +7 -0
  16. package/dist/components/ai/EmbeddedAssistent/VoiceRecoder.js +45 -0
  17. package/dist/components/ai/utils.d.ts +6 -0
  18. package/dist/components/ai/utils.js +14 -0
  19. package/dist/components/audio/Playbutton.js +4 -5
  20. package/dist/components/avatar/Assistant.d.ts +9 -0
  21. package/dist/components/avatar/Assistant.js +59 -0
  22. package/dist/components/avatar/Avatar.d.ts +12 -0
  23. package/dist/components/avatar/Avatar.js +42 -0
  24. package/dist/components/avatar/EmbeddedAssistent/AudioInputField.d.ts +7 -0
  25. package/dist/components/avatar/EmbeddedAssistent/AudioInputField.js +38 -0
  26. package/dist/components/avatar/EmbeddedAssistent/CircleAudioAvatar.d.ts +7 -0
  27. package/dist/components/avatar/EmbeddedAssistent/CircleAudioAvatar.js +59 -0
  28. package/dist/components/avatar/EmbeddedAssistent/TTS/MessageSender.d.ts +19 -0
  29. package/dist/components/avatar/EmbeddedAssistent/TTS/MessageSender.js +84 -0
  30. package/dist/components/avatar/EmbeddedAssistent/TTS/Player.d.ts +25 -0
  31. package/dist/components/avatar/EmbeddedAssistent/TTS/Player.js +180 -0
  32. package/dist/components/avatar/EmbeddedAssistent/VoiceRecoder.d.ts +7 -0
  33. package/dist/components/avatar/EmbeddedAssistent/VoiceRecoder.js +45 -0
  34. package/dist/components/avatar/utils.d.ts +6 -0
  35. package/dist/components/avatar/utils.js +14 -0
  36. package/dist/components.d.ts +9 -0
  37. package/dist/components.js +10 -0
  38. package/dist/controller/AIController.d.ts +4 -3
  39. package/dist/controller/AIController.js +32 -8
  40. package/dist/controller/ObjectController.d.ts +2 -2
  41. package/dist/controller/ObjectController.js +4 -5
  42. package/dist/controller/SettingsController.d.ts +3 -1
  43. package/dist/controller/SettingsController.js +9 -0
  44. package/dist/controller/SharedContentController.js +6 -6
  45. package/dist/controller/SidePluginController.d.ts +14 -0
  46. package/dist/{plugin/VoiceController.js → controller/SidePluginController.js} +18 -15
  47. package/dist/controller/VoiceController.js +1 -1
  48. package/dist/core.d.ts +9 -0
  49. package/dist/core.js +10 -0
  50. package/dist/hooks/UseChatHook.js +2 -2
  51. package/dist/index.d.ts +3 -2
  52. package/dist/index.js +4 -2
  53. package/dist/plugin/PluginController.d.ts +4 -12
  54. package/dist/plugin/PluginController.js +43 -70
  55. package/dist/plugin/RimoriClient.d.ts +87 -27
  56. package/dist/plugin/RimoriClient.js +101 -67
  57. package/dist/plugin/fromRimori/EventBus.d.ts +98 -0
  58. package/dist/plugin/fromRimori/EventBus.js +240 -0
  59. package/dist/providers/PluginProvider.d.ts +1 -0
  60. package/dist/providers/PluginProvider.js +64 -12
  61. package/dist/worker/WorkerSetup.d.ts +6 -0
  62. package/dist/worker/WorkerSetup.js +79 -0
  63. package/package.json +16 -3
  64. package/src/components/CRUDModal.tsx +1 -3
  65. package/src/components/ai/Assistant.tsx +96 -0
  66. package/src/components/ai/Avatar.tsx +61 -0
  67. package/src/components/ai/EmbeddedAssistent/AudioInputField.tsx +64 -0
  68. package/src/components/ai/EmbeddedAssistent/CircleAudioAvatar.tsx +75 -0
  69. package/src/components/ai/EmbeddedAssistent/TTS/MessageSender.ts +91 -0
  70. package/src/components/ai/EmbeddedAssistent/TTS/Player.ts +192 -0
  71. package/src/components/ai/EmbeddedAssistent/VoiceRecoder.tsx +56 -0
  72. package/src/components/ai/utils.ts +23 -0
  73. package/src/components/audio/Playbutton.tsx +4 -5
  74. package/src/components.ts +10 -0
  75. package/src/controller/AIController.ts +84 -60
  76. package/src/controller/ObjectController.ts +4 -6
  77. package/src/controller/SettingsController.ts +10 -1
  78. package/src/controller/SharedContentController.ts +6 -6
  79. package/src/controller/SidePluginController.ts +36 -0
  80. package/src/controller/VoiceController.ts +1 -1
  81. package/src/core.ts +10 -0
  82. package/src/hooks/UseChatHook.ts +2 -2
  83. package/src/index.ts +4 -2
  84. package/src/plugin/PluginController.ts +46 -76
  85. package/src/plugin/RimoriClient.ts +151 -76
  86. package/src/plugin/fromRimori/EventBus.ts +301 -0
  87. package/src/plugin/fromRimori/readme.md +2 -0
  88. package/src/providers/PluginProvider.tsx +70 -14
  89. package/src/worker/WorkerSetup.ts +80 -0
  90. package/dist/CRUDModal.d.ts +0 -16
  91. package/dist/CRUDModal.js +0 -31
  92. package/dist/MarkdownEditor.d.ts +0 -8
  93. package/dist/MarkdownEditor.js +0 -46
  94. package/dist/audio/Playbutton.d.ts +0 -14
  95. package/dist/audio/Playbutton.js +0 -73
  96. package/dist/components/hooks/UseChatHook.d.ts +0 -15
  97. package/dist/components/hooks/UseChatHook.js +0 -21
  98. package/dist/plugin/AIController copy.d.ts +0 -22
  99. package/dist/plugin/AIController copy.js +0 -68
  100. package/dist/plugin/AIController.d.ts +0 -22
  101. package/dist/plugin/AIController.js +0 -68
  102. package/dist/plugin/ObjectController.d.ts +0 -34
  103. package/dist/plugin/ObjectController.js +0 -77
  104. package/dist/plugin/SettingController.d.ts +0 -13
  105. package/dist/plugin/SettingController.js +0 -55
  106. package/dist/plugin/VoiceController.d.ts +0 -2
  107. package/dist/providers/EventEmitter.d.ts +0 -11
  108. package/dist/providers/EventEmitter.js +0 -41
  109. package/dist/providers/EventEmitterContext.d.ts +0 -6
  110. package/dist/providers/EventEmitterContext.js +0 -19
  111. package/dist/utils/DifficultyConverter.d.ts +0 -3
  112. package/dist/utils/DifficultyConverter.js +0 -7
  113. package/dist/utils/constants.d.ts +0 -4
  114. package/dist/utils/constants.js +0 -12
  115. package/dist/utils/plugin/Client.d.ts +0 -72
  116. package/dist/utils/plugin/Client.js +0 -118
  117. package/dist/utils/plugin/PluginController.d.ts +0 -36
  118. package/dist/utils/plugin/PluginController.js +0 -119
  119. package/dist/utils/plugin/PluginUtils.d.ts +0 -2
  120. package/dist/utils/plugin/PluginUtils.js +0 -23
  121. package/dist/utils/plugin/RimoriClient.d.ts +0 -72
  122. package/dist/utils/plugin/RimoriClient.js +0 -118
  123. package/dist/utils/plugin/ThemeSetter.d.ts +0 -1
  124. package/dist/utils/plugin/ThemeSetter.js +0 -13
  125. package/dist/utils/plugin/WhereClauseBuilder.d.ts +0 -24
  126. package/dist/utils/plugin/WhereClauseBuilder.js +0 -79
  127. package/dist/utils/plugin/providers/EventEmitter.d.ts +0 -11
  128. package/dist/utils/plugin/providers/EventEmitter.js +0 -41
  129. package/dist/utils/plugin/providers/EventEmitterContext.d.ts +0 -6
  130. package/dist/utils/plugin/providers/EventEmitterContext.js +0 -19
  131. package/dist/utils/plugin/providers/PluginProvider.d.ts +0 -8
  132. package/dist/utils/plugin/providers/PluginProvider.js +0 -49
  133. package/src/providers/EventEmitter.ts +0 -48
  134. package/src/providers/EventEmitterContext.tsx +0 -27
  135. package/src/utils/constants.ts +0 -18
@@ -1,24 +1,95 @@
1
1
  import { PluginController } from "./PluginController";
2
2
  import { SupabaseClient } from "@supabase/supabase-js";
3
+ import { EventBusMessage, EventPayload } from "./fromRimori/EventBus";
3
4
  import { GenericSchema } from "@supabase/supabase-js/dist/module/lib/types";
4
5
  import { PostgrestQueryBuilder, PostgrestFilterBuilder } from "@supabase/postgrest-js";
5
6
  import { BasicAssignment } from "../controller/SharedContentController";
6
7
  import { Message, Tool, OnLLMResponse } from "../controller/AIController";
7
8
  import { ObjectRequest } from "../controller/ObjectController";
8
- export declare class RimoriClient {
9
- private static instance;
10
- private superbase;
11
- private plugin;
9
+ import { Plugin } from "../controller/SidePluginController";
10
+ import { UserInfo } from "../controller/SettingsController";
11
+ import { EventHandler } from "./fromRimori/EventBus";
12
+ interface Db {
13
+ from: {
14
+ <TableName extends string & keyof GenericSchema['Tables'], Table extends GenericSchema['Tables'][TableName]>(relation: TableName): PostgrestQueryBuilder<GenericSchema, Table, TableName>;
15
+ <ViewName extends string & keyof GenericSchema['Views'], View extends GenericSchema['Views'][ViewName]>(relation: ViewName): PostgrestQueryBuilder<GenericSchema, View, ViewName>;
16
+ };
17
+ rpc: <Fn extends GenericSchema['Functions'][string], FnName extends string & keyof GenericSchema['Functions']>(functionName: FnName, args?: Fn["Args"], options?: {
18
+ head?: boolean;
19
+ get?: boolean;
20
+ count?: "exact" | "planned" | "estimated";
21
+ }) => PostgrestFilterBuilder<GenericSchema, Fn["Returns"] extends any[] ? Fn["Returns"][number] extends Record<string, unknown> ? Fn["Returns"][number] : never : never, Fn["Returns"], string, null>;
12
22
  functions: SupabaseClient["functions"];
13
23
  storage: SupabaseClient["storage"];
24
+ }
25
+ interface PluginInterface {
14
26
  pluginId: string;
15
27
  tablePrefix: string;
28
+ setSettings: (settings: any) => Promise<void>;
29
+ /**
30
+ * Get the settings for the plugin. T can be any type of settings, UserSettings or SystemSettings.
31
+ * @param defaultSettings The default settings to use if no settings are found.
32
+ * @param genericSettings The type of settings to get.
33
+ * @returns The settings for the plugin.
34
+ */
35
+ getSettings: <T extends object>(defaultSettings: T) => Promise<T>;
36
+ /**
37
+ * Fetches all installed plugins.
38
+ * @returns A promise that resolves to an array of plugins
39
+ */
40
+ getInstalled: () => Promise<Plugin[]>;
41
+ getUserInfo: () => Promise<UserInfo>;
42
+ }
43
+ export declare class RimoriClient {
44
+ private static instance;
45
+ private superbase;
46
+ private pluginController;
16
47
  private settingsController;
17
48
  private sharedContentController;
49
+ private supabaseUrl;
50
+ db: Db;
51
+ plugin: PluginInterface;
18
52
  private constructor();
53
+ event: {
54
+ /**
55
+ * Emit an event to Rimori or a plugin.
56
+ * The topic schema is:
57
+ * {pluginId}.{eventId}
58
+ * Check out the event bus documentation for more information.
59
+ * For triggering events from Rimori like context menu actions use the "global" keyword.
60
+ * @param topic The topic to emit the event on.
61
+ * @param data The data to emit.
62
+ * @param eventId The event id.
63
+ */
64
+ emit: (topic: string, data: any, eventId?: number) => void;
65
+ /**
66
+ * Request an event.
67
+ * @param topic The topic to request the event on.
68
+ * @param data The data to request.
69
+ * @returns The response from the event.
70
+ */
71
+ request: <T>(topic: string, data?: any) => Promise<EventBusMessage<T>>;
72
+ /**
73
+ * Subscribe to an event.
74
+ * @param topic The topic to subscribe to.
75
+ * @param callback The callback to call when the event is emitted.
76
+ */
77
+ on: <T = EventPayload>(topic: string, callback: EventHandler<T>) => void;
78
+ /**
79
+ * Subscribe to an event once.
80
+ * @param topic The topic to subscribe to.
81
+ * @param callback The callback to call when the event is emitted.
82
+ */
83
+ once: <T = EventPayload>(topic: string, callback: EventHandler<T>) => void;
84
+ /**
85
+ * Respond to an event.
86
+ * @param topic The topic to respond to.
87
+ * @param data The data to respond with.
88
+ */
89
+ respond: <T = EventPayload>(topic: string, data: EventPayload | ((data: EventBusMessage<T>) => EventPayload | Promise<EventPayload>)) => void;
90
+ };
19
91
  static getInstance(pluginController: PluginController): Promise<RimoriClient>;
20
- from<TableName extends string & keyof GenericSchema['Tables'], Table extends GenericSchema['Tables'][TableName]>(relation: TableName): PostgrestQueryBuilder<GenericSchema, Table, TableName>;
21
- from<ViewName extends string & keyof GenericSchema['Views'], View extends GenericSchema['Views'][ViewName]>(relation: ViewName): PostgrestQueryBuilder<GenericSchema, View, ViewName>;
92
+ private from;
22
93
  /**
23
94
  * Perform a function call.
24
95
  *
@@ -42,28 +113,15 @@ export declare class RimoriClient {
42
113
  * `"estimated"`: Uses exact count for low numbers and planned count for high
43
114
  * numbers.
44
115
  */
45
- rpc<Fn extends GenericSchema['Functions'][string], FnName extends string & keyof GenericSchema['Functions']>(functionName: FnName, args?: Fn['Args'], options?: {
46
- head?: boolean;
47
- get?: boolean;
48
- count?: 'exact' | 'planned' | 'estimated';
49
- }): PostgrestFilterBuilder<GenericSchema, Fn['Returns'] extends any[] ? Fn['Returns'][number] extends Record<string, unknown> ? Fn['Returns'][number] : never : never, Fn['Returns'], string, null>;
116
+ private rpc;
50
117
  private getTableName;
51
- subscribe(eventName: string, callback: (_id: number, data: any) => void): void;
52
- request<T>(eventName: string, data?: any): Promise<T>;
53
- emit(eventName: string, data: any): void;
54
- /**
55
- * Get the settings for the plugin. T can be any type of settings, UserSettings or SystemSettings.
56
- * @param defaultSettings The default settings to use if no settings are found.
57
- * @param genericSettings The type of settings to get.
58
- * @returns The settings for the plugin.
59
- */
60
- getSettings<T extends object>(defaultSettings: T, genericSettings?: "user" | "system"): Promise<T>;
61
- setSettings(settings: any, genericSettings?: "user" | "system"): Promise<void>;
62
- getAIResponse(messages: Message[], tools?: Tool[]): Promise<string>;
63
- getAIResponseStream(messages: Message[], onMessage: OnLLMResponse, tools?: Tool[]): Promise<void>;
64
- getVoiceResponse(text: string, voice?: string, speed?: number, language?: string): Promise<Blob>;
65
- getVoiceToTextResponse(file: Blob): Promise<string>;
66
- generateObject(request: ObjectRequest): Promise<any>;
118
+ llm: {
119
+ getText: (messages: Message[], tools?: Tool[]) => Promise<string>;
120
+ getSteamedText: (messages: Message[], onMessage: OnLLMResponse, tools?: Tool[]) => Promise<void>;
121
+ getVoice: (text: string, voice?: string, speed?: number, language?: string) => Promise<Blob>;
122
+ getTextFromVoice: (file: Blob) => Promise<string>;
123
+ getObject: (request: ObjectRequest) => Promise<any>;
124
+ };
67
125
  /**
68
126
  * Fetch new shared content.
69
127
  * @param type The type of shared content to fetch. E.g. assignments, exercises, etc.
@@ -88,4 +146,6 @@ export declare class RimoriClient {
88
146
  * @param assignmentId The id of the shared content item to complete.
89
147
  */
90
148
  completeSharedContent(type: string, assignmentId: string): Promise<void>;
149
+ triggerSidebarAction(pluginId: string, actionKey: string, text?: string): void;
91
150
  }
151
+ export {};
@@ -12,28 +12,110 @@ import { getSTTResponse, getTTSResponse } from "../controller/VoiceController";
12
12
  import { SharedContentController } from "../controller/SharedContentController";
13
13
  import { streamChatGPT, generateText } from "../controller/AIController";
14
14
  import { generateObject as generateObjectFunction } from "../controller/ObjectController";
15
+ import { getPlugins } from "../controller/SidePluginController";
16
+ import { EventBus } from "./fromRimori/EventBus";
15
17
  export class RimoriClient {
16
18
  constructor(options) {
19
+ this.event = {
20
+ /**
21
+ * Emit an event to Rimori or a plugin.
22
+ * The topic schema is:
23
+ * {pluginId}.{eventId}
24
+ * Check out the event bus documentation for more information.
25
+ * For triggering events from Rimori like context menu actions use the "global" keyword.
26
+ * @param topic The topic to emit the event on.
27
+ * @param data The data to emit.
28
+ * @param eventId The event id.
29
+ */
30
+ emit: (topic, data, eventId) => {
31
+ const globalTopic = this.pluginController.getGlobalEventTopic(topic);
32
+ EventBus.emit(this.plugin.pluginId, globalTopic, data, eventId);
33
+ },
34
+ /**
35
+ * Request an event.
36
+ * @param topic The topic to request the event on.
37
+ * @param data The data to request.
38
+ * @returns The response from the event.
39
+ */
40
+ request: (topic, data) => {
41
+ const globalTopic = this.pluginController.getGlobalEventTopic(topic);
42
+ return EventBus.request(this.plugin.pluginId, globalTopic, data);
43
+ },
44
+ /**
45
+ * Subscribe to an event.
46
+ * @param topic The topic to subscribe to.
47
+ * @param callback The callback to call when the event is emitted.
48
+ */
49
+ on: (topic, callback) => {
50
+ EventBus.on(this.pluginController.getGlobalEventTopic(topic), callback);
51
+ },
52
+ /**
53
+ * Subscribe to an event once.
54
+ * @param topic The topic to subscribe to.
55
+ * @param callback The callback to call when the event is emitted.
56
+ */
57
+ once: (topic, callback) => {
58
+ EventBus.once(this.pluginController.getGlobalEventTopic(topic), callback);
59
+ },
60
+ /**
61
+ * Respond to an event.
62
+ * @param topic The topic to respond to.
63
+ * @param data The data to respond with.
64
+ */
65
+ respond: (topic, data) => {
66
+ EventBus.respond(this.plugin.pluginId, this.pluginController.getGlobalEventTopic(topic), data);
67
+ }
68
+ };
69
+ this.llm = {
70
+ getText: (messages, tools) => __awaiter(this, void 0, void 0, function* () {
71
+ const token = yield this.pluginController.getToken();
72
+ return generateText(this.supabaseUrl, messages, tools || [], token).then(response => response.messages[0].content[0].text);
73
+ }),
74
+ getSteamedText: (messages, onMessage, tools) => __awaiter(this, void 0, void 0, function* () {
75
+ const token = yield this.pluginController.getToken();
76
+ streamChatGPT(this.supabaseUrl, messages, tools || [], onMessage, token);
77
+ }),
78
+ getVoice: (text_1, ...args_1) => __awaiter(this, [text_1, ...args_1], void 0, function* (text, voice = "alloy", speed = 1, language) {
79
+ return getTTSResponse(this.pluginController.getSupabaseUrl(), { input: text, voice, speed, language }, yield this.pluginController.getToken());
80
+ }),
81
+ getTextFromVoice: (file) => {
82
+ return getSTTResponse(this.superbase, file);
83
+ },
84
+ getObject: (request) => __awaiter(this, void 0, void 0, function* () {
85
+ const token = yield this.pluginController.getToken();
86
+ return generateObjectFunction(this.pluginController.getSupabaseUrl(), request, token);
87
+ }),
88
+ // getSteamedObject: this.generateObjectStream,
89
+ };
17
90
  this.superbase = options.supabase;
18
- this.pluginId = options.pluginId;
19
- this.plugin = options.pluginController;
20
- this.tablePrefix = options.tablePrefix;
21
- this.storage = this.superbase.storage;
22
- this.functions = this.superbase.functions;
91
+ this.pluginController = options.pluginController;
23
92
  this.settingsController = new SettingsController(options.supabase, options.pluginId);
24
93
  this.sharedContentController = new SharedContentController(this);
94
+ this.supabaseUrl = this.pluginController.getSupabaseUrl();
25
95
  this.rpc = this.rpc.bind(this);
26
96
  this.from = this.from.bind(this);
27
- this.emit = this.emit.bind(this);
28
- this.request = this.request.bind(this);
29
- this.subscribe = this.subscribe.bind(this);
30
- this.getSettings = this.getSettings.bind(this);
31
- this.setSettings = this.setSettings.bind(this);
32
- this.getAIResponse = this.getAIResponse.bind(this);
33
- this.generateObject = this.generateObject.bind(this);
34
- this.getVoiceResponse = this.getVoiceResponse.bind(this);
35
- this.getAIResponseStream = this.getAIResponseStream.bind(this);
36
- this.getVoiceToTextResponse = this.getVoiceToTextResponse.bind(this);
97
+ this.db = {
98
+ rpc: this.rpc,
99
+ from: this.from,
100
+ storage: this.superbase.storage,
101
+ functions: this.superbase.functions,
102
+ };
103
+ this.plugin = {
104
+ pluginId: options.pluginId,
105
+ tablePrefix: options.tablePrefix,
106
+ setSettings: (settings) => __awaiter(this, void 0, void 0, function* () {
107
+ yield this.settingsController.setSettings(settings);
108
+ }),
109
+ getSettings: (defaultSettings) => __awaiter(this, void 0, void 0, function* () {
110
+ return yield this.settingsController.getSettings(defaultSettings);
111
+ }),
112
+ getInstalled: () => __awaiter(this, void 0, void 0, function* () {
113
+ return getPlugins(this.superbase);
114
+ }),
115
+ getUserInfo: () => __awaiter(this, void 0, void 0, function* () {
116
+ return this.settingsController.getUserInfo();
117
+ })
118
+ };
37
119
  }
38
120
  static getInstance(pluginController) {
39
121
  return __awaiter(this, void 0, void 0, function* () {
@@ -74,58 +156,7 @@ export class RimoriClient {
74
156
  return this.superbase.rpc(this.getTableName(functionName), args, options);
75
157
  }
76
158
  getTableName(type) {
77
- return this.tablePrefix + "_" + type;
78
- }
79
- subscribe(eventName, callback) {
80
- this.plugin.subscribe(eventName, callback);
81
- }
82
- request(eventName, data) {
83
- return this.plugin.request(eventName, data);
84
- }
85
- emit(eventName, data) {
86
- this.plugin.emit(eventName, data);
87
- }
88
- /**
89
- * Get the settings for the plugin. T can be any type of settings, UserSettings or SystemSettings.
90
- * @param defaultSettings The default settings to use if no settings are found.
91
- * @param genericSettings The type of settings to get.
92
- * @returns The settings for the plugin.
93
- */
94
- getSettings(defaultSettings, genericSettings) {
95
- return __awaiter(this, void 0, void 0, function* () {
96
- return this.settingsController.getSettings(defaultSettings, genericSettings);
97
- });
98
- }
99
- setSettings(settings, genericSettings) {
100
- return __awaiter(this, void 0, void 0, function* () {
101
- yield this.settingsController.setSettings(settings, genericSettings);
102
- });
103
- }
104
- getAIResponse(messages, tools) {
105
- return __awaiter(this, void 0, void 0, function* () {
106
- const token = yield this.plugin.getToken();
107
- return generateText(messages, tools || [], token).then(response => response.messages[0].content[0].text);
108
- });
109
- }
110
- getAIResponseStream(messages, onMessage, tools) {
111
- return __awaiter(this, void 0, void 0, function* () {
112
- const token = yield this.plugin.getToken();
113
- streamChatGPT(messages, tools || [], onMessage, token);
114
- });
115
- }
116
- getVoiceResponse(text_1) {
117
- return __awaiter(this, arguments, void 0, function* (text, voice = "alloy", speed = 1, language) {
118
- return getTTSResponse(this.plugin.getSupabaseUrl(), { input: text, voice, speed, language }, yield this.plugin.getToken());
119
- });
120
- }
121
- getVoiceToTextResponse(file) {
122
- return getSTTResponse(this.superbase, file);
123
- }
124
- generateObject(request) {
125
- return __awaiter(this, void 0, void 0, function* () {
126
- const token = yield this.plugin.getToken();
127
- return generateObjectFunction(request, token);
128
- });
159
+ return this.plugin.tablePrefix + "_" + type;
129
160
  }
130
161
  /**
131
162
  * Fetch new shared content.
@@ -160,4 +191,7 @@ export class RimoriClient {
160
191
  return this.sharedContentController.completeSharedContent(type, assignmentId);
161
192
  });
162
193
  }
194
+ triggerSidebarAction(pluginId, actionKey, text) {
195
+ this.event.emit("global.sidebar.triggerAction", { pluginId, actionKey, text });
196
+ }
163
197
  }
@@ -0,0 +1,98 @@
1
+ export type EventPayload = Record<string, any>;
2
+ /**
3
+ * Interface representing a message sent through the EventBus
4
+ *
5
+ * Debug capabilities:
6
+ * - System-wide debugging: Send an event to "global.system.requestDebug"
7
+ * Example: `EventBus.emit("yourPluginId", "global.system.requestDebug");`
8
+ */
9
+ export interface EventBusMessage<T = EventPayload> {
10
+ timestamp: string;
11
+ eventId: number;
12
+ sender: string;
13
+ topic: string;
14
+ data: T;
15
+ debug: boolean;
16
+ }
17
+ export type EventHandler<T = EventPayload> = (event: EventBusMessage<T>) => void | Promise<void>;
18
+ export declare class EventBusHandler {
19
+ private listeners;
20
+ private responseResolvers;
21
+ private static instance;
22
+ private debugEnabled;
23
+ private evName;
24
+ private constructor();
25
+ static getInstance(name?: string): EventBusHandler;
26
+ private createEvent;
27
+ /**
28
+ * Emits an event to the event bus. Can be a new event or a response to a request.
29
+ * @param sender - The sender of the event.
30
+ * @param topic - The topic of the event.
31
+ * @param data - The data of the event.
32
+ * @param eventId - The event id of the event.
33
+ *
34
+ * The topic format is: **pluginId.area.action**
35
+ *
36
+ * Example topics:
37
+ * - pl1234.card.requestHard
38
+ * - pl1234.card.requestNew
39
+ * - pl1234.card.requestAll
40
+ * - pl1234.card.create
41
+ * - pl1234.card.update
42
+ * - pl1234.card.delete
43
+ * - pl1234.card.triggerBackup
44
+ */
45
+ emit<T = EventPayload>(sender: string, topic: string, data?: T, eventId?: number): void;
46
+ private emitInternal;
47
+ /**
48
+ * Subscribes to an event on the event bus.
49
+ * @param topics - The topic of the event.
50
+ * @param handler - The handler to be called when the event is emitted.
51
+ * @param ignoreSender - The senders to ignore.
52
+ * @returns The ids of the listeners.
53
+ */
54
+ on<T = EventPayload>(topics: string | string[], handler: EventHandler<T>, ignoreSender?: string[]): string[];
55
+ /**
56
+ * Subscribes to an event, processes the data and emits a response on the event bus.
57
+ * @param sender - The sender of the event.
58
+ * @param topic - The topic of the event.
59
+ * @param handler - The handler to be called when the event is received. The handler returns the data to be emitted. Can be a static object or a function.
60
+ * @returns The ids of the listeners.
61
+ */
62
+ respond(sender: string, topic: string, handler: EventPayload | ((data: EventBusMessage) => EventPayload | Promise<EventPayload>)): string[];
63
+ /**
64
+ * Subscribes to an event on the event bus. The handler will be called once and then removed.
65
+ * @param topic - The topic of the event.
66
+ * @param handler - The handler to be called when the event is emitted.
67
+ */
68
+ once<T = EventPayload>(topic: string, handler: EventHandler<T>): void;
69
+ /**
70
+ * Unsubscribes from an event on the event bus.
71
+ * @param listenerIds - The ids of the listeners to unsubscribe from.
72
+ */
73
+ off(listenerIds: string | string[]): void;
74
+ private toArray;
75
+ /**
76
+ * Requests data from the event bus.
77
+ * @param sender - The sender of the event.
78
+ * @param topic - The topic of the event.
79
+ * @param data - The data of the event.
80
+ * @returns A promise that resolves to the event.
81
+ */
82
+ request<T = EventPayload>(sender: string, topic: string, data?: EventPayload): Promise<EventBusMessage<T>>;
83
+ /**
84
+ * Gets the matching handlers for an event.
85
+ * @param topic - The topic of the event.
86
+ * @returns A set of handlers that match the event type.
87
+ */
88
+ private getMatchingHandlers;
89
+ /**
90
+ * Validates the topic of an event.
91
+ * @param topic - The topic of the event.
92
+ * @returns True if the topic is valid, false otherwise.
93
+ */
94
+ private validateTopic;
95
+ private logIfDebug;
96
+ private logAndThrowError;
97
+ }
98
+ export declare const EventBus: EventBusHandler;
@@ -0,0 +1,240 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ export class EventBusHandler {
11
+ constructor() {
12
+ this.listeners = new Map();
13
+ this.responseResolvers = new Map();
14
+ this.debugEnabled = false;
15
+ this.evName = "";
16
+ //private constructor
17
+ }
18
+ static getInstance(name) {
19
+ if (!EventBusHandler.instance) {
20
+ EventBusHandler.instance = new EventBusHandler();
21
+ EventBusHandler.instance.on("global.system.requestDebug", () => {
22
+ EventBusHandler.instance.debugEnabled = true;
23
+ console.log(`[${EventBusHandler.instance.evName}] Debug mode enabled. Make sure debugging messages are enabled in the browser console.`);
24
+ });
25
+ }
26
+ if (name && EventBusHandler.instance.evName === "") {
27
+ EventBusHandler.instance.evName = name;
28
+ }
29
+ return EventBusHandler.instance;
30
+ }
31
+ createEvent(sender, topic, data, eventId) {
32
+ const generatedEventId = eventId || Math.floor(Math.random() * 10000000000);
33
+ return {
34
+ eventId: generatedEventId,
35
+ timestamp: new Date().toISOString(),
36
+ sender,
37
+ topic,
38
+ data,
39
+ debug: this.debugEnabled,
40
+ };
41
+ }
42
+ /**
43
+ * Emits an event to the event bus. Can be a new event or a response to a request.
44
+ * @param sender - The sender of the event.
45
+ * @param topic - The topic of the event.
46
+ * @param data - The data of the event.
47
+ * @param eventId - The event id of the event.
48
+ *
49
+ * The topic format is: **pluginId.area.action**
50
+ *
51
+ * Example topics:
52
+ * - pl1234.card.requestHard
53
+ * - pl1234.card.requestNew
54
+ * - pl1234.card.requestAll
55
+ * - pl1234.card.create
56
+ * - pl1234.card.update
57
+ * - pl1234.card.delete
58
+ * - pl1234.card.triggerBackup
59
+ */
60
+ emit(sender, topic, data, eventId) {
61
+ this.emitInternal(sender, topic, data || {}, eventId);
62
+ }
63
+ emitInternal(sender, topic, data, eventId, skipResponseTrigger = false) {
64
+ if (!this.validateTopic(topic)) {
65
+ this.logAndThrowError(false, `Invalid topic: ` + topic);
66
+ return;
67
+ }
68
+ const event = this.createEvent(sender, topic, data, eventId);
69
+ const handlers = this.getMatchingHandlers(event.topic);
70
+ handlers.forEach(handler => {
71
+ if (handler.ignoreSender && handler.ignoreSender.includes(sender)) {
72
+ // console.log("ignore event as its in the ignoreSender list", { event, ignoreList: handler.ignoreSender });
73
+ return;
74
+ }
75
+ handler.handler(event);
76
+ });
77
+ this.logIfDebug(`Emitting event to ` + topic, event);
78
+ if (handlers.size === 0) {
79
+ this.logAndThrowError(false, `No handlers found for topic: ` + topic);
80
+ }
81
+ // If it's a response to a request
82
+ if (eventId && this.responseResolvers.has(eventId) && !skipResponseTrigger) {
83
+ // console.log("[Rimori] Resolving response to request: " + eventId, event.data);
84
+ this.responseResolvers.get(eventId)(event);
85
+ this.responseResolvers.delete(eventId);
86
+ }
87
+ }
88
+ /**
89
+ * Subscribes to an event on the event bus.
90
+ * @param topics - The topic of the event.
91
+ * @param handler - The handler to be called when the event is emitted.
92
+ * @param ignoreSender - The senders to ignore.
93
+ * @returns The ids of the listeners.
94
+ */
95
+ on(topics, handler, ignoreSender = []) {
96
+ return this.toArray(topics).map(topic => {
97
+ if (!this.validateTopic(topic)) {
98
+ this.logAndThrowError(true, `Invalid topic: ` + topic);
99
+ }
100
+ if (!this.listeners.has(topic)) {
101
+ this.listeners.set(topic, new Set());
102
+ }
103
+ const id = Math.floor(Math.random() * 10000000000);
104
+ // Type assertion to handle the generic type mismatch
105
+ const eventHandler = handler;
106
+ this.listeners.get(topic).add({ id, handler: eventHandler, ignoreSender });
107
+ this.logIfDebug(`Subscribed to ` + topic, { listenerId: id, ignoreSender });
108
+ return btoa(JSON.stringify({ topic, id }));
109
+ });
110
+ }
111
+ /**
112
+ * Subscribes to an event, processes the data and emits a response on the event bus.
113
+ * @param sender - The sender of the event.
114
+ * @param topic - The topic of the event.
115
+ * @param handler - The handler to be called when the event is received. The handler returns the data to be emitted. Can be a static object or a function.
116
+ * @returns The ids of the listeners.
117
+ */
118
+ respond(sender, topic, handler) {
119
+ const ids = this.on(topic, (data) => __awaiter(this, void 0, void 0, function* () {
120
+ const response = typeof handler === "function" ? yield handler(data) : handler;
121
+ this.emit(sender, topic, response, data.eventId);
122
+ }), [sender]);
123
+ this.logIfDebug(`Added respond listener ` + sender + " to topic " + topic, { listenerIds: ids, sender });
124
+ return ids;
125
+ }
126
+ /**
127
+ * Subscribes to an event on the event bus. The handler will be called once and then removed.
128
+ * @param topic - The topic of the event.
129
+ * @param handler - The handler to be called when the event is emitted.
130
+ */
131
+ once(topic, handler) {
132
+ if (!this.validateTopic(topic)) {
133
+ this.logAndThrowError(false, `Invalid topic: ` + topic);
134
+ return;
135
+ }
136
+ let ids = [];
137
+ const wrapper = (event) => {
138
+ handler(event);
139
+ this.off(ids);
140
+ };
141
+ ids = this.on(topic, wrapper);
142
+ this.logIfDebug(`Added once listener ` + topic, { listenerIds: ids, topic });
143
+ }
144
+ /**
145
+ * Unsubscribes from an event on the event bus.
146
+ * @param listenerIds - The ids of the listeners to unsubscribe from.
147
+ */
148
+ off(listenerIds) {
149
+ this.toArray(listenerIds).forEach(fullId => {
150
+ const { topic, id } = JSON.parse(atob(fullId));
151
+ const listeners = this.listeners.get(topic) || new Set();
152
+ listeners.forEach(listener => {
153
+ if (listener.id === Number(id)) {
154
+ listeners.delete(listener);
155
+ this.logIfDebug(`Removed listener ` + fullId, { topic, listenerId: id });
156
+ }
157
+ });
158
+ });
159
+ }
160
+ toArray(item) {
161
+ return Array.isArray(item) ? item : [item];
162
+ }
163
+ /**
164
+ * Requests data from the event bus.
165
+ * @param sender - The sender of the event.
166
+ * @param topic - The topic of the event.
167
+ * @param data - The data of the event.
168
+ * @returns A promise that resolves to the event.
169
+ */
170
+ request(sender, topic, data) {
171
+ return __awaiter(this, void 0, void 0, function* () {
172
+ if (!this.validateTopic(topic)) {
173
+ this.logAndThrowError(true, `Invalid topic: ` + topic);
174
+ }
175
+ const event = this.createEvent(sender, topic, data || {});
176
+ this.logIfDebug(`Requesting data from ` + topic, { event });
177
+ return new Promise(resolve => {
178
+ this.responseResolvers.set(event.eventId, (value) => resolve(value));
179
+ this.emitInternal(sender, topic, data || {}, event.eventId, true);
180
+ });
181
+ });
182
+ }
183
+ /**
184
+ * Gets the matching handlers for an event.
185
+ * @param topic - The topic of the event.
186
+ * @returns A set of handlers that match the event type.
187
+ */
188
+ getMatchingHandlers(topic) {
189
+ const exact = this.listeners.get(topic) || new Set();
190
+ // Find wildcard matches
191
+ const wildcard = [...this.listeners.entries()]
192
+ .filter(([key]) => key.endsWith("*") && topic.startsWith(key.slice(0, -1)))
193
+ .flatMap(([_, handlers]) => [...handlers]);
194
+ return new Set([...exact, ...wildcard]);
195
+ }
196
+ /**
197
+ * Validates the topic of an event.
198
+ * @param topic - The topic of the event.
199
+ * @returns True if the topic is valid, false otherwise.
200
+ */
201
+ validateTopic(topic) {
202
+ // Split event type into parts
203
+ const parts = topic.split(".");
204
+ const [plugin, area, action] = parts;
205
+ if (parts.length !== 3) {
206
+ if (parts.length === 1 && plugin === "*") {
207
+ return true;
208
+ }
209
+ if (parts.length === 2 && plugin !== "*" && area === "*") {
210
+ return true;
211
+ }
212
+ this.logAndThrowError(false, `Event type must have 3 parts separated by dots. Received: ` + topic);
213
+ return false;
214
+ }
215
+ if (action === "*") {
216
+ return true;
217
+ }
218
+ // Validate action part
219
+ const validActions = ["request", "create", "update", "delete", "trigger"];
220
+ if (validActions.some(a => action.startsWith(a))) {
221
+ return true;
222
+ }
223
+ this.logAndThrowError(false, `Invalid event topic name. The action: ` + action + ". Must be or start with one of: " + validActions.join(", "));
224
+ return false;
225
+ }
226
+ logIfDebug(...args) {
227
+ if (this.debugEnabled) {
228
+ console.debug(`[${this.evName}] ` + args[0], ...args.slice(1));
229
+ }
230
+ }
231
+ logAndThrowError(throwError, ...args) {
232
+ const message = `[${this.evName}] ` + args[0];
233
+ console.error(message, ...args.slice(1));
234
+ if (throwError) {
235
+ throw new Error(message);
236
+ }
237
+ }
238
+ }
239
+ EventBusHandler.instance = null;
240
+ export const EventBus = EventBusHandler.getInstance();