kozz-module-maker 0.1.0

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 (42) hide show
  1. package/.env +2 -0
  2. package/.prettierrc +8 -0
  3. package/jest.config.ts +196 -0
  4. package/package.json +33 -0
  5. package/readme.md +187 -0
  6. package/src/Instance/Common/ResourceMap/index.ts +26 -0
  7. package/src/Instance/Common/UseFns/index.ts +22 -0
  8. package/src/Instance/Common/index.ts +3 -0
  9. package/src/Instance/Common/onEvent/index.ts +105 -0
  10. package/src/Instance/GeneralModule/index.ts +98 -0
  11. package/src/Message/FromTemplate/index.ts +74 -0
  12. package/src/Message/PayloadCreation/Media.ts +62 -0
  13. package/src/Message/PayloadCreation/React.ts +16 -0
  14. package/src/Message/PayloadCreation/Reply.ts +63 -0
  15. package/src/Message/PayloadCreation/index.ts +1 -0
  16. package/src/Message/PayloadCreation/sendMessage.ts +27 -0
  17. package/src/Message/ProxiedMessage/index.ts +27 -0
  18. package/src/Message/RoutineCreation/AskResource/AskResourceApi/index.ts +43 -0
  19. package/src/Message/RoutineCreation/AskResource/index.ts +85 -0
  20. package/src/Message/RoutineCreation/Reply/WithMedia.ts +63 -0
  21. package/src/Message/RoutineCreation/Reply/WithSticker.ts +9 -0
  22. package/src/Message/RoutineCreation/Reply/WithTemplate.ts +28 -0
  23. package/src/Message/RoutineCreation/Reply/index.ts +3 -0
  24. package/src/Message/RoutineCreation/SendMessage/index.ts +64 -0
  25. package/src/Message/RoutineCreation/reply.ts +23 -0
  26. package/src/Message/index.ts +44 -0
  27. package/src/Message/kozz-md.parser/index.ts +138 -0
  28. package/src/Schema/index.ts +102 -0
  29. package/src/Socket/Events/Emit/ForwardEvent.ts +22 -0
  30. package/src/Socket/Events/Emit/Introduction.ts +28 -0
  31. package/src/Socket/Events/Emit/RequestProxy.ts +38 -0
  32. package/src/Socket/Events/Emit/RevokeProxy.ts +15 -0
  33. package/src/Socket/Events/Handle/AskResource.ts +37 -0
  34. package/src/Socket/Events/Handle/Command.ts +68 -0
  35. package/src/Socket/Events/Handle/ProxiedMessage.ts +28 -0
  36. package/src/Socket/index.ts +40 -0
  37. package/src/Validator/index.ts +81 -0
  38. package/src/index.ts +2 -0
  39. package/src/messages.kozz.md +52 -0
  40. package/src/util/index.ts +89 -0
  41. package/test.kozz.md +81 -0
  42. package/tsconfig.json +100 -0
package/.env ADDED
@@ -0,0 +1,2 @@
1
+ GATEWAY_URL=http://gramont.ddns.net:4521
2
+ MY_CONTACT_ID=5511947952409@c.us
package/.prettierrc ADDED
@@ -0,0 +1,8 @@
1
+ {
2
+ "trailingComma": "es5",
3
+ "arrowParens": "avoid",
4
+ "useTabs": true,
5
+ "printWidth": 80,
6
+ "singleQuote": true,
7
+ "bracketSpacing": true
8
+ }
package/jest.config.ts ADDED
@@ -0,0 +1,196 @@
1
+ /*
2
+ * For a detailed explanation regarding each configuration property and type check, visit:
3
+ * https://jestjs.io/docs/configuration
4
+ */
5
+
6
+ export default {
7
+ // All imported modules in your tests should be mocked automatically
8
+ // automock: false,
9
+
10
+ // Stop running tests after `n` failures
11
+ // bail: 0,
12
+
13
+ // The directory where Jest should store its cached dependency information
14
+ // cacheDirectory: "C:\\Users\\guiga\\AppData\\Local\\Temp\\jest",
15
+
16
+ // Automatically clear mock calls, instances, contexts and results before every test
17
+ clearMocks: true,
18
+
19
+ // Indicates whether the coverage information should be collected while executing the test
20
+ collectCoverage: true,
21
+
22
+ // An array of glob patterns indicating a set of files for which coverage information should be collected
23
+ // collectCoverageFrom: undefined,
24
+
25
+ // The directory where Jest should output its coverage files
26
+ coverageDirectory: "coverage",
27
+
28
+ // An array of regexp pattern strings used to skip coverage collection
29
+ // coveragePathIgnorePatterns: [
30
+ // "\\\\node_modules\\\\"
31
+ // ],
32
+
33
+ // Indicates which provider should be used to instrument code for coverage
34
+ coverageProvider: "v8",
35
+
36
+ // A list of reporter names that Jest uses when writing coverage reports
37
+ // coverageReporters: [
38
+ // "json",
39
+ // "text",
40
+ // "lcov",
41
+ // "clover"
42
+ // ],
43
+
44
+ // An object that configures minimum threshold enforcement for coverage results
45
+ // coverageThreshold: undefined,
46
+
47
+ // A path to a custom dependency extractor
48
+ // dependencyExtractor: undefined,
49
+
50
+ // Make calling deprecated APIs throw helpful error messages
51
+ // errorOnDeprecated: false,
52
+
53
+ // The default configuration for fake timers
54
+ // fakeTimers: {
55
+ // "enableGlobally": false
56
+ // },
57
+
58
+ // Force coverage collection from ignored files using an array of glob patterns
59
+ // forceCoverageMatch: [],
60
+
61
+ // A path to a module which exports an async function that is triggered once before all test suites
62
+ // globalSetup: undefined,
63
+
64
+ // A path to a module which exports an async function that is triggered once after all test suites
65
+ // globalTeardown: undefined,
66
+
67
+ // A set of global variables that need to be available in all test environments
68
+ // globals: {},
69
+
70
+ // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
71
+ // maxWorkers: "50%",
72
+
73
+ // An array of directory names to be searched recursively up from the requiring module's location
74
+ // moduleDirectories: [
75
+ // "node_modules"
76
+ // ],
77
+
78
+ // An array of file extensions your modules use
79
+ // moduleFileExtensions: [
80
+ // "js",
81
+ // "mjs",
82
+ // "cjs",
83
+ // "jsx",
84
+ // "ts",
85
+ // "tsx",
86
+ // "json",
87
+ // "node"
88
+ // ],
89
+
90
+ // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
91
+ // moduleNameMapper: {},
92
+
93
+ // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
94
+ // modulePathIgnorePatterns: [],
95
+
96
+ // Activates notifications for test results
97
+ // notify: false,
98
+
99
+ // An enum that specifies notification mode. Requires { notify: true }
100
+ // notifyMode: "failure-change",
101
+
102
+ // A preset that is used as a base for Jest's configuration
103
+ // preset: undefined,
104
+
105
+ // Run tests from one or more projects
106
+ // projects: undefined,
107
+
108
+ // Use this configuration option to add custom reporters to Jest
109
+ // reporters: undefined,
110
+
111
+ // Automatically reset mock state before every test
112
+ // resetMocks: false,
113
+
114
+ // Reset the module registry before running each individual test
115
+ // resetModules: false,
116
+
117
+ // A path to a custom resolver
118
+ // resolver: undefined,
119
+
120
+ // Automatically restore mock state and implementation before every test
121
+ // restoreMocks: false,
122
+
123
+ // The root directory that Jest should scan for tests and modules within
124
+ // rootDir: undefined,
125
+
126
+ // A list of paths to directories that Jest should use to search for files in
127
+ // roots: [
128
+ // "<rootDir>"
129
+ // ],
130
+
131
+ // Allows you to use a custom runner instead of Jest's default test runner
132
+ // runner: "jest-runner",
133
+
134
+ // The paths to modules that run some code to configure or set up the testing environment before each test
135
+ // setupFiles: [],
136
+
137
+ // A list of paths to modules that run some code to configure or set up the testing framework before each test
138
+ // setupFilesAfterEnv: [],
139
+
140
+ // The number of seconds after which a test is considered as slow and reported as such in the results.
141
+ // slowTestThreshold: 5,
142
+
143
+ // A list of paths to snapshot serializer modules Jest should use for snapshot testing
144
+ // snapshotSerializers: [],
145
+
146
+ // The test environment that will be used for testing
147
+ // testEnvironment: "jest-environment-node",
148
+
149
+ // Options that will be passed to the testEnvironment
150
+ // testEnvironmentOptions: {},
151
+
152
+ // Adds a location field to test results
153
+ // testLocationInResults: false,
154
+
155
+ // The glob patterns Jest uses to detect test files
156
+ // testMatch: [
157
+ // "**/__tests__/**/*.[jt]s?(x)",
158
+ // "**/?(*.)+(spec|test).[tj]s?(x)"
159
+ // ],
160
+
161
+ // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
162
+ testPathIgnorePatterns: [
163
+ "\\\\node_modules\\\\",
164
+ "\\\\dist\\\\"
165
+ ],
166
+
167
+ // The regexp pattern or array of patterns that Jest uses to detect test files
168
+ // testRegex: [],
169
+
170
+ // This option allows the use of a custom results processor
171
+ // testResultsProcessor: undefined,
172
+
173
+ // This option allows use of a custom test runner
174
+ // testRunner: "jest-circus/runner",
175
+
176
+ // A map from regular expressions to paths to transformers
177
+ // transform: undefined,
178
+
179
+ // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
180
+ // transformIgnorePatterns: [
181
+ // "\\\\node_modules\\\\",
182
+ // "\\.pnp\\.[^\\\\]+$"
183
+ // ],
184
+
185
+ // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
186
+ // unmockedModulePathPatterns: undefined,
187
+
188
+ // Indicates whether each individual test should be reported during the run
189
+ // verbose: undefined,
190
+
191
+ // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
192
+ // watchPathIgnorePatterns: [],
193
+
194
+ // Whether to use watchman for file crawling
195
+ // watchman: true,
196
+ };
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "kozz-module-maker",
3
+ "version": "0.1.0",
4
+ "description": "Library to create new module for the Kozz-Bot protocol",
5
+ "main": "./dist",
6
+ "license": "MIT",
7
+ "scripts": {
8
+ "dev": "tsc && link-module-alias && concurrently \"tsc --watch\" \"nodemon dist/debugIndex.js\"",
9
+ "start": "tsc && link-module-alias && node dist/index.js",
10
+ "test": "jest",
11
+ "docs": "typedoc ./src/index.ts",
12
+ "prepare": "husky install",
13
+ "refresh-lib": "./.husky./post-commit"
14
+ },
15
+ "devDependencies": {
16
+ "@types/jest": "^29.2.5",
17
+ "concurrently": "^7.5.0",
18
+ "kozz-types": "./../kozz-types/",
19
+ "nodemon": "^2.0.22",
20
+ "typedoc": "^0.23.21",
21
+ "typescript": "^5.0.4"
22
+ },
23
+ "dependencies": {
24
+ "arcsecond": "^5.0.0",
25
+ "dotenv": "^16.0.3",
26
+ "husky": "^8.0.3",
27
+ "link-module-alias": "^1.2.0",
28
+ "socket.io-client": "^4.6.1"
29
+ },
30
+ "_moduleAliases": {
31
+ "src": "dist"
32
+ }
33
+ }
package/readme.md ADDED
@@ -0,0 +1,187 @@
1
+ # Kozz Handler Maker
2
+
3
+ This is a library that allows you to create your Handlers for any given chatbot created with Kozz-Bot.
4
+
5
+ ## Authentication
6
+
7
+ All the entities connected to the Gateway must introduce themselves. Is at this point that the authenticaton happens using a pair of RSA keys. You can generate a pair running the script inside `./scripts/generate_key_pair.sh`. There will be a private key and a public key. The public key must be sent to the person who is running the `Kozz-Gateway` instance to be copied to the `./keys` folder. The name of the files must not be changed. After that, the authentication should be taken care. At the moment you have to authenticate all the entities with the same key pair but it's going to change in the future.
8
+
9
+ If for some reason you need to generate the introduction payloads outside the library, you can run the scripts `./scripts/boundary_signature.js` or `./scripts/handler_signature.js`. The payload will be outputed to the console and you have to store the signature in a secure place. Currently it's the solution for you to authenticate when in a Web Browser because the readding of the key is done using `fs` which is not supported on browsers.
10
+
11
+ ```bash
12
+ node ./scripts/handler_signature.js my-handler
13
+ # ^
14
+ # Name of the handler
15
+ {
16
+ methods: [],
17
+ name: 'my-handler',
18
+ role: 'handler',
19
+ signature: 'EkeHbGsdky3r1AbXBkxnybipTtAdLhJ9sIV0w6BfN7tXpWWHztII7xvyROk0jAVdj3DjzQgWxRugxb2f5qAowcKLmr8akBCVU2PO5hnA/XaXjqX6XR2D+AOwVOYwJZk4ToiiJJ/s/qyouJ643cabm+sAt0VvYHsn2JUcg7YqZY4aexFfjHdWJMGFy8CV+JGtA9YTQvTa0+KZTgxE2qY+aLAmTQ3cXC7TML0EtNUgFJV9jlvWUg0Vm7x47unIyIZWROUm6LP8DPnVkraOFNICwWXqhJJ7FhdxiE88L/Q1s8i9T6deRF5tKiZYduOIXz7wQbB3xyrfAxei7s5vvVsIIA=='
20
+ }
21
+ ```
22
+
23
+ ```bash
24
+ node ./scripts/boundary_signature.js my-boundary
25
+ # ^
26
+ # Name of the boundary
27
+ {
28
+ OS: 'windows',
29
+ platforrm: 'WA',
30
+ id: 'my-boundary',
31
+ role: 'boundary',
32
+ signature: 'ONidVqD49w6d7jitqBHtMJ5sJoTqoq1iDNZBruA+xCYLWv5IunY7MF0UwORPJK2pDb4bMlwW+yTd8UdFLlDBzXSEATY+CRUc3HJTS3Hwvf1mICmLqKykERb70I5v1Tba/htakTgKYpTBk1PSBfwabUcLQfNecMZoBoN7J5iCFATshBMeQXgh1mFV9PpS8eNVHnSFDu+d471va9C/BEFutQE+ezLXol/1wtxQm4wKO2a4z07ipUgCPwHaau5dyPPJYr5LDLFGrzzdYenOI5qLthF4Z3t6fswgfwYS5b/yg3tsXr1qgk6YY4Vn5ESjB1Jcits9qsvKz3ryL403nZ4wJg=='
33
+ }
34
+ ```
35
+
36
+ ## Basic Controller
37
+
38
+ The basic controller is a type of Handler that doens't receive messages. It's purpose is to send events to the boundaries or exchange resources with other entities.
39
+
40
+ ```typescript
41
+ const basicController = createBasicController({
42
+ address: 'gateway_address',
43
+ name: 'myController', //must be unique
44
+ });
45
+
46
+ basicController.sendMessage('contact_id', 'boundary_id', 'Hello!!');
47
+
48
+ basicController.ask
49
+ .handler('otherhandler', {
50
+ resource: 'some_resource',
51
+ data: {},
52
+ })
53
+ .then(resource => {
54
+ basicController.sendMessage.withMedia(
55
+ 'contact_id',
56
+ 'boundary_id',
57
+ 'Here is your picture',
58
+ resource.response
59
+ );
60
+ });
61
+ ```
62
+
63
+ ## Message Proxy
64
+
65
+ Message proxy is a type of Handler that will request all the messages from a given boundary to be forwareded to it. The proxy can also request only a single chat from the boundary to be proxied to it. The destination of the messages can be overritten, so there can be a proxy request for another entity other than the proxy itself.
66
+
67
+ ```typescript
68
+ const proxy = createProxyInstance({
69
+ address: 'gateway_address',
70
+ source: 'source_boundary_id/chat_id',
71
+ name: 'my_proxy'
72
+ onMessage: message => {
73
+ if (message.body === "Hello"){
74
+ message.reply("World!");
75
+ }
76
+
77
+ // Stops listening to messages;
78
+ proxy.revoke();
79
+ },
80
+ });
81
+
82
+ const forwarder = createProxyInstance({
83
+ address: 'gateway_address',
84
+ source: 'source_boundary_id/*',
85
+ //Forwards all the messages to another boundary
86
+ name: 'my_other_boundary'
87
+ // Not dealing with messages here, just forwarding them
88
+ onMessage: message => {},
89
+ });
90
+ ```
91
+
92
+ ## Command Handler
93
+
94
+ The command handler is a cool CLI-ish command interpreter that can deal with strong-typed commands.
95
+
96
+ The structure of a command is described below:
97
+
98
+ ### `/hanlder method immediateArg --argName1 arg_value1 --argName2 arg_value2...`
99
+
100
+ `/` is the initial character. All the commands must start with one of the initial characters.
101
+
102
+ `handler` is the name of the handler that must reply to the provided command.
103
+
104
+ `method` is tha name of the method that the command is trying to execute. If no method is provided, it falls back to the method named "default";
105
+
106
+ `immediateArg` is the argument that follows the method.
107
+
108
+ `namedArgs` are arguments to the command that can be referencied with a name.
109
+
110
+ ```typescript
111
+ createHandlerInstance({
112
+ // only commands comming from those bounaries will attempt to run the methods
113
+ boundariesToHandle: ['my_boundary', 'my-other-boundary'],
114
+ name: 'ping',
115
+ address: 'gateway_address',
116
+ methods: {
117
+ // `/ping` => `pong! 0,3 seconds`
118
+ ...createMethod({
119
+ name: 'default',
120
+ args: {},
121
+ func: requester => {
122
+ const now = new Date().getTime();
123
+ const requestTime = requester.rawCommand.message.timestamp;
124
+ const difference = (now - requestTime) / 1000;
125
+
126
+ requester.reply(`Pong! ${difference} seconds`);
127
+ },
128
+ });
129
+
130
+ // `/ping echo test --foo true --bar 12345` => `you provided the correct args!`
131
+ // `/ping echo test --bar 12345` => `you provided the correct args!`
132
+ // `/ping echo --foo true --bar 12345` => _no_response_
133
+ ...createMethod({
134
+ name: 'echo',
135
+ args: {
136
+ immediate: "string"
137
+ foo: "boolean?",
138
+ bar: "number",
139
+ },
140
+ // the args will be type checked and strong typed in the callback;
141
+ func: (requester, {immediate, foo, bar, baz}) => {
142
+ requester.reply("you provided the correct args!");
143
+ },
144
+ });
145
+ },
146
+ });
147
+ ```
148
+
149
+ ## From template
150
+
151
+ You cand send or reply to messages using templates. Instead of relying on strings hard-coded in the methods or callbacks, you can create a simpler version of .MD files and read message templates direct from them. It is still in its early stages so you can bet the .md parser will fail. Use at your own risk.
152
+
153
+ ```markdown
154
+ > @pong
155
+
156
+ # PONG!
157
+
158
+ Time: {{difference}} seconds
159
+
160
+ > ---
161
+ ```
162
+
163
+ ```typescript
164
+ createHandlerInstance({
165
+ boundariesToHandle: ['my_boundary', 'my-other-boundary'],
166
+ name: 'ping',
167
+ address: 'gateway_address',
168
+ methods: {
169
+ // `/ping` =>
170
+ // `PONG! (in bold)
171
+ // Time: 0.3 seconds` (interpolation with values is working)
172
+ ...createMethod({
173
+ name: 'default',
174
+ args: {},
175
+ func: requester => {
176
+ const now = new Date().getTime();
177
+ const requestTime = requester.rawCommand.message.timestamp;
178
+ const difference = (now - requestTime) / 1000;
179
+
180
+ requester.reply.withTemplate('pong', {
181
+ difference,
182
+ });
183
+ },
184
+ });
185
+ templatePath: './src/Handlers/Ping/reply.kozz.md',
186
+ });
187
+ ```
@@ -0,0 +1,26 @@
1
+ import { AskResourcePayload } from 'kozz-types/dist';
2
+
3
+ type ResourceName = string;
4
+ type ResourceGetter = (args: AskResourcePayload['request']['data']) => any;
5
+
6
+ export type ResourceMap = {
7
+ [key: ResourceName]: ResourceGetter;
8
+ };
9
+
10
+ export const createResourceMap = () => {
11
+ const resourceMap: ResourceMap = {};
12
+
13
+ const upsertResource = (name: ResourceName, getter: ResourceGetter) => {
14
+ resourceMap[name] = getter;
15
+ };
16
+
17
+ const removeResource = (name: ResourceName) => {
18
+ delete resourceMap[name];
19
+ };
20
+
21
+ return {
22
+ resourceMap,
23
+ upsertResource,
24
+ removeResource,
25
+ };
26
+ };
@@ -0,0 +1,22 @@
1
+ import { Command } from 'kozz-types';
2
+
3
+ // [TODO] Better type for this
4
+ type HandlerOrProxy = any;
5
+ type HandleOrProxyGetter = () => HandlerOrProxy;
6
+
7
+ export type UseFn = (args: Command) => Command;
8
+ export type OriginalFn = (args: Command) => any;
9
+
10
+ export const createUseFns = (instanceGetter: HandleOrProxyGetter) => {
11
+ const moduleUseFns: UseFn[] = [];
12
+
13
+ const use = (useFn: UseFn) => {
14
+ moduleUseFns.push(useFn);
15
+ return instanceGetter();
16
+ };
17
+
18
+ return {
19
+ moduleUseFns,
20
+ use,
21
+ };
22
+ };
@@ -0,0 +1,3 @@
1
+ export { createResourceMap } from './ResourceMap';
2
+ export { UseFn, createUseFns } from './UseFns';
3
+ export { onEvent } from './onEvent';
@@ -0,0 +1,105 @@
1
+ import { Socket } from 'socket.io-client';
2
+ import { ForwardedEventPayload } from 'kozz-types';
3
+ import crypto from 'crypto';
4
+
5
+ type OnEvent = {
6
+ name: string;
7
+ source: string;
8
+ listeners: {
9
+ id: string;
10
+ cb: (ev: any) => any;
11
+ }[];
12
+ };
13
+
14
+ export const onEvent = (socket: Socket, handlerId: string) => {
15
+ const eventListeners: OnEvent[] = [];
16
+
17
+ const getListenersFromEvent = (evName: string) => {
18
+ return eventListeners.find(ev => ev.name === evName);
19
+ };
20
+
21
+ const on = (
22
+ evName: string,
23
+ eventSource: string,
24
+ callback: (ev: any) => any
25
+ ) => {
26
+ if (!eventListeners.find(listener => listener.name === evName)) {
27
+ eventListeners.push({
28
+ name: evName,
29
+ source: eventSource,
30
+ listeners: [],
31
+ });
32
+ }
33
+
34
+ const id = crypto.randomUUID();
35
+
36
+ eventListeners
37
+ .find(listener => listener.name === evName)
38
+ ?.listeners.push({
39
+ id,
40
+ cb: callback,
41
+ });
42
+
43
+ socket.emit('event_forward_request', {
44
+ sourceId: eventSource,
45
+ destination: {
46
+ id: handlerId,
47
+ type: 'Handler',
48
+ },
49
+ eventName: evName,
50
+ });
51
+
52
+ return {
53
+ eventId: id,
54
+ revoke: removeListener(evName, id),
55
+ };
56
+ };
57
+
58
+ const resendEvents = () => {
59
+ eventListeners.forEach(({ name, listeners, source }) => {
60
+ listeners.forEach(({ id, cb }) => {
61
+ socket.emit('event_forward_request', {
62
+ sourceId: source,
63
+ destination: {
64
+ id: handlerId,
65
+ type: 'Handler',
66
+ },
67
+ eventName: name,
68
+ });
69
+ });
70
+ });
71
+ };
72
+
73
+ const removeListener = (evName: string, evId: string) => () => {
74
+ const event = getListenersFromEvent(evName);
75
+ if (!event?.listeners) return;
76
+ event.listeners = event?.listeners.filter(listener => listener.id !== evId);
77
+ if (event.listeners.length === 0) {
78
+ socket.emit('event_forward_revoke', {
79
+ eventName: evName,
80
+ destination: {
81
+ id: handlerId,
82
+ type: 'Handler',
83
+ },
84
+ });
85
+ }
86
+ };
87
+
88
+ const tryRunEventListeners = (evName: string, eventPayload: any) => {
89
+ const event = getListenersFromEvent(evName);
90
+ if (!event?.listeners) return;
91
+ event.listeners.forEach(listener => listener.cb(eventPayload));
92
+ };
93
+
94
+ socket.on('forwarded_event', (event: ForwardedEventPayload) => {
95
+ console.log('Received Event aaa');
96
+ tryRunEventListeners(event.eventName, event.payload);
97
+ });
98
+
99
+ socket.on('connect', resendEvents);
100
+
101
+ return {
102
+ on,
103
+ tryRunEventListeners,
104
+ };
105
+ };
@@ -0,0 +1,98 @@
1
+ import { Method, TypeString } from '../../Schema';
2
+ import { createResourceMap, createUseFns, onEvent } from '../Common';
3
+ import { connect } from '../../Socket';
4
+ import { revokeProxy } from '../../Socket/Events/Emit/RevokeProxy';
5
+ import { requestProxy } from '../../Socket/Events/Emit/RequestProxy';
6
+ import { ProxiedMessageObject } from '../../Message/ProxiedMessage';
7
+ import { Source } from 'kozz-types';
8
+ import { onAskResource } from '../../Socket/Events/Handle/AskResource';
9
+ import { sendMessageToContact } from '../../Message/RoutineCreation/SendMessage';
10
+ import { createAskResource } from '../../Message/RoutineCreation/AskResource';
11
+
12
+ export type ControllerInitParams<Methods extends Record<string, TypeString>> = {
13
+ name: string;
14
+ address: string;
15
+ templatePath?: string;
16
+ signature?: string;
17
+
18
+ commands?: {
19
+ boundariesToHandle: string[];
20
+ methods?: Record<string, Method<Methods>>;
21
+ };
22
+
23
+ proxy?: {
24
+ source: Source;
25
+ destinationOverride?: string;
26
+ onMessage: (message: ProxiedMessageObject) => any;
27
+ keepAliveProxy?: boolean;
28
+ };
29
+ };
30
+
31
+ export const createModule = <Methods extends Record<string, TypeString>>({
32
+ name,
33
+ address,
34
+ commands,
35
+ proxy,
36
+ signature,
37
+ templatePath,
38
+ }: ControllerInitParams<Methods>) => {
39
+ const { moduleUseFns, use } = createUseFns(() => instance);
40
+
41
+ const { socket, registerMethods } = connect(
42
+ address,
43
+ moduleUseFns,
44
+ templatePath || '',
45
+ name,
46
+ commands?.methods || {},
47
+ commands?.boundariesToHandle || [],
48
+ signature
49
+ );
50
+
51
+ if (commands?.methods) {
52
+ registerMethods(commands?.methods);
53
+ }
54
+
55
+ if (proxy) {
56
+ requestProxy(socket, {
57
+ address,
58
+ name,
59
+ ...proxy,
60
+ });
61
+ }
62
+
63
+ const { removeResource, resourceMap, upsertResource } = createResourceMap();
64
+ onAskResource(socket, resourceMap);
65
+
66
+ const sendMessage = sendMessageToContact(socket, name);
67
+
68
+ let revoke = () => {
69
+ if (proxy) {
70
+ revokeProxy(socket, proxy.source);
71
+ }
72
+ };
73
+
74
+ const { on } = onEvent(socket, name);
75
+
76
+ const ask = createAskResource(socket, {
77
+ requester: {
78
+ id: name,
79
+ type: 'Handler',
80
+ },
81
+ });
82
+
83
+ const instance = {
84
+ use,
85
+ on,
86
+ sendMessage,
87
+ resources: {
88
+ removeResource,
89
+ upsertResource,
90
+ },
91
+ proxy: {
92
+ revoke,
93
+ },
94
+ ask,
95
+ };
96
+
97
+ return instance;
98
+ };