ag-common 0.0.853 → 0.0.855

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.
@@ -1,15 +1,12 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  exports.blockKeyService = exports.getAvailableCombinations = void 0;
7
- const node_cache_1 = __importDefault(require("node-cache"));
8
4
  const common_1 = require("../../../common");
9
5
  const log_1 = require("../../../common/helpers/log");
10
6
  const truncate_1 = require("../../../common/helpers/string/truncate");
7
+ const helpers_1 = require("../../../node/helpers");
11
8
  // Initialize NodeCache with 1 hour TTL for blocklisted key combinations
12
- const blocklist = new node_cache_1.default({ stdTTL: 3600 });
9
+ const blocklist = new helpers_1.TypedNodeCache({ stdTTL: 3600 });
13
10
  // Helper to generate blocklist key
14
11
  const getBlocklistKey = (apiKey, service) => `${(0, truncate_1.truncate)(apiKey, 10)}_${service}`;
15
12
  // Helper to check if a key+service combination is blocklisted
@@ -1,4 +1,10 @@
1
1
  export type ModelPreference = 'quality' | 'fast' | undefined;
2
+ export declare const geminiPromptImage: ({ prompt, urls, ident, prefer, }: {
3
+ prompt: string;
4
+ urls?: string[];
5
+ ident: string | undefined;
6
+ prefer?: ModelPreference;
7
+ }) => Promise<string>;
2
8
  export declare const geminiPromptDirect: ({ prompt, images, ident, prefer, groundedSearch, }: {
3
9
  prompt: string;
4
10
  images?: {
@@ -9,9 +9,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.resolveGroundedUrl = exports.geminiPromptDirect = void 0;
12
+ exports.resolveGroundedUrl = exports.geminiPromptDirect = exports.geminiPromptImage = void 0;
13
13
  const genai_1 = require("@google/genai");
14
+ const array_1 = require("../../../common/helpers/array");
15
+ const async_1 = require("../../../common/helpers/async");
14
16
  const log_1 = require("../../../common/helpers/log");
17
+ const fetch_1 = require("../../../node/helpers/fetch");
15
18
  const apikey_1 = require("./apikey");
16
19
  let genAIs;
17
20
  // Available Gemini models
@@ -72,6 +75,24 @@ const getAvailableGeminiCombinations = (prefer) => {
72
75
  }
73
76
  return combinations;
74
77
  };
78
+ const geminiPromptImage = (_a) => __awaiter(void 0, [_a], void 0, function* ({ prompt, urls, ident, prefer, }) {
79
+ let images = [];
80
+ if (urls && urls.length > 0) {
81
+ images = yield (0, async_1.asyncMap)(urls, (i) => (0, fetch_1.fetchToMemory)(i));
82
+ }
83
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
84
+ if (images.find((a) => !a)) {
85
+ throw new Error('image not downloaded correctly');
86
+ }
87
+ const r = yield (0, exports.geminiPromptDirect)({
88
+ prompt,
89
+ images: images.filter(array_1.notEmpty),
90
+ ident,
91
+ prefer,
92
+ });
93
+ return r;
94
+ });
95
+ exports.geminiPromptImage = geminiPromptImage;
75
96
  const geminiPromptDirect = (_a) => __awaiter(void 0, [_a], void 0, function* ({ prompt, images = [], ident, prefer, groundedSearch = false, }) {
76
97
  var _b;
77
98
  const combinations = getAvailableGeminiCombinations(prefer);
@@ -6,3 +6,8 @@ export declare function fetchFile(p: {
6
6
  FILE_URL: string;
7
7
  FILE_PATH: string;
8
8
  }): Promise<void>;
9
+ export declare function fetchToMemory(imageUrl: string): Promise<{
10
+ type: string;
11
+ arraybuffer: ArrayBuffer;
12
+ } | undefined>;
13
+ export declare function fetchExists(imageUrl: string): Promise<boolean>;
@@ -13,7 +13,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
13
13
  };
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.fetchFile = fetchFile;
16
+ exports.fetchToMemory = fetchToMemory;
17
+ exports.fetchExists = fetchExists;
16
18
  const fs_1 = __importDefault(require("fs"));
19
+ const withRetry_1 = require("../../api/helpers/withRetry");
20
+ const log_1 = require("../../common/helpers/log");
21
+ const headers_1 = require("./headers");
22
+ const node_cache_1 = require("./node-cache");
17
23
  /**
18
24
  * download(fetch) file
19
25
  * @param p
@@ -45,3 +51,54 @@ function fetchFile(p) {
45
51
  }
46
52
  });
47
53
  }
54
+ function fetchToMemory(imageUrl) {
55
+ return __awaiter(this, void 0, void 0, function* () {
56
+ try {
57
+ // Download the image
58
+ const response = yield fetch(imageUrl, { headers: (0, headers_1.getFetchHeaders)() });
59
+ if (!response.ok) {
60
+ throw new Error(`HTTP error! status: ${response.status}`);
61
+ }
62
+ let type = response.headers.get('content-type') || 'image/jpeg';
63
+ if (type.includes('octet')) {
64
+ (0, log_1.debug)('forcing type to jpeg:' + imageUrl);
65
+ type = 'image/jpeg';
66
+ }
67
+ // Get the image data as an ArrayBuffer
68
+ const arraybuffer = yield response.arrayBuffer();
69
+ return { type, arraybuffer };
70
+ }
71
+ catch (e) {
72
+ const em = e;
73
+ (0, log_1.warn)('Error downloading image:', imageUrl, em.toString());
74
+ return undefined;
75
+ }
76
+ });
77
+ }
78
+ const imageExistsCache = new node_cache_1.TypedNodeCache({ stdTTL: 60 * 60 * 24 });
79
+ function fetchExists(imageUrl) {
80
+ return __awaiter(this, void 0, void 0, function* () {
81
+ const cached = imageExistsCache.get(imageUrl);
82
+ if (typeof cached === 'boolean') {
83
+ return cached;
84
+ }
85
+ const response = yield (0, withRetry_1.withRetry)(() => __awaiter(this, void 0, void 0, function* () {
86
+ const response = yield fetch(imageUrl, {
87
+ method: 'HEAD',
88
+ headers: (0, headers_1.getFetchHeaders)(),
89
+ });
90
+ if (response.status === 200)
91
+ return true;
92
+ if (response.status === 404)
93
+ return false;
94
+ throw new Error(`Unexpected status: ${response.status}`);
95
+ }), 'imageExistsAtUrl');
96
+ if (response === false) {
97
+ imageExistsCache.set(imageUrl, false, 1);
98
+ }
99
+ else {
100
+ imageExistsCache.set(imageUrl, true);
101
+ }
102
+ return response;
103
+ });
104
+ }
@@ -0,0 +1,29 @@
1
+ export declare const getFetchHeaders: (host?: string) => {
2
+ accept: string;
3
+ 'accept-language': string;
4
+ connection: string;
5
+ dnt: string;
6
+ host: string;
7
+ 'sec-fetch-dest': string;
8
+ 'sec-fetch-mode': string;
9
+ 'sec-fetch-site': string;
10
+ 'user-agent': string;
11
+ 'sec-ch-ua': string;
12
+ 'sec-ch-ua-mobile': string;
13
+ 'sec-ch-ua-platform': string;
14
+ 'sec-fetch-user': string;
15
+ 'upgrade-insecure-requests': string;
16
+ 'viewport-width': string;
17
+ 'viewport-height': string;
18
+ 'sec-ch-ua-full-version-list': string;
19
+ 'sec-ch-ua-arch': string;
20
+ 'sec-ch-ua-bitness': string;
21
+ 'sec-ch-ua-model': string;
22
+ 'sec-ch-ua-platform-version': string;
23
+ 'sec-ch-ua-wow64': string;
24
+ 'device-memory': string;
25
+ downlink: string;
26
+ ect: string;
27
+ rtt: string;
28
+ 'color-depth': string;
29
+ };
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getFetchHeaders = void 0;
4
+ const languages = [
5
+ 'en-AU,en;q=0.9,en-GB;q=0.8,en-US;q=0.7,cy;q=0.6,af;q=0.5,lb;q=0.4,hu;q=0.3,pt;q=0.2',
6
+ ];
7
+ const browsers = [
8
+ {
9
+ name: 'Google Chrome',
10
+ version: '135',
11
+ userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36',
12
+ },
13
+ {
14
+ name: 'Firefox',
15
+ version: '124',
16
+ userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:124.0) Gecko/20100101 Firefox/124.0',
17
+ },
18
+ {
19
+ name: 'Edge',
20
+ version: '122',
21
+ userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0',
22
+ },
23
+ ];
24
+ const platforms = ['Windows', 'Macintosh', 'Linux'];
25
+ const getRandomItem = (array) => {
26
+ return array[Math.floor(Math.random() * array.length)];
27
+ };
28
+ // Add randomization to viewport dimensions
29
+ const viewports = [
30
+ { width: 1920, height: 1080 },
31
+ { width: 1366, height: 768 },
32
+ { width: 1536, height: 864 },
33
+ { width: 1440, height: 900 },
34
+ { width: 1280, height: 720 },
35
+ ];
36
+ const getFetchHeaders = (host) => {
37
+ const browser = getRandomItem(browsers);
38
+ const browserString = `"${browser.name}";v="${browser.version}", "Not-A.Brand";v="8", "Chromium";v="${browser.version}"`;
39
+ const viewport = getRandomItem(viewports);
40
+ const platform = getRandomItem(platforms);
41
+ const colorDepth = getRandomItem([24, 30, 48]);
42
+ const connection = getRandomItem(['4g', '5g', 'wifi']);
43
+ return {
44
+ accept: '*/*',
45
+ 'accept-language': getRandomItem(languages),
46
+ connection: 'keep-alive',
47
+ dnt: '1',
48
+ host: host || '',
49
+ 'sec-fetch-dest': 'empty',
50
+ 'sec-fetch-mode': 'cors',
51
+ 'sec-fetch-site': 'same-origin',
52
+ 'user-agent': browser.userAgent,
53
+ 'sec-ch-ua': browserString,
54
+ 'sec-ch-ua-mobile': '?0',
55
+ 'sec-ch-ua-platform': '"Windows"',
56
+ 'sec-fetch-user': '?1',
57
+ 'upgrade-insecure-requests': '1',
58
+ 'viewport-width': viewport.width.toString(),
59
+ 'viewport-height': viewport.height.toString(),
60
+ 'sec-ch-ua-full-version-list': browserString,
61
+ 'sec-ch-ua-arch': `"${platform === 'Windows' ? 'x86' : 'arm'}"`,
62
+ 'sec-ch-ua-bitness': '64',
63
+ 'sec-ch-ua-model': '',
64
+ 'sec-ch-ua-platform-version': platform === 'Windows' ? '"15.0.0"' : '"14.0.0"',
65
+ 'sec-ch-ua-wow64': '?0',
66
+ 'device-memory': getRandomItem(['4', '8', '16']),
67
+ downlink: getRandomItem(['1.5', '5.0', '10.0']),
68
+ ect: connection,
69
+ rtt: getRandomItem(['50', '100', '150']),
70
+ 'color-depth': colorDepth.toString(),
71
+ };
72
+ };
73
+ exports.getFetchHeaders = getFetchHeaders;
@@ -1,2 +1,4 @@
1
1
  export * from './fetch';
2
2
  export * from './fs';
3
+ export * from './headers';
4
+ export * from './node-cache';
@@ -16,3 +16,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./fetch"), exports);
18
18
  __exportStar(require("./fs"), exports);
19
+ __exportStar(require("./headers"), exports);
20
+ __exportStar(require("./node-cache"), exports);
@@ -0,0 +1,71 @@
1
+ import NodeCache from 'node-cache';
2
+ export interface CacheOptions {
3
+ stdTTL?: number;
4
+ checkperiod?: number;
5
+ useClones?: boolean;
6
+ deleteOnExpire?: boolean;
7
+ enableLegacyCallbacks?: boolean;
8
+ maxKeys?: number;
9
+ }
10
+ export declare class TypedNodeCache<T = any> {
11
+ private cache;
12
+ constructor(options?: CacheOptions);
13
+ /**
14
+ * Normalizes the key to lowercase for case-insensitive operations
15
+ */
16
+ private normalizeKey;
17
+ /**
18
+ * Get a value from the cache
19
+ */
20
+ get(key: string): T | undefined;
21
+ /**
22
+ * Set a value in the cache
23
+ */
24
+ set(key: string, value: T, ttl?: number): boolean;
25
+ /**
26
+ * Delete a key from the cache
27
+ */
28
+ del(key: string): number;
29
+ /**
30
+ * Check if a key exists in the cache
31
+ */
32
+ has(key: string): boolean;
33
+ /**
34
+ * Get multiple values from the cache
35
+ */
36
+ mget(keys: string[]): {
37
+ [key: string]: T;
38
+ };
39
+ /**
40
+ * Set multiple values in the cache
41
+ */
42
+ mset(keyValuePairs: Array<{
43
+ key: string;
44
+ val: T;
45
+ ttl?: number;
46
+ }>): boolean;
47
+ /**
48
+ * Get all keys in the cache
49
+ */
50
+ keys(): string[];
51
+ /**
52
+ * Get cache statistics
53
+ */
54
+ getStats(): NodeCache.Stats;
55
+ /**
56
+ * Flush all data from the cache
57
+ */
58
+ flushAll(): void;
59
+ /**
60
+ * Close the cache and clear all timers
61
+ */
62
+ close(): void;
63
+ /**
64
+ * Get the TTL for a key
65
+ */
66
+ getTtl(key: string): number | undefined;
67
+ /**
68
+ * Set the TTL for a key
69
+ */
70
+ ttl(key: string, ttl: number): boolean;
71
+ }
@@ -0,0 +1,97 @@
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.TypedNodeCache = void 0;
7
+ const node_cache_1 = __importDefault(require("node-cache"));
8
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
9
+ class TypedNodeCache {
10
+ constructor(options = {}) {
11
+ this.cache = new node_cache_1.default(Object.assign({ stdTTL: 3600, checkperiod: 120 }, options));
12
+ }
13
+ /**
14
+ * Normalizes the key to lowercase for case-insensitive operations
15
+ */
16
+ normalizeKey(key) {
17
+ return key.toLowerCase();
18
+ }
19
+ /**
20
+ * Get a value from the cache
21
+ */
22
+ get(key) {
23
+ return this.cache.get(this.normalizeKey(key));
24
+ }
25
+ /**
26
+ * Set a value in the cache
27
+ */
28
+ set(key, value, ttl) {
29
+ if (ttl !== undefined) {
30
+ return this.cache.set(this.normalizeKey(key), value, ttl);
31
+ }
32
+ return this.cache.set(this.normalizeKey(key), value);
33
+ }
34
+ /**
35
+ * Delete a key from the cache
36
+ */
37
+ del(key) {
38
+ return this.cache.del(this.normalizeKey(key));
39
+ }
40
+ /**
41
+ * Check if a key exists in the cache
42
+ */
43
+ has(key) {
44
+ return this.cache.has(this.normalizeKey(key));
45
+ }
46
+ /**
47
+ * Get multiple values from the cache
48
+ */
49
+ mget(keys) {
50
+ const normalizedKeys = keys.map((key) => this.normalizeKey(key));
51
+ return this.cache.mget(normalizedKeys);
52
+ }
53
+ /**
54
+ * Set multiple values in the cache
55
+ */
56
+ mset(keyValuePairs) {
57
+ const normalizedPairs = keyValuePairs.map((pair) => (Object.assign(Object.assign({}, pair), { key: this.normalizeKey(pair.key) })));
58
+ return this.cache.mset(normalizedPairs);
59
+ }
60
+ /**
61
+ * Get all keys in the cache
62
+ */
63
+ keys() {
64
+ return this.cache.keys();
65
+ }
66
+ /**
67
+ * Get cache statistics
68
+ */
69
+ getStats() {
70
+ return this.cache.getStats();
71
+ }
72
+ /**
73
+ * Flush all data from the cache
74
+ */
75
+ flushAll() {
76
+ this.cache.flushAll();
77
+ }
78
+ /**
79
+ * Close the cache and clear all timers
80
+ */
81
+ close() {
82
+ this.cache.close();
83
+ }
84
+ /**
85
+ * Get the TTL for a key
86
+ */
87
+ getTtl(key) {
88
+ return this.cache.getTtl(this.normalizeKey(key));
89
+ }
90
+ /**
91
+ * Set the TTL for a key
92
+ */
93
+ ttl(key, ttl) {
94
+ return this.cache.ttl(this.normalizeKey(key), ttl);
95
+ }
96
+ }
97
+ exports.TypedNodeCache = TypedNodeCache;
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.0.853",
2
+ "version": "0.0.855",
3
3
  "name": "ag-common",
4
4
  "main": "./dist/index.js",
5
5
  "types": "./dist/index.d.ts",