@blocklet/aigne-hub 0.2.7

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 (128) hide show
  1. package/README.md +29 -0
  2. package/lib/cjs/api/ai-kit.js +60 -0
  3. package/lib/cjs/api/api.js +17 -0
  4. package/lib/cjs/api/app.js +57 -0
  5. package/lib/cjs/api/call/api.js +51 -0
  6. package/lib/cjs/api/call/app.js +74 -0
  7. package/lib/cjs/api/call/index.js +19 -0
  8. package/lib/cjs/api/call/proxy.js +64 -0
  9. package/lib/cjs/api/call/v1.js +166 -0
  10. package/lib/cjs/api/call/v2.js +101 -0
  11. package/lib/cjs/api/config.js +46 -0
  12. package/lib/cjs/api/constants.js +4 -0
  13. package/lib/cjs/api/error.js +42 -0
  14. package/lib/cjs/api/index.js +19 -0
  15. package/lib/cjs/api/types/audio.js +2 -0
  16. package/lib/cjs/api/types/chat.js +14 -0
  17. package/lib/cjs/api/types/embedding.js +2 -0
  18. package/lib/cjs/api/types/image.js +2 -0
  19. package/lib/cjs/api/types/index.js +19 -0
  20. package/lib/cjs/api/types/status.js +2 -0
  21. package/lib/cjs/api/utils/auth.js +90 -0
  22. package/lib/cjs/api/utils/event-stream.js +59 -0
  23. package/lib/cjs/components/conversation/conversation.js +71 -0
  24. package/lib/cjs/components/conversation/index.js +25 -0
  25. package/lib/cjs/components/conversation/message.js +120 -0
  26. package/lib/cjs/components/conversation/prompt.js +43 -0
  27. package/lib/cjs/components/conversation/use-conversation.js +100 -0
  28. package/lib/cjs/components/credit/alert.js +40 -0
  29. package/lib/cjs/components/credit/balance.js +95 -0
  30. package/lib/cjs/components/credit/button.js +69 -0
  31. package/lib/cjs/components/credit/index.js +12 -0
  32. package/lib/cjs/components/form-label.js +27 -0
  33. package/lib/cjs/components/image-preview.js +116 -0
  34. package/lib/cjs/components/index.js +45 -0
  35. package/lib/cjs/components/loading-image.js +37 -0
  36. package/lib/cjs/components/subscribe/alert.js +53 -0
  37. package/lib/cjs/components/subscribe/button.js +92 -0
  38. package/lib/cjs/components/subscribe/state.js +42 -0
  39. package/lib/cjs/components/switch-button.js +48 -0
  40. package/lib/cjs/components/table.js +203 -0
  41. package/lib/cjs/index.js +2 -0
  42. package/lib/cjs/libs/logger.js +8 -0
  43. package/lib/cjs/utils/withLocaleProvider.js +11 -0
  44. package/lib/esm/api/ai-kit.js +54 -0
  45. package/lib/esm/api/api.js +11 -0
  46. package/lib/esm/api/app.js +42 -0
  47. package/lib/esm/api/call/api.js +24 -0
  48. package/lib/esm/api/call/app.js +68 -0
  49. package/lib/esm/api/call/index.js +3 -0
  50. package/lib/esm/api/call/proxy.js +58 -0
  51. package/lib/esm/api/call/v1.js +155 -0
  52. package/lib/esm/api/call/v2.js +93 -0
  53. package/lib/esm/api/config.js +41 -0
  54. package/lib/esm/api/constants.js +1 -0
  55. package/lib/esm/api/error.js +37 -0
  56. package/lib/esm/api/index.js +3 -0
  57. package/lib/esm/api/types/audio.js +1 -0
  58. package/lib/esm/api/types/chat.js +9 -0
  59. package/lib/esm/api/types/embedding.js +1 -0
  60. package/lib/esm/api/types/image.js +1 -0
  61. package/lib/esm/api/types/index.js +3 -0
  62. package/lib/esm/api/types/status.js +1 -0
  63. package/lib/esm/api/utils/auth.js +79 -0
  64. package/lib/esm/api/utils/event-stream.js +50 -0
  65. package/lib/esm/components/conversation/conversation.js +65 -0
  66. package/lib/esm/components/conversation/index.js +4 -0
  67. package/lib/esm/components/conversation/message.js +114 -0
  68. package/lib/esm/components/conversation/prompt.js +40 -0
  69. package/lib/esm/components/conversation/use-conversation.js +97 -0
  70. package/lib/esm/components/credit/alert.js +35 -0
  71. package/lib/esm/components/credit/balance.js +90 -0
  72. package/lib/esm/components/credit/button.js +64 -0
  73. package/lib/esm/components/credit/index.js +3 -0
  74. package/lib/esm/components/form-label.js +24 -0
  75. package/lib/esm/components/image-preview.js +110 -0
  76. package/lib/esm/components/index.js +14 -0
  77. package/lib/esm/components/loading-image.js +35 -0
  78. package/lib/esm/components/subscribe/alert.js +48 -0
  79. package/lib/esm/components/subscribe/button.js +87 -0
  80. package/lib/esm/components/subscribe/state.js +39 -0
  81. package/lib/esm/components/switch-button.js +46 -0
  82. package/lib/esm/components/table.js +198 -0
  83. package/lib/esm/index.js +1 -0
  84. package/lib/esm/libs/logger.js +3 -0
  85. package/lib/esm/utils/withLocaleProvider.js +8 -0
  86. package/lib/types/api/ai-kit.d.ts +70 -0
  87. package/lib/types/api/api.d.ts +4 -0
  88. package/lib/types/api/app.d.ts +113 -0
  89. package/lib/types/api/call/api.d.ts +2 -0
  90. package/lib/types/api/call/app.d.ts +50 -0
  91. package/lib/types/api/call/index.d.ts +3 -0
  92. package/lib/types/api/call/proxy.d.ts +6 -0
  93. package/lib/types/api/call/v1.d.ts +51 -0
  94. package/lib/types/api/call/v2.d.ts +30 -0
  95. package/lib/types/api/config.d.ts +14 -0
  96. package/lib/types/api/constants.d.ts +1 -0
  97. package/lib/types/api/error.d.ts +18 -0
  98. package/lib/types/api/index.d.ts +3 -0
  99. package/lib/types/api/types/audio.d.ts +18 -0
  100. package/lib/types/api/types/chat.d.ts +97 -0
  101. package/lib/types/api/types/embedding.d.ts +9 -0
  102. package/lib/types/api/types/image.d.ts +23 -0
  103. package/lib/types/api/types/index.d.ts +3 -0
  104. package/lib/types/api/types/status.d.ts +3 -0
  105. package/lib/types/api/utils/auth.d.ts +33 -0
  106. package/lib/types/api/utils/event-stream.d.ts +7 -0
  107. package/lib/types/components/conversation/conversation.d.ts +30 -0
  108. package/lib/types/components/conversation/index.d.ts +4 -0
  109. package/lib/types/components/conversation/message.d.ts +10 -0
  110. package/lib/types/components/conversation/prompt.d.ts +10 -0
  111. package/lib/types/components/conversation/use-conversation.d.ts +44 -0
  112. package/lib/types/components/credit/alert.d.ts +10 -0
  113. package/lib/types/components/credit/balance.d.ts +7 -0
  114. package/lib/types/components/credit/button.d.ts +11 -0
  115. package/lib/types/components/credit/index.d.ts +3 -0
  116. package/lib/types/components/form-label.d.ts +7 -0
  117. package/lib/types/components/image-preview.d.ts +17 -0
  118. package/lib/types/components/index.d.ts +12 -0
  119. package/lib/types/components/loading-image.d.ts +6 -0
  120. package/lib/types/components/subscribe/alert.d.ts +5 -0
  121. package/lib/types/components/subscribe/button.d.ts +5 -0
  122. package/lib/types/components/subscribe/state.d.ts +14 -0
  123. package/lib/types/components/switch-button.d.ts +7 -0
  124. package/lib/types/components/table.d.ts +3 -0
  125. package/lib/types/index.d.ts +1 -0
  126. package/lib/types/libs/logger.d.ts +2 -0
  127. package/lib/types/utils/withLocaleProvider.d.ts +9 -0
  128. package/package.json +158 -0
package/README.md ADDED
@@ -0,0 +1,29 @@
1
+ # AIGNE Hub Lib
2
+
3
+ AIGNE Hub common UX component
4
+
5
+ ## Usage
6
+
7
+ ```jsx
8
+ import React from 'react';
9
+ import { HelloWorld } from '@blocklet/aigne-hub';
10
+
11
+ function App() {
12
+ return <HelloWorld />;
13
+ }
14
+ ```
15
+
16
+ ## Develop
17
+
18
+ ```
19
+
20
+ # develop with @blocklet/aigne-hub and storybook
21
+ npm run dev
22
+
23
+ # only develop with @blocklet/aigne-hub
24
+ npm run watch
25
+
26
+ # only develop with storybook
27
+ npm run storybook
28
+
29
+ ```
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createImageGenerationApi = exports.createTextCompletionApi = exports.createStatusApi = void 0;
4
+ const error_1 = require("./error");
5
+ const createStatusApi = ({ axios, path }) => () => axios.get(path).then((res) => res.data);
6
+ exports.createStatusApi = createStatusApi;
7
+ const createTextCompletionApi = ({ fetch, path, timeout, }) => async (options) => {
8
+ const promise = options.stream
9
+ ? fetch(path, {
10
+ method: 'POST',
11
+ headers: { 'Content-Type': 'application/json' },
12
+ body: JSON.stringify(options),
13
+ }).then(async (res) => {
14
+ var _a, _b, _c;
15
+ if (res.status !== 200) {
16
+ const text = await res.text();
17
+ let json;
18
+ try {
19
+ json = JSON.parse(text);
20
+ }
21
+ catch (_d) {
22
+ // eslint-disable-next-line no-empty
23
+ }
24
+ if ((_a = json === null || json === void 0 ? void 0 : json.error) === null || _a === void 0 ? void 0 : _a.type) {
25
+ throw new error_1.SubscriptionError((_b = json === null || json === void 0 ? void 0 : json.error) === null || _b === void 0 ? void 0 : _b.type);
26
+ }
27
+ throw new Error(((_c = json === null || json === void 0 ? void 0 : json.error) === null || _c === void 0 ? void 0 : _c.message) || (json === null || json === void 0 ? void 0 : json.message) || text || res.status);
28
+ }
29
+ return res.body;
30
+ })
31
+ : fetch(path, options)
32
+ .then((res) => res.json())
33
+ .then((data) => { var _a, _b, _c, _d, _e, _f, _g; return ({ text: (_d = (_a = data.text) !== null && _a !== void 0 ? _a : (_c = (_b = data.choices) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.text) !== null && _d !== void 0 ? _d : (_g = (_f = (_e = data.choices) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.message) === null || _g === void 0 ? void 0 : _g.content }); })
34
+ .catch(processResponseError);
35
+ if (!timeout) {
36
+ return promise;
37
+ }
38
+ return Promise.race([
39
+ promise,
40
+ new Promise((_, reject) => {
41
+ setTimeout(() => reject(new Error('Timeout')), timeout);
42
+ }),
43
+ ]);
44
+ };
45
+ exports.createTextCompletionApi = createTextCompletionApi;
46
+ const createImageGenerationApi = ({ axios, path, }) => async (options) => {
47
+ return axios
48
+ .post(path, options)
49
+ .then((res) => res.data)
50
+ .catch(processResponseError);
51
+ };
52
+ exports.createImageGenerationApi = createImageGenerationApi;
53
+ function processResponseError(error) {
54
+ var _a, _b, _c, _d, _e;
55
+ const msg = ((_c = (_b = (_a = error.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.error) === null || _c === void 0 ? void 0 : _c.message) || ((_e = (_d = error.response) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.message);
56
+ if (msg) {
57
+ throw new Error(msg);
58
+ }
59
+ throw error;
60
+ }
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ var _a, _b;
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.API_TIMEOUT = exports.PREFIX = void 0;
8
+ const axios_1 = __importDefault(require("axios"));
9
+ exports.PREFIX = (typeof window !== 'undefined' &&
10
+ ((_b = (_a = window.blocklet) === null || _a === void 0 ? void 0 : _a.componentMountPoints.find((i) => i.name === 'ai-kit')) === null || _b === void 0 ? void 0 : _b.mountPoint)) ||
11
+ '/';
12
+ exports.API_TIMEOUT = 30 * 1000;
13
+ const api = axios_1.default.create({
14
+ baseURL: exports.PREFIX,
15
+ timeout: exports.API_TIMEOUT,
16
+ });
17
+ exports.default = api;
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.appStatus = appStatus;
7
+ exports.appConfig = appConfig;
8
+ exports.setAppConfig = setAppConfig;
9
+ exports.appServiceRegister = appServiceRegister;
10
+ exports.appUsedCredits = appUsedCredits;
11
+ exports.unsubscribe = unsubscribe;
12
+ exports.getCreditPaymentLink = getCreditPaymentLink;
13
+ exports.getCreditBalance = getCreditBalance;
14
+ exports.getCreditGrants = getCreditGrants;
15
+ exports.getCreditTransactions = getCreditTransactions;
16
+ const api_1 = __importDefault(require("./api"));
17
+ async function appStatus() {
18
+ return Promise.all([api_1.default.get('/api/app/service/status'), appConfig()]).then(([res, config]) => ({
19
+ ...res.data,
20
+ config,
21
+ }));
22
+ }
23
+ async function appConfig() {
24
+ return api_1.default.get('/api/app/config').then((res) => res.data);
25
+ }
26
+ async function setAppConfig(payload) {
27
+ return api_1.default.patch('/api/app/config', payload).then((res) => res.data);
28
+ }
29
+ async function appServiceRegister() {
30
+ return api_1.default.post('/api/app/service/register').then((res) => res.data);
31
+ }
32
+ async function appUsedCredits(query, options) {
33
+ return api_1.default
34
+ .get((options === null || options === void 0 ? void 0 : options.useAIKitService) ? '/api/app/service/usage' : '/api/app/usage', { params: query })
35
+ .then((res) => res.data);
36
+ }
37
+ async function unsubscribe() {
38
+ return api_1.default.post('/api/app/service/unsubscribe');
39
+ }
40
+ async function getCreditPaymentLink(options) {
41
+ const endpoint = (options === null || options === void 0 ? void 0 : options.useAIKitService) ? '/api/user/service/credit/payment-link' : '/api/user/credit/payment-link';
42
+ return api_1.default.get(endpoint).then((res) => res.data);
43
+ }
44
+ // Get credit balance
45
+ async function getCreditBalance(options) {
46
+ const endpoint = (options === null || options === void 0 ? void 0 : options.useAIKitService) ? '/api/user/service/credit/balance' : '/api/user/credit/balance';
47
+ return api_1.default.get(endpoint).then((res) => res.data);
48
+ }
49
+ // Get credit grants
50
+ async function getCreditGrants(params, options) {
51
+ const endpoint = (options === null || options === void 0 ? void 0 : options.useAIKitService) ? '/api/user/service/credit/grants' : '/api/user/credit/grants';
52
+ return api_1.default.get(endpoint, { params }).then((res) => res.data);
53
+ }
54
+ async function getCreditTransactions(params, options) {
55
+ const endpoint = (options === null || options === void 0 ? void 0 : options.useAIKitService) ? '/api/user/service/credit/transactions' : '/api/user/credit/transactions';
56
+ return api_1.default.get(endpoint, { params }).then((res) => res.data);
57
+ }
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.aiKitApi = void 0;
27
+ exports.catchAndRethrowUpstreamError = catchAndRethrowUpstreamError;
28
+ const axios_1 = __importStar(require("axios"));
29
+ const constants_1 = require("../constants");
30
+ const event_stream_1 = require("../utils/event-stream");
31
+ exports.aiKitApi = axios_1.default.create({
32
+ baseURL: constants_1.AI_KIT_BASE_URL,
33
+ });
34
+ async function catchAndRethrowUpstreamError(response) {
35
+ return response.catch(async (error) => {
36
+ var _a, _b, _c;
37
+ if ((0, axios_1.isAxiosError)(error) && ((_a = error.response) === null || _a === void 0 ? void 0 : _a.data)) {
38
+ const { data } = error.response;
39
+ const json = typeof data[Symbol.iterator] === 'function'
40
+ ? await (0, event_stream_1.tryParseJsonFromResponseStream)(data)
41
+ : data;
42
+ const message = (_b = json === null || json === void 0 ? void 0 : json.error) === null || _b === void 0 ? void 0 : _b.message;
43
+ if (typeof message === 'string') {
44
+ const error = new Error(message);
45
+ error.type = (_c = json === null || json === void 0 ? void 0 : json.error) === null || _c === void 0 ? void 0 : _c.type;
46
+ throw error;
47
+ }
48
+ }
49
+ throw error;
50
+ });
51
+ }
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.appStatus = appStatus;
4
+ exports.appRegister = appRegister;
5
+ exports.cancelSubscription = cancelSubscription;
6
+ exports.recoverSubscription = recoverSubscription;
7
+ const component_1 = require("@blocklet/sdk/lib/component");
8
+ const auth_1 = require("../utils/auth");
9
+ const api_1 = require("./api");
10
+ async function appStatus({ description }, { useAIKitService, ...options } = {}) {
11
+ const response = await (0, api_1.catchAndRethrowUpstreamError)(useAIKitService
12
+ ? api_1.aiKitApi.get('/api/app/status', {
13
+ params: { description },
14
+ responseType: options.responseType,
15
+ headers: { ...(0, auth_1.getRemoteComponentCallHeaders)({}) },
16
+ })
17
+ : (0, component_1.call)({
18
+ name: 'ai-kit',
19
+ method: 'GET',
20
+ path: '/api/app/status',
21
+ params: { description },
22
+ data: {},
23
+ responseType: options === null || options === void 0 ? void 0 : options.responseType,
24
+ }));
25
+ if ((options === null || options === void 0 ? void 0 : options.responseType) === 'stream')
26
+ return response;
27
+ return response.data;
28
+ }
29
+ async function appRegister(payload, { useAIKitService, ...options } = {}) {
30
+ const response = await (0, api_1.catchAndRethrowUpstreamError)(useAIKitService
31
+ ? api_1.aiKitApi.post('/api/app/register', payload, { responseType: options.responseType })
32
+ : (0, component_1.call)({
33
+ name: 'ai-kit',
34
+ method: 'GET',
35
+ path: '/api/app/register',
36
+ data: payload,
37
+ responseType: options === null || options === void 0 ? void 0 : options.responseType,
38
+ }));
39
+ if ((options === null || options === void 0 ? void 0 : options.responseType) === 'stream')
40
+ return response;
41
+ return response.data;
42
+ }
43
+ async function cancelSubscription({ useAIKitService, ...options } = {}) {
44
+ const response = await (0, api_1.catchAndRethrowUpstreamError)(useAIKitService
45
+ ? api_1.aiKitApi.post('/api/app/subscription/cancel', {}, {
46
+ responseType: options.responseType,
47
+ headers: { ...(0, auth_1.getRemoteComponentCallHeaders)({}) },
48
+ })
49
+ : (0, component_1.call)({
50
+ name: 'ai-kit',
51
+ path: '/api/app/subscription/cancel',
52
+ data: {},
53
+ responseType: options === null || options === void 0 ? void 0 : options.responseType,
54
+ }));
55
+ if ((options === null || options === void 0 ? void 0 : options.responseType) === 'stream')
56
+ return response;
57
+ return response.data;
58
+ }
59
+ async function recoverSubscription({ useAIKitService, ...options } = {}) {
60
+ const response = await (0, api_1.catchAndRethrowUpstreamError)(useAIKitService
61
+ ? api_1.aiKitApi.post('/api/app/subscription/recover', {}, {
62
+ responseType: options.responseType,
63
+ headers: { ...(0, auth_1.getRemoteComponentCallHeaders)({}) },
64
+ })
65
+ : (0, component_1.call)({
66
+ name: 'ai-kit',
67
+ path: '/api/app/subscription/recover',
68
+ data: {},
69
+ responseType: options === null || options === void 0 ? void 0 : options.responseType,
70
+ }));
71
+ if ((options === null || options === void 0 ? void 0 : options.responseType) === 'stream')
72
+ return response;
73
+ return response.data;
74
+ }
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./v1"), exports);
18
+ __exportStar(require("./v2"), exports);
19
+ __exportStar(require("./proxy"), exports);
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.proxyToAIKit = proxyToAIKit;
7
+ const http_1 = __importDefault(require("http"));
8
+ const https_1 = __importDefault(require("https"));
9
+ const component_1 = require("@blocklet/sdk/lib/component");
10
+ const verify_sign_1 = require("@blocklet/sdk/lib/util/verify-sign");
11
+ const lodash_1 = require("lodash");
12
+ const ufo_1 = require("ufo");
13
+ const constants_1 = require("../constants");
14
+ const auth_1 = require("../utils/auth");
15
+ function proxyToAIKit(path, { useAIKitService, proxyReqHeaders = ['accept', 'content-type'], proxyResHeaders = ['content-type', 'cache-control'], } = {}) {
16
+ const parseReqBody = path !== '/api/v1/audio/transcriptions';
17
+ return (req, res, next) => {
18
+ var _a;
19
+ const url = (0, ufo_1.parseURL)((0, ufo_1.withQuery)((0, ufo_1.joinURL)(useAIKitService ? constants_1.AI_KIT_BASE_URL : (0, component_1.getComponentWebEndpoint)('ai-kit'), path), req.query));
20
+ const userDid = ((_a = req.user) === null || _a === void 0 ? void 0 : _a.did) || (req === null || req === void 0 ? void 0 : req.get('x-app-user-did'));
21
+ const proxyReq = (url.protocol === 'https:' ? https_1.default : http_1.default).request((0, ufo_1.stringifyParsedURL)(url), {
22
+ headers: {
23
+ ...(0, lodash_1.pick)(req.headers, ...proxyReqHeaders),
24
+ ...(useAIKitService
25
+ ? (0, auth_1.getRemoteComponentCallHeaders)(req.body || {}, userDid)
26
+ : (() => {
27
+ const { iat, exp, sig, version } = (0, verify_sign_1.getSignData)({
28
+ data: req.body,
29
+ params: req.query,
30
+ method: req.method,
31
+ url: (0, ufo_1.stringifyParsedURL)(url),
32
+ });
33
+ return {
34
+ 'x-component-sig': sig,
35
+ 'x-component-sig-iat': iat,
36
+ 'x-component-sig-exp': exp,
37
+ 'x-component-sig-version': version,
38
+ };
39
+ })()),
40
+ },
41
+ method: req.method,
42
+ }, (proxyRes) => {
43
+ if (proxyRes.statusCode)
44
+ res.status(proxyRes.statusCode);
45
+ res.setHeader('X-Accel-Buffering', 'no');
46
+ for (const [k, v] of Object.entries((0, lodash_1.pick)(proxyRes.headers, ...proxyResHeaders))) {
47
+ if (!(0, lodash_1.isNil)(v))
48
+ res.setHeader(k, v);
49
+ }
50
+ proxyRes.pipe(res);
51
+ });
52
+ proxyReq.on('error', (e) => next(e));
53
+ req.on('aborted', () => {
54
+ proxyReq.destroy();
55
+ });
56
+ if (parseReqBody) {
57
+ proxyReq.write(JSON.stringify(req.body));
58
+ proxyReq.end();
59
+ }
60
+ else {
61
+ req.pipe(proxyReq);
62
+ }
63
+ };
64
+ }
@@ -0,0 +1,166 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.status = status;
7
+ exports.chatCompletions = chatCompletions;
8
+ exports.imageGenerations = imageGenerations;
9
+ exports.embeddings = embeddings;
10
+ exports.audioTranscriptions = audioTranscriptions;
11
+ exports.audioSpeech = audioSpeech;
12
+ const web_1 = require("stream/web");
13
+ const component_1 = require("@blocklet/sdk/lib/component");
14
+ const verify_sign_1 = require("@blocklet/sdk/lib/util/verify-sign");
15
+ const axios_1 = __importDefault(require("axios"));
16
+ const form_data_1 = __importDefault(require("form-data"));
17
+ const json_stable_stringify_1 = __importDefault(require("json-stable-stringify"));
18
+ const ufo_1 = require("ufo");
19
+ const types_1 = require("../types");
20
+ const auth_1 = require("../utils/auth");
21
+ const event_stream_1 = require("../utils/event-stream");
22
+ const api_1 = require("./api");
23
+ async function status({ useAIKitService, ...options } = {}) {
24
+ const response = await (0, api_1.catchAndRethrowUpstreamError)(useAIKitService
25
+ ? api_1.aiKitApi
26
+ .get('/api/v1/status', {
27
+ responseType: options.responseType,
28
+ headers: { ...(0, auth_1.getRemoteComponentCallHeaders)({}) },
29
+ })
30
+ .then((res) => res.data)
31
+ : (0, component_1.call)({ name: 'ai-kit', method: 'GET', path: '/api/v1/status', responseType: options === null || options === void 0 ? void 0 : options.responseType }).then((res) => res.data));
32
+ if ((options === null || options === void 0 ? void 0 : options.responseType) === 'stream')
33
+ return response;
34
+ return response.data;
35
+ }
36
+ async function chatCompletions(input, { useAIKitService, ...options } = {}) {
37
+ const response = (0, api_1.catchAndRethrowUpstreamError)(useAIKitService
38
+ ? (0, api_1.aiKitApi)('/api/v1/chat/completions', {
39
+ responseType: 'stream',
40
+ method: 'POST',
41
+ data: (0, json_stable_stringify_1.default)(input),
42
+ headers: {
43
+ ...(0, auth_1.getRemoteComponentCallHeaders)(input),
44
+ Accept: 'text/event-stream',
45
+ 'Content-Type': 'application/json',
46
+ },
47
+ })
48
+ : (0, component_1.call)({
49
+ name: 'ai-kit',
50
+ path: 'api/v1/chat/completions',
51
+ data: input,
52
+ responseType: 'stream',
53
+ headers: { Accept: 'text/event-stream' },
54
+ }));
55
+ if ((options === null || options === void 0 ? void 0 : options.responseType) === 'stream')
56
+ return response;
57
+ return new web_1.ReadableStream({
58
+ async start(controller) {
59
+ try {
60
+ const stream = (0, event_stream_1.readableToWeb)((await response).data)
61
+ .pipeThrough(new web_1.TextDecoderStream())
62
+ .pipeThrough(new event_stream_1.EventSourceParserStream());
63
+ for await (const chunk of stream) {
64
+ if ((0, types_1.isChatCompletionError)(chunk)) {
65
+ if (chunk.error.type) {
66
+ const error = new Error(chunk.error.message);
67
+ error.type = chunk.error.type;
68
+ error.timestamp = chunk.error.timestamp;
69
+ controller.error(error);
70
+ }
71
+ else {
72
+ controller.error(new Error(chunk.error.message));
73
+ }
74
+ break;
75
+ }
76
+ controller.enqueue(chunk);
77
+ }
78
+ }
79
+ catch (error) {
80
+ controller.error(error);
81
+ }
82
+ finally {
83
+ controller.close();
84
+ }
85
+ },
86
+ });
87
+ }
88
+ async function imageGenerations(input, { useAIKitService, ...options } = {}) {
89
+ const response = await (0, api_1.catchAndRethrowUpstreamError)(useAIKitService
90
+ ? api_1.aiKitApi.post('/api/v1/image/generations', input, {
91
+ responseType: options.responseType,
92
+ headers: { ...(0, auth_1.getRemoteComponentCallHeaders)(input) },
93
+ })
94
+ : // @ts-ignore
95
+ (0, component_1.call)({
96
+ name: 'ai-kit',
97
+ path: '/api/v1/image/generations',
98
+ data: input,
99
+ responseType: options === null || options === void 0 ? void 0 : options.responseType,
100
+ timeout: options === null || options === void 0 ? void 0 : options.timeout,
101
+ }));
102
+ if ((options === null || options === void 0 ? void 0 : options.responseType) === 'stream')
103
+ return response;
104
+ return response.data;
105
+ }
106
+ async function embeddings(input, { useAIKitService, ...options } = {}) {
107
+ const response = await (0, api_1.catchAndRethrowUpstreamError)(useAIKitService
108
+ ? api_1.aiKitApi.post('/api/v1/embeddings', input, {
109
+ responseType: options.responseType,
110
+ headers: { ...(0, auth_1.getRemoteComponentCallHeaders)(input) },
111
+ })
112
+ : (0, component_1.call)({
113
+ name: 'ai-kit',
114
+ path: '/api/v1/embeddings',
115
+ data: input,
116
+ responseType: options === null || options === void 0 ? void 0 : options.responseType,
117
+ }));
118
+ if ((options === null || options === void 0 ? void 0 : options.responseType) === 'stream')
119
+ return response;
120
+ return response.data;
121
+ }
122
+ async function audioTranscriptions(input, { useAIKitService, ...options } = {}) {
123
+ const form = new form_data_1.default();
124
+ for (const [key, val] of Object.entries(input)) {
125
+ form.append(key, val);
126
+ }
127
+ const response = await (0, api_1.catchAndRethrowUpstreamError)(useAIKitService
128
+ ? api_1.aiKitApi.post('/api/v1/audio/transcriptions', form, {
129
+ responseType: options.responseType,
130
+ headers: { ...(0, auth_1.getRemoteComponentCallHeaders)({}) },
131
+ })
132
+ : (() => {
133
+ const { iat, exp, sig, version } = (0, verify_sign_1.getSignData)({
134
+ data: {},
135
+ params: {},
136
+ method: 'post',
137
+ url: '/api/v1/audio/transcriptions',
138
+ });
139
+ return axios_1.default.post((0, ufo_1.joinURL)((0, component_1.getComponentWebEndpoint)('ai-kit'), '/api/v1/audio/transcriptions'), form, {
140
+ headers: {
141
+ 'x-component-sig': sig,
142
+ 'x-component-sig-iat': iat,
143
+ 'x-component-sig-exp': exp,
144
+ 'x-component-sig-version': version,
145
+ },
146
+ responseType: options === null || options === void 0 ? void 0 : options.responseType,
147
+ });
148
+ })());
149
+ if ((options === null || options === void 0 ? void 0 : options.responseType) === 'stream')
150
+ return response;
151
+ return response.data;
152
+ }
153
+ async function audioSpeech(input, { useAIKitService } = {}) {
154
+ const response = await (0, api_1.catchAndRethrowUpstreamError)(useAIKitService
155
+ ? api_1.aiKitApi.post('/api/v1/audio/speech', input, {
156
+ responseType: 'stream',
157
+ headers: { ...(0, auth_1.getRemoteComponentCallHeaders)(input) },
158
+ })
159
+ : (0, component_1.call)({
160
+ name: 'ai-kit',
161
+ path: '/api/v1/audio/speech',
162
+ data: input,
163
+ responseType: 'stream',
164
+ }));
165
+ return response;
166
+ }
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.chatCompletionsV2 = chatCompletionsV2;
7
+ exports.imageGenerationsV2 = imageGenerationsV2;
8
+ exports.embeddingsV2 = embeddingsV2;
9
+ const web_1 = require("stream/web");
10
+ const component_1 = require("@blocklet/sdk/lib/component");
11
+ const json_stable_stringify_1 = __importDefault(require("json-stable-stringify"));
12
+ const types_1 = require("../types");
13
+ const auth_1 = require("../utils/auth");
14
+ const event_stream_1 = require("../utils/event-stream");
15
+ const api_1 = require("./api");
16
+ async function chatCompletionsV2(input, { useAIKitService, ...options } = {}) {
17
+ const response = (0, api_1.catchAndRethrowUpstreamError)(useAIKitService
18
+ ? (0, api_1.aiKitApi)('/api/v2/chat/completions', {
19
+ responseType: 'stream',
20
+ method: 'POST',
21
+ data: (0, json_stable_stringify_1.default)(input),
22
+ headers: {
23
+ ...(0, auth_1.getRemoteComponentCallHeaders)(input, options.userDid),
24
+ Accept: 'text/event-stream',
25
+ 'Content-Type': 'application/json',
26
+ },
27
+ })
28
+ : (0, component_1.call)({
29
+ name: 'ai-kit',
30
+ path: 'api/v2/chat/completions',
31
+ data: input,
32
+ responseType: 'stream',
33
+ headers: { Accept: 'text/event-stream' },
34
+ }));
35
+ if ((options === null || options === void 0 ? void 0 : options.responseType) === 'stream')
36
+ return response;
37
+ return new web_1.ReadableStream({
38
+ async start(controller) {
39
+ try {
40
+ const stream = (0, event_stream_1.readableToWeb)((await response).data)
41
+ .pipeThrough(new web_1.TextDecoderStream())
42
+ .pipeThrough(new event_stream_1.EventSourceParserStream());
43
+ for await (const chunk of stream) {
44
+ if ((0, types_1.isChatCompletionError)(chunk)) {
45
+ if (chunk.error.type) {
46
+ const error = new Error(chunk.error.message);
47
+ error.type = chunk.error.type;
48
+ error.timestamp = chunk.error.timestamp;
49
+ controller.error(error);
50
+ }
51
+ else {
52
+ controller.error(new Error(chunk.error.message));
53
+ }
54
+ break;
55
+ }
56
+ controller.enqueue(chunk);
57
+ }
58
+ }
59
+ catch (error) {
60
+ controller.error(error);
61
+ }
62
+ finally {
63
+ controller.close();
64
+ }
65
+ },
66
+ });
67
+ }
68
+ async function imageGenerationsV2(input, { useAIKitService, ...options } = {}) {
69
+ const response = await (0, api_1.catchAndRethrowUpstreamError)(useAIKitService
70
+ ? api_1.aiKitApi.post('/api/v2/image/generations', input, {
71
+ responseType: options.responseType,
72
+ headers: { ...(0, auth_1.getRemoteComponentCallHeaders)(input, options.userDid) },
73
+ })
74
+ : // @ts-ignore
75
+ (0, component_1.call)({
76
+ name: 'ai-kit',
77
+ path: '/api/v2/image/generations',
78
+ data: input,
79
+ responseType: options === null || options === void 0 ? void 0 : options.responseType,
80
+ timeout: options === null || options === void 0 ? void 0 : options.timeout,
81
+ }));
82
+ if ((options === null || options === void 0 ? void 0 : options.responseType) === 'stream')
83
+ return response;
84
+ return response.data;
85
+ }
86
+ async function embeddingsV2(input, { useAIKitService, ...options } = {}) {
87
+ const response = await (0, api_1.catchAndRethrowUpstreamError)(useAIKitService
88
+ ? api_1.aiKitApi.post('/api/v2/embeddings', input, {
89
+ responseType: options.responseType,
90
+ headers: { ...(0, auth_1.getRemoteComponentCallHeaders)(input, options.userDid) },
91
+ })
92
+ : (0, component_1.call)({
93
+ name: 'ai-kit',
94
+ path: '/api/v2/embeddings',
95
+ data: input,
96
+ responseType: options === null || options === void 0 ? void 0 : options.responseType,
97
+ }));
98
+ if ((options === null || options === void 0 ? void 0 : options.responseType) === 'stream')
99
+ return response;
100
+ return response.data;
101
+ }