Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

chatgpt-api-cjs

Package Overview
Dependencies
Maintainers
1
Versions
11
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

chatgpt-api-cjs - npm Package Compare versions

Comparing version 5.0.10 to 5.0.11

1171

build/index.js

@@ -7,2 +7,5 @@ var __create = Object.create;

var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {

@@ -30,2 +33,654 @@ for (var name in all)

// node_modules/.pnpm/json-buffer@3.0.1/node_modules/json-buffer/index.js
var require_json_buffer = __commonJS({
"node_modules/.pnpm/json-buffer@3.0.1/node_modules/json-buffer/index.js"(exports) {
exports.stringify = function stringify(o) {
if ("undefined" == typeof o)
return o;
if (o && Buffer.isBuffer(o))
return JSON.stringify(":base64:" + o.toString("base64"));
if (o && o.toJSON)
o = o.toJSON();
if (o && "object" === typeof o) {
var s = "";
var array = Array.isArray(o);
s = array ? "[" : "{";
var first = true;
for (var k in o) {
var ignore = "function" == typeof o[k] || !array && "undefined" === typeof o[k];
if (Object.hasOwnProperty.call(o, k) && !ignore) {
if (!first)
s += ",";
first = false;
if (array) {
if (o[k] == void 0)
s += "null";
else
s += stringify(o[k]);
} else if (o[k] !== void 0) {
s += stringify(k) + ":" + stringify(o[k]);
}
}
}
s += array ? "]" : "}";
return s;
} else if ("string" === typeof o) {
return JSON.stringify(/^:/.test(o) ? ":" + o : o);
} else if ("undefined" === typeof o) {
return "null";
} else
return JSON.stringify(o);
};
exports.parse = function(s) {
return JSON.parse(s, function(key, value) {
if ("string" === typeof value) {
if (/^:base64:/.test(value))
return Buffer.from(value.substring(8), "base64");
else
return /^:/.test(value) ? value.substring(1) : value;
}
return value;
});
};
}
});
// node_modules/.pnpm/keyv@4.5.2/node_modules/keyv/src/index.js
var require_src = __commonJS({
"node_modules/.pnpm/keyv@4.5.2/node_modules/keyv/src/index.js"(exports, module2) {
"use strict";
var EventEmitter = require("events");
var JSONB = require_json_buffer();
var loadStore = (options) => {
const adapters = {
redis: "@keyv/redis",
rediss: "@keyv/redis",
mongodb: "@keyv/mongo",
mongo: "@keyv/mongo",
sqlite: "@keyv/sqlite",
postgresql: "@keyv/postgres",
postgres: "@keyv/postgres",
mysql: "@keyv/mysql",
etcd: "@keyv/etcd",
offline: "@keyv/offline",
tiered: "@keyv/tiered"
};
if (options.adapter || options.uri) {
const adapter = options.adapter || /^[^:+]*/.exec(options.uri)[0];
return new (require(adapters[adapter]))(options);
}
return /* @__PURE__ */ new Map();
};
var iterableAdapters = [
"sqlite",
"postgres",
"mysql",
"mongo",
"redis",
"tiered"
];
var Keyv2 = class extends EventEmitter {
constructor(uri, { emitErrors = true, ...options } = {}) {
super();
this.opts = {
namespace: "keyv",
serialize: JSONB.stringify,
deserialize: JSONB.parse,
...typeof uri === "string" ? { uri } : uri,
...options
};
if (!this.opts.store) {
const adapterOptions = { ...this.opts };
this.opts.store = loadStore(adapterOptions);
}
if (this.opts.compression) {
const compression = this.opts.compression;
this.opts.serialize = compression.serialize.bind(compression);
this.opts.deserialize = compression.deserialize.bind(compression);
}
if (typeof this.opts.store.on === "function" && emitErrors) {
this.opts.store.on("error", (error) => this.emit("error", error));
}
this.opts.store.namespace = this.opts.namespace;
const generateIterator = (iterator) => async function* () {
for await (const [key, raw] of typeof iterator === "function" ? iterator(this.opts.store.namespace) : iterator) {
const data = this.opts.deserialize(raw);
if (this.opts.store.namespace && !key.includes(this.opts.store.namespace)) {
continue;
}
if (typeof data.expires === "number" && Date.now() > data.expires) {
this.delete(key);
continue;
}
yield [this._getKeyUnprefix(key), data.value];
}
};
if (typeof this.opts.store[Symbol.iterator] === "function" && this.opts.store instanceof Map) {
this.iterator = generateIterator(this.opts.store);
} else if (typeof this.opts.store.iterator === "function" && this.opts.store.opts && this._checkIterableAdaptar()) {
this.iterator = generateIterator(this.opts.store.iterator.bind(this.opts.store));
}
}
_checkIterableAdaptar() {
return iterableAdapters.includes(this.opts.store.opts.dialect) || iterableAdapters.findIndex((element) => this.opts.store.opts.url.includes(element)) >= 0;
}
_getKeyPrefix(key) {
return `${this.opts.namespace}:${key}`;
}
_getKeyPrefixArray(keys) {
return keys.map((key) => `${this.opts.namespace}:${key}`);
}
_getKeyUnprefix(key) {
return key.split(":").splice(1).join(":");
}
get(key, options) {
const { store } = this.opts;
const isArray = Array.isArray(key);
const keyPrefixed = isArray ? this._getKeyPrefixArray(key) : this._getKeyPrefix(key);
if (isArray && store.getMany === void 0) {
const promises = [];
for (const key2 of keyPrefixed) {
promises.push(
Promise.resolve().then(() => store.get(key2)).then((data) => typeof data === "string" ? this.opts.deserialize(data) : this.opts.compression ? this.opts.deserialize(data) : data).then((data) => {
if (data === void 0 || data === null) {
return void 0;
}
if (typeof data.expires === "number" && Date.now() > data.expires) {
return this.delete(key2).then(() => void 0);
}
return options && options.raw ? data : data.value;
})
);
}
return Promise.allSettled(promises).then((values) => {
const data = [];
for (const value of values) {
data.push(value.value);
}
return data;
});
}
return Promise.resolve().then(() => isArray ? store.getMany(keyPrefixed) : store.get(keyPrefixed)).then((data) => typeof data === "string" ? this.opts.deserialize(data) : this.opts.compression ? this.opts.deserialize(data) : data).then((data) => {
if (data === void 0 || data === null) {
return void 0;
}
if (isArray) {
const result = [];
for (let row of data) {
if (typeof row === "string") {
row = this.opts.deserialize(row);
}
if (row === void 0 || row === null) {
result.push(void 0);
continue;
}
if (typeof row.expires === "number" && Date.now() > row.expires) {
this.delete(key).then(() => void 0);
result.push(void 0);
} else {
result.push(options && options.raw ? row : row.value);
}
}
return result;
}
if (typeof data.expires === "number" && Date.now() > data.expires) {
return this.delete(key).then(() => void 0);
}
return options && options.raw ? data : data.value;
});
}
set(key, value, ttl) {
const keyPrefixed = this._getKeyPrefix(key);
if (typeof ttl === "undefined") {
ttl = this.opts.ttl;
}
if (ttl === 0) {
ttl = void 0;
}
const { store } = this.opts;
return Promise.resolve().then(() => {
const expires = typeof ttl === "number" ? Date.now() + ttl : null;
if (typeof value === "symbol") {
this.emit("error", "symbol cannot be serialized");
}
value = { value, expires };
return this.opts.serialize(value);
}).then((value2) => store.set(keyPrefixed, value2, ttl)).then(() => true);
}
delete(key) {
const { store } = this.opts;
if (Array.isArray(key)) {
const keyPrefixed2 = this._getKeyPrefixArray(key);
if (store.deleteMany === void 0) {
const promises = [];
for (const key2 of keyPrefixed2) {
promises.push(store.delete(key2));
}
return Promise.allSettled(promises).then((values) => values.every((x) => x.value === true));
}
return Promise.resolve().then(() => store.deleteMany(keyPrefixed2));
}
const keyPrefixed = this._getKeyPrefix(key);
return Promise.resolve().then(() => store.delete(keyPrefixed));
}
clear() {
const { store } = this.opts;
return Promise.resolve().then(() => store.clear());
}
has(key) {
const keyPrefixed = this._getKeyPrefix(key);
const { store } = this.opts;
return Promise.resolve().then(async () => {
if (typeof store.has === "function") {
return store.has(keyPrefixed);
}
const value = await store.get(keyPrefixed);
return value !== void 0;
});
}
disconnect() {
const { store } = this.opts;
if (typeof store.disconnect === "function") {
return store.disconnect();
}
}
};
module2.exports = Keyv2;
}
});
// node_modules/.pnpm/@dqbd+tiktoken@0.4.0/node_modules/@dqbd/tiktoken/dist/node/_tiktoken.js
var require_tiktoken = __commonJS({
"node_modules/.pnpm/@dqbd+tiktoken@0.4.0/node_modules/@dqbd/tiktoken/dist/node/_tiktoken.js"(exports, module2) {
var imports = {};
imports["__wbindgen_placeholder__"] = module2.exports;
var wasm;
var { TextEncoder, TextDecoder: TextDecoder2 } = require("util");
var heap = new Array(128).fill(void 0);
heap.push(void 0, null, true, false);
function getObject(idx) {
return heap[idx];
}
var heap_next = heap.length;
function dropObject(idx) {
if (idx < 132)
return;
heap[idx] = heap_next;
heap_next = idx;
}
function takeObject(idx) {
const ret = getObject(idx);
dropObject(idx);
return ret;
}
var WASM_VECTOR_LEN = 0;
var cachedUint8Memory0 = null;
function getUint8Memory0() {
if (cachedUint8Memory0 === null || cachedUint8Memory0.byteLength === 0) {
cachedUint8Memory0 = new Uint8Array(wasm.memory.buffer);
}
return cachedUint8Memory0;
}
var cachedTextEncoder = new TextEncoder("utf-8");
var encodeString = typeof cachedTextEncoder.encodeInto === "function" ? function(arg, view) {
return cachedTextEncoder.encodeInto(arg, view);
} : function(arg, view) {
const buf = cachedTextEncoder.encode(arg);
view.set(buf);
return {
read: arg.length,
written: buf.length
};
};
function passStringToWasm0(arg, malloc, realloc) {
if (realloc === void 0) {
const buf = cachedTextEncoder.encode(arg);
const ptr2 = malloc(buf.length);
getUint8Memory0().subarray(ptr2, ptr2 + buf.length).set(buf);
WASM_VECTOR_LEN = buf.length;
return ptr2;
}
let len = arg.length;
let ptr = malloc(len);
const mem = getUint8Memory0();
let offset = 0;
for (; offset < len; offset++) {
const code = arg.charCodeAt(offset);
if (code > 127)
break;
mem[ptr + offset] = code;
}
if (offset !== len) {
if (offset !== 0) {
arg = arg.slice(offset);
}
ptr = realloc(ptr, len, len = offset + arg.length * 3);
const view = getUint8Memory0().subarray(ptr + offset, ptr + len);
const ret = encodeString(arg, view);
offset += ret.written;
}
WASM_VECTOR_LEN = offset;
return ptr;
}
function isLikeNone(x) {
return x === void 0 || x === null;
}
var cachedInt32Memory0 = null;
function getInt32Memory0() {
if (cachedInt32Memory0 === null || cachedInt32Memory0.byteLength === 0) {
cachedInt32Memory0 = new Int32Array(wasm.memory.buffer);
}
return cachedInt32Memory0;
}
var cachedTextDecoder = new TextDecoder2("utf-8", { ignoreBOM: true, fatal: true });
cachedTextDecoder.decode();
function getStringFromWasm0(ptr, len) {
return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len));
}
function addHeapObject(obj) {
if (heap_next === heap.length)
heap.push(heap.length + 1);
const idx = heap_next;
heap_next = heap[idx];
heap[idx] = obj;
return idx;
}
var cachedUint32Memory0 = null;
function getUint32Memory0() {
if (cachedUint32Memory0 === null || cachedUint32Memory0.byteLength === 0) {
cachedUint32Memory0 = new Uint32Array(wasm.memory.buffer);
}
return cachedUint32Memory0;
}
function getArrayU32FromWasm0(ptr, len) {
return getUint32Memory0().subarray(ptr / 4, ptr / 4 + len);
}
function passArray8ToWasm0(arg, malloc) {
const ptr = malloc(arg.length * 1);
getUint8Memory0().set(arg, ptr / 1);
WASM_VECTOR_LEN = arg.length;
return ptr;
}
function passArray32ToWasm0(arg, malloc) {
const ptr = malloc(arg.length * 4);
getUint32Memory0().set(arg, ptr / 4);
WASM_VECTOR_LEN = arg.length;
return ptr;
}
function getArrayU8FromWasm0(ptr, len) {
return getUint8Memory0().subarray(ptr / 1, ptr / 1 + len);
}
module2.exports.get_encoding = function(encoding, extend_special_tokens) {
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
const ptr0 = passStringToWasm0(encoding, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len0 = WASM_VECTOR_LEN;
wasm.get_encoding(retptr, ptr0, len0, addHeapObject(extend_special_tokens));
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
var r2 = getInt32Memory0()[retptr / 4 + 2];
if (r2) {
throw takeObject(r1);
}
return Tiktoken.__wrap(r0);
} finally {
wasm.__wbindgen_add_to_stack_pointer(16);
}
};
module2.exports.encoding_for_model = function(model, extend_special_tokens) {
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
const ptr0 = passStringToWasm0(model, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len0 = WASM_VECTOR_LEN;
wasm.encoding_for_model(retptr, ptr0, len0, addHeapObject(extend_special_tokens));
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
var r2 = getInt32Memory0()[retptr / 4 + 2];
if (r2) {
throw takeObject(r1);
}
return Tiktoken.__wrap(r0);
} finally {
wasm.__wbindgen_add_to_stack_pointer(16);
}
};
function handleError(f, args) {
try {
return f.apply(this, args);
} catch (e) {
wasm.__wbindgen_exn_store(addHeapObject(e));
}
}
var Tiktoken = class {
static __wrap(ptr) {
const obj = Object.create(Tiktoken.prototype);
obj.ptr = ptr;
return obj;
}
__destroy_into_raw() {
const ptr = this.ptr;
this.ptr = 0;
return ptr;
}
free() {
const ptr = this.__destroy_into_raw();
wasm.__wbg_tiktoken_free(ptr);
}
/**
* @param {string} tiktoken_bfe
* @param {any} special_tokens
* @param {string} pat_str
*/
constructor(tiktoken_bfe, special_tokens, pat_str) {
const ptr0 = passStringToWasm0(tiktoken_bfe, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len0 = WASM_VECTOR_LEN;
const ptr1 = passStringToWasm0(pat_str, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len1 = WASM_VECTOR_LEN;
const ret = wasm.tiktoken_new(ptr0, len0, addHeapObject(special_tokens), ptr1, len1);
return Tiktoken.__wrap(ret);
}
/**
* @returns {string | undefined}
*/
get name() {
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
wasm.tiktoken_name(retptr, this.ptr);
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
let v0;
if (r0 !== 0) {
v0 = getStringFromWasm0(r0, r1).slice();
wasm.__wbindgen_free(r0, r1 * 1);
}
return v0;
} finally {
wasm.__wbindgen_add_to_stack_pointer(16);
}
}
/**
* @param {string} text
* @param {any} allowed_special
* @param {any} disallowed_special
* @returns {Uint32Array}
*/
encode(text, allowed_special, disallowed_special) {
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
const ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len0 = WASM_VECTOR_LEN;
wasm.tiktoken_encode(retptr, this.ptr, ptr0, len0, addHeapObject(allowed_special), addHeapObject(disallowed_special));
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
var r2 = getInt32Memory0()[retptr / 4 + 2];
var r3 = getInt32Memory0()[retptr / 4 + 3];
if (r3) {
throw takeObject(r2);
}
var v1 = getArrayU32FromWasm0(r0, r1).slice();
wasm.__wbindgen_free(r0, r1 * 4);
return v1;
} finally {
wasm.__wbindgen_add_to_stack_pointer(16);
}
}
/**
* @param {string} text
* @returns {Uint32Array}
*/
encode_ordinary(text) {
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
const ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len0 = WASM_VECTOR_LEN;
wasm.tiktoken_encode_ordinary(retptr, this.ptr, ptr0, len0);
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
var v1 = getArrayU32FromWasm0(r0, r1).slice();
wasm.__wbindgen_free(r0, r1 * 4);
return v1;
} finally {
wasm.__wbindgen_add_to_stack_pointer(16);
}
}
/**
* @param {string} text
* @param {any} allowed_special
* @param {any} disallowed_special
* @returns {any}
*/
encode_with_unstable(text, allowed_special, disallowed_special) {
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
const ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len0 = WASM_VECTOR_LEN;
wasm.tiktoken_encode_with_unstable(retptr, this.ptr, ptr0, len0, addHeapObject(allowed_special), addHeapObject(disallowed_special));
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
var r2 = getInt32Memory0()[retptr / 4 + 2];
if (r2) {
throw takeObject(r1);
}
return takeObject(r0);
} finally {
wasm.__wbindgen_add_to_stack_pointer(16);
}
}
/**
* @param {Uint8Array} bytes
* @returns {number}
*/
encode_single_token(bytes2) {
const ptr0 = passArray8ToWasm0(bytes2, wasm.__wbindgen_malloc);
const len0 = WASM_VECTOR_LEN;
const ret = wasm.tiktoken_encode_single_token(this.ptr, ptr0, len0);
return ret >>> 0;
}
/**
* @param {Uint8Array} bytes
* @returns {Uint32Array}
*/
_encode_single_piece(bytes2) {
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
const ptr0 = passArray8ToWasm0(bytes2, wasm.__wbindgen_malloc);
const len0 = WASM_VECTOR_LEN;
wasm.tiktoken__encode_single_piece(retptr, this.ptr, ptr0, len0);
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
var v1 = getArrayU32FromWasm0(r0, r1).slice();
wasm.__wbindgen_free(r0, r1 * 4);
return v1;
} finally {
wasm.__wbindgen_add_to_stack_pointer(16);
}
}
/**
* @param {Uint32Array} tokens
* @returns {Uint8Array}
*/
decode(tokens) {
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
const ptr0 = passArray32ToWasm0(tokens, wasm.__wbindgen_malloc);
const len0 = WASM_VECTOR_LEN;
wasm.tiktoken_decode(retptr, this.ptr, ptr0, len0);
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
var v1 = getArrayU8FromWasm0(r0, r1).slice();
wasm.__wbindgen_free(r0, r1 * 1);
return v1;
} finally {
wasm.__wbindgen_add_to_stack_pointer(16);
}
}
/**
* @param {number} token
* @returns {Uint8Array}
*/
decode_single_token_bytes(token) {
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
wasm.tiktoken_decode_single_token_bytes(retptr, this.ptr, token);
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
var v0 = getArrayU8FromWasm0(r0, r1).slice();
wasm.__wbindgen_free(r0, r1 * 1);
return v0;
} finally {
wasm.__wbindgen_add_to_stack_pointer(16);
}
}
/**
* @returns {any}
*/
token_byte_values() {
const ret = wasm.tiktoken_token_byte_values(this.ptr);
return takeObject(ret);
}
};
module2.exports.Tiktoken = Tiktoken;
module2.exports.__wbindgen_object_drop_ref = function(arg0) {
takeObject(arg0);
};
module2.exports.__wbindgen_string_get = function(arg0, arg1) {
const obj = getObject(arg1);
const ret = typeof obj === "string" ? obj : void 0;
var ptr0 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
getInt32Memory0()[arg0 / 4 + 1] = len0;
getInt32Memory0()[arg0 / 4 + 0] = ptr0;
};
module2.exports.__wbindgen_error_new = function(arg0, arg1) {
const ret = new Error(getStringFromWasm0(arg0, arg1));
return addHeapObject(ret);
};
module2.exports.__wbg_parse_3ac95b51fc312db8 = function() {
return handleError(function(arg0, arg1) {
const ret = JSON.parse(getStringFromWasm0(arg0, arg1));
return addHeapObject(ret);
}, arguments);
};
module2.exports.__wbindgen_is_undefined = function(arg0) {
const ret = getObject(arg0) === void 0;
return ret;
};
module2.exports.__wbg_stringify_029a979dfb73aa17 = function() {
return handleError(function(arg0) {
const ret = JSON.stringify(getObject(arg0));
return addHeapObject(ret);
}, arguments);
};
module2.exports.__wbindgen_throw = function(arg0, arg1) {
throw new Error(getStringFromWasm0(arg0, arg1));
};
var path = require("path").join(__dirname, "_tiktoken_bg.wasm");
var bytes = require("fs").readFileSync(path);
var wasmModule = new WebAssembly.Module(bytes);
var wasmInstance = new WebAssembly.Instance(wasmModule, imports);
wasm = wasmInstance.exports;
module2.exports.__wasm = wasm;
}
});
// src/index.ts

@@ -42,9 +697,369 @@ var src_exports = {};

// src/chatgpt-api.ts
var import_keyv = __toESM(require("keyv"));
var import_p_timeout = __toESM(require("p-timeout"));
var import_quick_lru = __toESM(require("quick-lru"));
var import_uuid = require("uuid");
var import_keyv = __toESM(require_src());
// node_modules/.pnpm/p-timeout@6.1.1/node_modules/p-timeout/index.js
var TimeoutError = class extends Error {
constructor(message) {
super(message);
this.name = "TimeoutError";
}
};
var AbortError = class extends Error {
constructor(message) {
super();
this.name = "AbortError";
this.message = message;
}
};
var getDOMException = (errorMessage) => globalThis.DOMException === void 0 ? new AbortError(errorMessage) : new DOMException(errorMessage);
var getAbortedReason = (signal) => {
const reason = signal.reason === void 0 ? getDOMException("This operation was aborted.") : signal.reason;
return reason instanceof Error ? reason : getDOMException(reason);
};
function pTimeout(promise, options) {
const {
milliseconds,
fallback,
message,
customTimers = { setTimeout, clearTimeout }
} = options;
let timer;
const cancelablePromise = new Promise((resolve, reject) => {
if (typeof milliseconds !== "number" || Math.sign(milliseconds) !== 1) {
throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${milliseconds}\``);
}
if (milliseconds === Number.POSITIVE_INFINITY) {
resolve(promise);
return;
}
if (options.signal) {
const { signal } = options;
if (signal.aborted) {
reject(getAbortedReason(signal));
}
signal.addEventListener("abort", () => {
reject(getAbortedReason(signal));
});
}
const timeoutError = new TimeoutError();
timer = customTimers.setTimeout.call(void 0, () => {
if (fallback) {
try {
resolve(fallback());
} catch (error) {
reject(error);
}
return;
}
if (typeof promise.cancel === "function") {
promise.cancel();
}
if (message === false) {
resolve();
} else if (message instanceof Error) {
reject(message);
} else {
timeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`;
reject(timeoutError);
}
}, milliseconds);
(async () => {
try {
resolve(await promise);
} catch (error) {
reject(error);
} finally {
customTimers.clearTimeout.call(void 0, timer);
}
})();
});
cancelablePromise.clear = () => {
customTimers.clearTimeout.call(void 0, timer);
timer = void 0;
};
return cancelablePromise;
}
// node_modules/.pnpm/quick-lru@6.1.1/node_modules/quick-lru/index.js
var QuickLRU = class extends Map {
constructor(options = {}) {
super();
if (!(options.maxSize && options.maxSize > 0)) {
throw new TypeError("`maxSize` must be a number greater than 0");
}
if (typeof options.maxAge === "number" && options.maxAge === 0) {
throw new TypeError("`maxAge` must be a number greater than 0");
}
this.maxSize = options.maxSize;
this.maxAge = options.maxAge || Number.POSITIVE_INFINITY;
this.onEviction = options.onEviction;
this.cache = /* @__PURE__ */ new Map();
this.oldCache = /* @__PURE__ */ new Map();
this._size = 0;
}
// TODO: Use private class methods when targeting Node.js 16.
_emitEvictions(cache) {
if (typeof this.onEviction !== "function") {
return;
}
for (const [key, item] of cache) {
this.onEviction(key, item.value);
}
}
_deleteIfExpired(key, item) {
if (typeof item.expiry === "number" && item.expiry <= Date.now()) {
if (typeof this.onEviction === "function") {
this.onEviction(key, item.value);
}
return this.delete(key);
}
return false;
}
_getOrDeleteIfExpired(key, item) {
const deleted = this._deleteIfExpired(key, item);
if (deleted === false) {
return item.value;
}
}
_getItemValue(key, item) {
return item.expiry ? this._getOrDeleteIfExpired(key, item) : item.value;
}
_peek(key, cache) {
const item = cache.get(key);
return this._getItemValue(key, item);
}
_set(key, value) {
this.cache.set(key, value);
this._size++;
if (this._size >= this.maxSize) {
this._size = 0;
this._emitEvictions(this.oldCache);
this.oldCache = this.cache;
this.cache = /* @__PURE__ */ new Map();
}
}
_moveToRecent(key, item) {
this.oldCache.delete(key);
this._set(key, item);
}
*_entriesAscending() {
for (const item of this.oldCache) {
const [key, value] = item;
if (!this.cache.has(key)) {
const deleted = this._deleteIfExpired(key, value);
if (deleted === false) {
yield item;
}
}
}
for (const item of this.cache) {
const [key, value] = item;
const deleted = this._deleteIfExpired(key, value);
if (deleted === false) {
yield item;
}
}
}
get(key) {
if (this.cache.has(key)) {
const item = this.cache.get(key);
return this._getItemValue(key, item);
}
if (this.oldCache.has(key)) {
const item = this.oldCache.get(key);
if (this._deleteIfExpired(key, item) === false) {
this._moveToRecent(key, item);
return item.value;
}
}
}
set(key, value, { maxAge = this.maxAge } = {}) {
const expiry = typeof maxAge === "number" && maxAge !== Number.POSITIVE_INFINITY ? Date.now() + maxAge : void 0;
if (this.cache.has(key)) {
this.cache.set(key, {
value,
expiry
});
} else {
this._set(key, { value, expiry });
}
}
has(key) {
if (this.cache.has(key)) {
return !this._deleteIfExpired(key, this.cache.get(key));
}
if (this.oldCache.has(key)) {
return !this._deleteIfExpired(key, this.oldCache.get(key));
}
return false;
}
peek(key) {
if (this.cache.has(key)) {
return this._peek(key, this.cache);
}
if (this.oldCache.has(key)) {
return this._peek(key, this.oldCache);
}
}
delete(key) {
const deleted = this.cache.delete(key);
if (deleted) {
this._size--;
}
return this.oldCache.delete(key) || deleted;
}
clear() {
this.cache.clear();
this.oldCache.clear();
this._size = 0;
}
resize(newSize) {
if (!(newSize && newSize > 0)) {
throw new TypeError("`maxSize` must be a number greater than 0");
}
const items = [...this._entriesAscending()];
const removeCount = items.length - newSize;
if (removeCount < 0) {
this.cache = new Map(items);
this.oldCache = /* @__PURE__ */ new Map();
this._size = items.length;
} else {
if (removeCount > 0) {
this._emitEvictions(items.slice(0, removeCount));
}
this.oldCache = new Map(items.slice(removeCount));
this.cache = /* @__PURE__ */ new Map();
this._size = 0;
}
this.maxSize = newSize;
}
*keys() {
for (const [key] of this) {
yield key;
}
}
*values() {
for (const [, value] of this) {
yield value;
}
}
*[Symbol.iterator]() {
for (const item of this.cache) {
const [key, value] = item;
const deleted = this._deleteIfExpired(key, value);
if (deleted === false) {
yield [key, value.value];
}
}
for (const item of this.oldCache) {
const [key, value] = item;
if (!this.cache.has(key)) {
const deleted = this._deleteIfExpired(key, value);
if (deleted === false) {
yield [key, value.value];
}
}
}
}
*entriesDescending() {
let items = [...this.cache];
for (let i = items.length - 1; i >= 0; --i) {
const item = items[i];
const [key, value] = item;
const deleted = this._deleteIfExpired(key, value);
if (deleted === false) {
yield [key, value.value];
}
}
items = [...this.oldCache];
for (let i = items.length - 1; i >= 0; --i) {
const item = items[i];
const [key, value] = item;
if (!this.cache.has(key)) {
const deleted = this._deleteIfExpired(key, value);
if (deleted === false) {
yield [key, value.value];
}
}
}
}
*entriesAscending() {
for (const [key, value] of this._entriesAscending()) {
yield [key, value.value];
}
}
get size() {
if (!this._size) {
return this.oldCache.size;
}
let oldCacheSize = 0;
for (const key of this.oldCache.keys()) {
if (!this.cache.has(key)) {
oldCacheSize++;
}
}
return Math.min(this._size + oldCacheSize, this.maxSize);
}
entries() {
return this.entriesAscending();
}
forEach(callbackFunction, thisArgument = this) {
for (const [key, value] of this.entriesAscending()) {
callbackFunction.call(thisArgument, value, key, this);
}
}
get [Symbol.toStringTag]() {
return JSON.stringify([...this.entriesAscending()]);
}
};
// node_modules/.pnpm/uuid@9.0.0/node_modules/uuid/dist/esm-node/rng.js
var import_crypto = __toESM(require("crypto"));
var rnds8Pool = new Uint8Array(256);
var poolPtr = rnds8Pool.length;
function rng() {
if (poolPtr > rnds8Pool.length - 16) {
import_crypto.default.randomFillSync(rnds8Pool);
poolPtr = 0;
}
return rnds8Pool.slice(poolPtr, poolPtr += 16);
}
// node_modules/.pnpm/uuid@9.0.0/node_modules/uuid/dist/esm-node/stringify.js
var byteToHex = [];
for (let i = 0; i < 256; ++i) {
byteToHex.push((i + 256).toString(16).slice(1));
}
function unsafeStringify(arr, offset = 0) {
return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
}
// node_modules/.pnpm/uuid@9.0.0/node_modules/uuid/dist/esm-node/native.js
var import_crypto2 = __toESM(require("crypto"));
var native_default = {
randomUUID: import_crypto2.default.randomUUID
};
// node_modules/.pnpm/uuid@9.0.0/node_modules/uuid/dist/esm-node/v4.js
function v4(options, buf, offset) {
if (native_default.randomUUID && !buf && !options) {
return native_default.randomUUID();
}
options = options || {};
const rnds = options.random || (options.rng || rng)();
rnds[6] = rnds[6] & 15 | 64;
rnds[8] = rnds[8] & 63 | 128;
if (buf) {
offset = offset || 0;
for (let i = 0; i < 16; ++i) {
buf[offset + i] = rnds[i];
}
return buf;
}
return unsafeStringify(rnds);
}
var v4_default = v4;
// src/tokenizer.ts
var import_tiktoken = require("@dqbd/tiktoken");
var import_tiktoken = __toESM(require_tiktoken());
var tokenizer = (0, import_tiktoken.get_encoding)("cl100k_base");

@@ -65,4 +1080,121 @@ function encode(input) {

// src/fetch-sse.ts
var import_eventsource_parser = require("eventsource-parser");
// node_modules/.pnpm/eventsource-parser@0.0.5/node_modules/eventsource-parser/dist/index.mjs
function createParser(onParse) {
let isFirstChunk;
let buffer;
let startingPosition;
let startingFieldLength;
let eventId;
let eventName;
let data;
reset();
return {
feed,
reset
};
function reset() {
isFirstChunk = true;
buffer = "";
startingPosition = 0;
startingFieldLength = -1;
eventId = void 0;
eventName = void 0;
data = "";
}
function feed(chunk) {
buffer = buffer ? buffer + chunk : chunk;
if (isFirstChunk && hasBom(buffer)) {
buffer = buffer.slice(BOM.length);
}
isFirstChunk = false;
const length = buffer.length;
let position = 0;
let discardTrailingNewline = false;
while (position < length) {
if (discardTrailingNewline) {
if (buffer[position] === "\n") {
++position;
}
discardTrailingNewline = false;
}
let lineLength = -1;
let fieldLength = startingFieldLength;
let character;
for (let index = startingPosition; lineLength < 0 && index < length; ++index) {
character = buffer[index];
if (character === ":" && fieldLength < 0) {
fieldLength = index - position;
} else if (character === "\r") {
discardTrailingNewline = true;
lineLength = index - position;
} else if (character === "\n") {
lineLength = index - position;
}
}
if (lineLength < 0) {
startingPosition = length - position;
startingFieldLength = fieldLength;
break;
} else {
startingPosition = 0;
startingFieldLength = -1;
}
parseEventStreamLine(buffer, position, fieldLength, lineLength);
position += lineLength + 1;
}
if (position === length) {
buffer = "";
} else if (position > 0) {
buffer = buffer.slice(position);
}
}
function parseEventStreamLine(lineBuffer, index, fieldLength, lineLength) {
if (lineLength === 0) {
if (data.length > 0) {
onParse({
type: "event",
id: eventId,
event: eventName || void 0,
data: data.slice(0, -1)
});
data = "";
eventId = void 0;
}
eventName = void 0;
return;
}
const noValue = fieldLength < 0;
const field = lineBuffer.slice(index, index + (noValue ? lineLength : fieldLength));
let step = 0;
if (noValue) {
step = lineLength;
} else if (lineBuffer[index + fieldLength + 1] === " ") {
step = fieldLength + 2;
} else {
step = fieldLength + 1;
}
const position = index + step;
const valueLength = lineLength - step;
const value = lineBuffer.slice(position, position + valueLength).toString();
if (field === "data") {
data += value ? "".concat(value, "\n") : "\n";
} else if (field === "event") {
eventName = value;
} else if (field === "id" && !value.includes("\0")) {
eventId = value;
} else if (field === "retry") {
const retry = parseInt(value, 10);
if (!Number.isNaN(retry)) {
onParse({
type: "reconnect-interval",
value: retry
});
}
}
}
}
var BOM = [239, 187, 191];
function hasBom(buffer) {
return BOM.every((charCode, index) => buffer.charCodeAt(index) === charCode);
}

@@ -102,3 +1234,3 @@ // src/stream-async-iterable.ts

}
const parser = (0, import_eventsource_parser.createParser)((event) => {
const parser = createParser((event) => {
if (event.type === "event") {

@@ -173,3 +1305,3 @@ onMessage(event.data);

if (this._systemMessage === void 0) {
const currentDate = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
const currentDate = new Date().toISOString().split("T")[0];
this._systemMessage = `You are ChatGPT, a large language model trained by OpenAI. Answer as concisely as possible.

@@ -187,3 +1319,3 @@ Knowledge cutoff: 2021-09-01

this._messageStore = new import_keyv.default({
store: new import_quick_lru.default({ maxSize: 1e4 })
store: new QuickLRU({ maxSize: 1e4 })
});

@@ -224,3 +1356,3 @@ }

parentMessageId,
messageId = (0, import_uuid.v4)(),
messageId = v4_default(),
timeoutMs,

@@ -249,3 +1381,3 @@ onProgress,

role: "assistant",
id: (0, import_uuid.v4)(),
id: v4_default(),
parentMessageId: messageId,

@@ -364,3 +1496,3 @@ text: ""

}
return (0, import_p_timeout.default)(responseP, {
return pTimeout(responseP, {
milliseconds: timeoutMs,

@@ -466,6 +1598,2 @@ message: "OpenAI timed out waiting for response"

// src/chatgpt-unofficial-proxy-api.ts
var import_p_timeout2 = __toESM(require("p-timeout"));
var import_uuid2 = require("uuid");
// src/utils.ts

@@ -559,4 +1687,4 @@ var uuidv4Re = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;

conversationId,
parentMessageId = (0, import_uuid2.v4)(),
messageId = (0, import_uuid2.v4)(),
parentMessageId = v4_default(),
messageId = v4_default(),
action = "next",

@@ -592,3 +1720,3 @@ timeoutMs,

role: "assistant",
id: (0, import_uuid2.v4)(),
id: v4_default(),
parentMessageId: messageId,

@@ -660,3 +1788,3 @@ conversationId,

}
return (0, import_p_timeout2.default)(responseP, {
return pTimeout(responseP, {
milliseconds: timeoutMs,

@@ -677,2 +1805,1 @@ message: "ChatGPT timed out waiting for response"

});
//# sourceMappingURL=index.js.map

2

package.json
{
"name": "chatgpt-api-cjs",
"version": "5.0.10",
"version": "5.0.11",
"description": "Node.js client for the official ChatGPT API.(commonjs version)",

@@ -5,0 +5,0 @@ "author": "wangfengyuan",

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc