@datastax/astra-db-ts
Advanced tools
Comparing version 1.4.1 to 1.5.0
@@ -18,3 +18,5 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.reviver = exports.replacer = exports.DataAPIHttpClient = exports.EmissionStrategy = void 0; | ||
exports.DataAPIHttpClient = exports.EmissionStrategy = void 0; | ||
exports.replacer = replacer; | ||
exports.reviver = reviver; | ||
const api_1 = require("../../api"); | ||
@@ -36,4 +38,4 @@ const data_api_1 = require("../../data-api"); | ||
}, | ||
emitCommandSucceeded(info, resp, started) { | ||
emitter.emit('commandSucceeded', new events_1.CommandSucceededEvent(info, resp, started)); | ||
emitCommandSucceeded(info, resp, warnings, started) { | ||
emitter.emit('commandSucceeded', new events_1.CommandSucceededEvent(info, resp, warnings, started)); | ||
}, | ||
@@ -48,4 +50,4 @@ }), | ||
}, | ||
emitCommandSucceeded(info, resp, started) { | ||
emitter.emit('adminCommandSucceeded', new devops_1.AdminCommandSucceededEvent(adaptInfo4Devops(info), true, resp, started)); | ||
emitCommandSucceeded(info, resp, warnings, started) { | ||
emitter.emit('adminCommandSucceeded', new devops_1.AdminCommandSucceededEvent(adaptInfo4Devops(info), true, resp, warnings, started)); | ||
}, | ||
@@ -69,3 +71,3 @@ }), | ||
}); | ||
Object.defineProperty(this, "namespace", { | ||
Object.defineProperty(this, "keyspace", { | ||
enumerable: true, | ||
@@ -89,3 +91,3 @@ configurable: true, | ||
_DataAPIHttpClient_props.set(this, void 0); | ||
this.namespace = props.namespace; | ||
this.keyspace = props.keyspace; | ||
__classPrivateFieldSet(this, _DataAPIHttpClient_props, props, "f"); | ||
@@ -95,7 +97,7 @@ this.maxTimeMS = this.fetchCtx.maxTimeMS ?? api_1.DEFAULT_TIMEOUT; | ||
} | ||
forCollection(namespace, collection, opts) { | ||
forCollection(keyspace, collection, opts) { | ||
const clone = new DataAPIHttpClient({ | ||
...__classPrivateFieldGet(this, _DataAPIHttpClient_props, "f"), | ||
embeddingHeaders: embedding_providers_1.EmbeddingHeadersProvider.parseHeaders(opts?.embeddingApiKey), | ||
namespace: { ref: namespace }, | ||
keyspace: { ref: keyspace }, | ||
}); | ||
@@ -128,3 +130,3 @@ clone.collection = collection; | ||
collection: options?.collection, | ||
namespace: options?.namespace, | ||
keyspace: (0, common_1.resolveKeyspace)(options, true), | ||
command: command, | ||
@@ -137,9 +139,9 @@ }); | ||
info.collection || (info.collection = this.collection); | ||
if (info.namespace !== null) { | ||
info.namespace || (info.namespace = this.namespace?.ref); | ||
if ((0, common_1.isNullish)(info.namespace)) { | ||
throw new Error('Db is missing a required namespace; be sure to set one w/ client.db(..., { namespace }), or db.useNamespace()'); | ||
if (info.keyspace !== null) { | ||
info.keyspace || (info.keyspace = this.keyspace?.ref); | ||
if ((0, common_1.isNullish)(info.keyspace)) { | ||
throw new Error('Db is missing a required keyspace; be sure to set one w/ client.db(..., { keyspace }), or db.useKeyspace()'); | ||
} | ||
} | ||
const keyspacePath = info.namespace ? `/${info.namespace}` : ''; | ||
const keyspacePath = info.keyspace ? `/${info.keyspace}` : ''; | ||
const collectionPath = info.collection ? `/${info.collection}` : ''; | ||
@@ -161,8 +163,10 @@ info.url += keyspacePath + collectionPath; | ||
const data = resp.body ? JSON.parse(resp.body, reviver) : {}; | ||
const warnings = data?.status?.warnings ?? []; | ||
delete data?.status?.warnings; | ||
if (data.errors && data.errors.length > 0 && data.errors[0]?.errorCode === 'COLLECTION_NOT_EXIST') { | ||
const name = data.errors[0]?.message.split(': ')[1]; | ||
throw new errors_1.CollectionNotFoundError(info.namespace ?? '<unknown>', name); | ||
throw new errors_1.CollectionNotFoundError(info.keyspace ?? '<unknown>', name); | ||
} | ||
if (data.errors && data.errors.length > 0) { | ||
throw (0, errors_1.mkRespErrorFromResponse)(data_api_1.DataAPIResponseError, info.command, data); | ||
throw (0, errors_1.mkRespErrorFromResponse)(data_api_1.DataAPIResponseError, info.command, data, warnings); | ||
} | ||
@@ -175,3 +179,3 @@ const respData = { | ||
if (this.monitorCommands) { | ||
this.emissionStrategy.emitCommandSucceeded(info, respData, started); | ||
this.emissionStrategy.emitCommandSucceeded(info, respData, warnings, started); | ||
} | ||
@@ -204,3 +208,2 @@ return respData; | ||
} | ||
exports.replacer = replacer; | ||
function reviver(_, value) { | ||
@@ -221,3 +224,2 @@ if (!value) { | ||
} | ||
exports.reviver = reviver; | ||
const mkAuthHeaderProvider = (tp) => () => { | ||
@@ -224,0 +226,0 @@ const token = tp.getToken(); |
@@ -12,2 +12,3 @@ "use strict"; | ||
const devops_1 = require("../../devops"); | ||
const common_1 = require("../../common"); | ||
class DevOpsAPIHttpClient extends http_client_1.HttpClient { | ||
@@ -34,3 +35,3 @@ constructor(opts) { | ||
}); | ||
const data = resp.body ? JSON.parse(resp.body) : undefined; | ||
const data = resp.body ? (0, common_1.jsonTryParse)(resp.body, undefined) : undefined; | ||
if (resp.status >= 400) { | ||
@@ -40,3 +41,3 @@ throw new errors_1.DevOpsAPIResponseError(resp, data); | ||
if (this.monitorCommands && !isLongRunning) { | ||
this.emitter.emit('adminCommandSucceeded', new devops_1.AdminCommandSucceededEvent(req, false, data, started)); | ||
this.emitter.emit('adminCommandSucceeded', new devops_1.AdminCommandSucceededEvent(req, false, data, [], started)); | ||
} | ||
@@ -72,3 +73,3 @@ return { | ||
if (this.monitorCommands && isLongRunning) { | ||
this.emitter.emit('adminCommandSucceeded', new devops_1.AdminCommandSucceededEvent(req, true, resp, started)); | ||
this.emitter.emit('adminCommandSucceeded', new devops_1.AdminCommandSucceededEvent(req, true, resp, [], started)); | ||
} | ||
@@ -75,0 +76,0 @@ return resp; |
@@ -5,3 +5,5 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.buildUserAgent = exports.hrTimeMs = exports.HttpClient = void 0; | ||
exports.HttpClient = void 0; | ||
exports.hrTimeMs = hrTimeMs; | ||
exports.buildUserAgent = buildUserAgent; | ||
const constants_1 = require("../../api/constants"); | ||
@@ -94,3 +96,2 @@ class HttpClient { | ||
} | ||
exports.hrTimeMs = hrTimeMs; | ||
function buildUserAgent(caller) { | ||
@@ -107,2 +108,1 @@ const callers = ((!caller) | ||
} | ||
exports.buildUserAgent = buildUserAgent; |
@@ -5,3 +5,3 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.DEFAULT_DATA_API_PATHS = exports.DEFAULT_DEVOPS_API_ENDPOINT = exports.DEFAULT_DEVOPS_API_AUTH_HEADER = exports.DEFAULT_DATA_API_AUTH_HEADER = exports.DEFAULT_TIMEOUT = exports.DEFAULT_NAMESPACE = exports.HttpMethods = exports.CLIENT_USER_AGENT = exports.RAGSTACK_REQUESTED_WITH = void 0; | ||
exports.DEFAULT_DATA_API_PATHS = exports.DEFAULT_DEVOPS_API_ENDPOINTS = exports.DEFAULT_DEVOPS_API_AUTH_HEADER = exports.DEFAULT_DATA_API_AUTH_HEADER = exports.DEFAULT_TIMEOUT = exports.DEFAULT_KEYSPACE = exports.HttpMethods = exports.CLIENT_USER_AGENT = exports.RAGSTACK_REQUESTED_WITH = void 0; | ||
const version_1 = require("../version"); | ||
@@ -16,3 +16,3 @@ exports.RAGSTACK_REQUESTED_WITH = (() => { | ||
} | ||
catch (e) { | ||
catch (_) { | ||
return ''; | ||
@@ -33,7 +33,11 @@ } | ||
}; | ||
exports.DEFAULT_NAMESPACE = 'default_keyspace'; | ||
exports.DEFAULT_KEYSPACE = 'default_keyspace'; | ||
exports.DEFAULT_TIMEOUT = 30000; | ||
exports.DEFAULT_DATA_API_AUTH_HEADER = 'Token'; | ||
exports.DEFAULT_DEVOPS_API_AUTH_HEADER = 'Authorization'; | ||
exports.DEFAULT_DEVOPS_API_ENDPOINT = 'https://api.astra.datastax.com/v2'; | ||
exports.DEFAULT_DEVOPS_API_ENDPOINTS = { | ||
prod: 'https://api.astra.datastax.com/v2', | ||
test: 'https://api.test.cloud.datastax.com/v2', | ||
dev: 'https://api.dev.cloud.datastax.com/v2', | ||
}; | ||
exports.DEFAULT_DATA_API_PATHS = { | ||
@@ -40,0 +44,0 @@ astra: 'api/json/v1', |
@@ -29,3 +29,3 @@ "use strict"; | ||
try { | ||
const [indirectRequire] = [require].map(x => Math.random() > 10 ? null : x); | ||
const [indirectRequire] = [require].map(x => isNaN(Math.random()) ? null : x); | ||
const fetchH2 = validateFetchH2(options?.fetchH2) ?? indirectRequire('fetch-h2'); | ||
@@ -50,3 +50,3 @@ this._http1 = fetchH2.context({ | ||
} | ||
async fetch(info) { | ||
async fetch(info) { | ||
const init = info; | ||
@@ -73,3 +73,3 @@ try { | ||
} | ||
async close() { | ||
async close() { | ||
await this._preferred.disconnectAll(); | ||
@@ -89,3 +89,3 @@ await this._http1.disconnectAll(); | ||
if (!(prop in fetchH2)) { | ||
throw new Error(`fetchH2 missing the required ${prop} property`); | ||
throw new TypeError(`fetchH2 missing the required '${prop}' property`); | ||
} | ||
@@ -92,0 +92,0 @@ } |
@@ -8,3 +8,3 @@ "use strict"; | ||
class FetchNative { | ||
async fetch(info) { | ||
async fetch(info) { | ||
try { | ||
@@ -32,7 +32,10 @@ const init = info; | ||
} | ||
if (e instanceof TypeError && e.message === 'fetch failed' && 'cause' in e) { | ||
throw e.cause; | ||
} | ||
throw e; | ||
} | ||
} | ||
async close() { } | ||
async close() { } | ||
} | ||
exports.FetchNative = FetchNative; |
@@ -31,3 +31,3 @@ "use strict"; | ||
} | ||
catch (e) { | ||
catch (_) { | ||
throw new Error(`\`${version_1.LIB_NAME}\` requires the \`events\` module to be available for usage. Please provide a polyfill (e.g. the \`events\` package) or use a compatible environment.`); | ||
@@ -146,3 +146,3 @@ } | ||
(0, utils_1.validateOption)('httpOptions.maxTimeMS', opts.maxTimeMS, 'number'); | ||
if (opts.client === 'default' || (0, common_1.isNullish)(opts.client)) { | ||
if (opts.client === 'default' || !opts.client) { | ||
(0, utils_1.validateOption)('httpOptions.preferHttp2', opts.preferHttp2, 'boolean'); | ||
@@ -149,0 +149,0 @@ (0, utils_1.validateOption)('httpOptions.http1 options', opts.http1, 'object', false, (http1) => { |
@@ -17,4 +17,5 @@ "use strict"; | ||
this.rootCause = rootCause; | ||
this.name = 'FailedToLoadDefaultClientError'; | ||
} | ||
} | ||
exports.FailedToLoadDefaultClientError = FailedToLoadDefaultClientError; |
@@ -5,3 +5,6 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.validateDataAPIEnv = exports.isNullish = void 0; | ||
exports.isNullish = isNullish; | ||
exports.validateDataAPIEnv = validateDataAPIEnv; | ||
exports.jsonTryParse = jsonTryParse; | ||
exports.resolveKeyspace = resolveKeyspace; | ||
const constants_1 = require("../common/constants"); | ||
@@ -11,3 +14,2 @@ function isNullish(t) { | ||
} | ||
exports.isNullish = isNullish; | ||
function validateDataAPIEnv(env) { | ||
@@ -18,2 +20,14 @@ if (!isNullish(env) && !constants_1.DataAPIEnvironments.includes(env)) { | ||
} | ||
exports.validateDataAPIEnv = validateDataAPIEnv; | ||
function jsonTryParse(json, otherwise, reviver) { | ||
try { | ||
return JSON.parse(json, reviver); | ||
} | ||
catch (_) { | ||
return otherwise; | ||
} | ||
} | ||
function resolveKeyspace(obj, nullBypass) { | ||
return (nullBypass) | ||
? (obj?.keyspace !== undefined) ? obj?.keyspace : obj?.namespace | ||
: obj?.keyspace ?? obj?.namespace ?? undefined; | ||
} |
@@ -26,2 +26,3 @@ "use strict"; | ||
const types_1 = require("../data-api/types"); | ||
const common_1 = require("../common"); | ||
class Collection { | ||
@@ -37,2 +38,8 @@ constructor(db, httpClient, name, opts) { | ||
}); | ||
Object.defineProperty(this, "keyspace", { | ||
enumerable: true, | ||
configurable: true, | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, "namespace", { | ||
@@ -48,7 +55,11 @@ enumerable: true, | ||
}); | ||
Object.defineProperty(this, 'keyspace', { | ||
value: (0, common_1.resolveKeyspace)(opts) ?? db.keyspace, | ||
writable: false, | ||
}); | ||
Object.defineProperty(this, 'namespace', { | ||
value: opts?.namespace ?? db.namespace, | ||
value: this.keyspace, | ||
writable: false, | ||
}); | ||
__classPrivateFieldSet(this, _Collection_httpClient, httpClient.forCollection(this.namespace, this.collectionName, opts), "f"); | ||
__classPrivateFieldSet(this, _Collection_httpClient, httpClient.forCollection(this.keyspace, this.collectionName, opts), "f"); | ||
__classPrivateFieldSet(this, _Collection_db, db, "f"); | ||
@@ -154,3 +165,3 @@ } | ||
resp = await __classPrivateFieldGet(this, _Collection_httpClient, "f").executeCommand(command, { timeoutManager }); | ||
command.updateMany.options.pagingState = resp.status?.nextPageState; | ||
command.updateMany.options.pageState = resp.status?.nextPageState; | ||
commonResult.modifiedCount += resp.status?.modifiedCount ?? 0; | ||
@@ -168,3 +179,3 @@ commonResult.matchedCount += resp.status?.matchedCount ?? 0; | ||
commonResult.upsertedCount = desc.rawResponse.status?.upsertedCount ?? 0; | ||
throw (0, errors_1.mkRespErrorFromResponse)(errors_1.UpdateManyError, command, desc.rawResponse, commonResult); | ||
throw (0, errors_1.mkRespErrorFromResponse)(errors_1.UpdateManyError, command, desc.rawResponse, { partialResult: commonResult }); | ||
} | ||
@@ -224,3 +235,3 @@ return (resp.status?.upsertedId) | ||
} | ||
async deleteMany(filter = {}, options) { | ||
async deleteMany(filter, options) { | ||
const command = { | ||
@@ -243,3 +254,7 @@ deleteMany: { filter }, | ||
const desc = e.detailedErrorDescriptors[0]; | ||
throw (0, errors_1.mkRespErrorFromResponse)(errors_1.DeleteManyError, command, desc.rawResponse, { deletedCount: numDeleted + (desc.rawResponse.status?.deletedCount ?? 0) }); | ||
throw (0, errors_1.mkRespErrorFromResponse)(errors_1.DeleteManyError, command, desc.rawResponse, { | ||
partialResult: { | ||
deletedCount: numDeleted + (desc.rawResponse.status?.deletedCount ?? 0), | ||
}, | ||
}); | ||
} | ||
@@ -254,3 +269,3 @@ return { | ||
find(filter, options) { | ||
return new cursor_1.FindCursor(this.namespace, __classPrivateFieldGet(this, _Collection_httpClient, "f"), filter, coalesceVectorSpecialsIntoSort(options)); | ||
return new cursor_1.FindCursor(this.keyspace, __classPrivateFieldGet(this, _Collection_httpClient, "f"), filter, coalesceVectorSpecialsIntoSort(options)); | ||
} | ||
@@ -304,2 +319,5 @@ async findOne(filter, options) { | ||
} | ||
if (upperBound < 0) { | ||
throw new Error('upperBound must be >= 0'); | ||
} | ||
const resp = await __classPrivateFieldGet(this, _Collection_httpClient, "f").executeCommand(command, options); | ||
@@ -405,3 +423,3 @@ if (resp.status?.moreData) { | ||
if (!collection) { | ||
throw new errors_1.CollectionNotFoundError(this.namespace, this.collectionName); | ||
throw new errors_1.CollectionNotFoundError(this.keyspace, this.collectionName); | ||
} | ||
@@ -411,3 +429,3 @@ return collection.options; | ||
async drop(options) { | ||
return await __classPrivateFieldGet(this, _Collection_db, "f").dropCollection(this.collectionName, options); | ||
return await __classPrivateFieldGet(this, _Collection_db, "f").dropCollection(this.collectionName, { keyspace: this.keyspace, ...options }); | ||
} | ||
@@ -443,14 +461,14 @@ get _httpClient() { | ||
const slice = documents.slice(i, i + chunkSize); | ||
try { | ||
const inserted = await insertMany(httpClient, slice, true, timeoutManager); | ||
insertedIds.push(...inserted); | ||
const [_docResp, inserted, errDesc] = await insertMany(httpClient, slice, true, timeoutManager); | ||
insertedIds.push(...inserted); | ||
if (errDesc) { | ||
throw (0, errors_1.mkRespErrorFromResponse)(errors_1.InsertManyError, errDesc.command, errDesc.rawResponse, { | ||
partialResult: { | ||
insertedIds: insertedIds, | ||
insertedCount: insertedIds.length, | ||
}, | ||
// documentResponses: docResp, | ||
// failedCount: docResp.length - insertedIds.length, | ||
}); | ||
} | ||
catch (e) { | ||
if (!(e instanceof errors_1.DataAPIResponseError)) { | ||
throw e; | ||
} | ||
const desc = e.detailedErrorDescriptors[0]; | ||
insertedIds.push(...desc.rawResponse.status?.insertedIds ?? []); | ||
throw (0, errors_1.mkRespErrorFromResponse)(errors_1.InsertManyError, desc.command, desc.rawResponse, { insertedIds: insertedIds, insertedCount: insertedIds.length }); | ||
} | ||
} | ||
@@ -464,2 +482,3 @@ return insertedIds; | ||
const failRaw = []; | ||
const docResps = []; | ||
const workers = Array.from({ length: concurrency }, async () => { | ||
@@ -474,16 +493,9 @@ while (masterIndex < documents.length) { | ||
const slice = documents.slice(localI, endIdx); | ||
try { | ||
const inserted = await insertMany(httpClient, slice, false, timeoutManager); | ||
insertedIds.push(...inserted); | ||
const [docResp, inserted, errDesc] = await insertMany(httpClient, slice, false, timeoutManager); | ||
insertedIds.push(...inserted); | ||
docResps.push(...docResp); | ||
if (errDesc) { | ||
failCommands.push(errDesc.command); | ||
failRaw.push(errDesc.rawResponse); | ||
} | ||
catch (e) { | ||
if (!(e instanceof errors_1.DataAPIResponseError)) { | ||
throw e; | ||
} | ||
const desc = e.detailedErrorDescriptors[0]; | ||
const justInserted = desc.rawResponse.status?.insertedIds ?? []; | ||
insertedIds.push(...justInserted); | ||
failCommands.push(desc.command); | ||
failRaw.push(desc.rawResponse); | ||
} | ||
} | ||
@@ -493,3 +505,10 @@ }); | ||
if (failCommands.length > 0) { | ||
throw (0, errors_1.mkRespErrorFromResponses)(errors_1.InsertManyError, failCommands, failRaw, { insertedIds: insertedIds, insertedCount: insertedIds.length }); | ||
throw (0, errors_1.mkRespErrorFromResponses)(errors_1.InsertManyError, failCommands, failRaw, { | ||
partialResult: { | ||
insertedIds: insertedIds, | ||
insertedCount: insertedIds.length, | ||
}, | ||
// documentResponses: docResps, | ||
// failedCount: docResps.length - insertedIds.length, | ||
}); | ||
} | ||
@@ -502,7 +521,33 @@ return insertedIds; | ||
documents, | ||
options: { ordered }, | ||
options: { | ||
returnDocumentResponses: true, | ||
ordered, | ||
}, | ||
}, | ||
}; | ||
let resp, err; | ||
try { | ||
resp = await httpClient.executeCommand(command, { timeoutManager }); | ||
} | ||
catch (e) { | ||
if (!(e instanceof errors_1.DataAPIResponseError)) { | ||
throw e; | ||
} | ||
}; | ||
const resp = await httpClient.executeCommand(command, { timeoutManager }); | ||
return resp.status?.insertedIds ?? []; | ||
resp = e.detailedErrorDescriptors[0].rawResponse; | ||
err = e; | ||
} | ||
const documentResponses = resp.status?.documentResponses ?? []; | ||
const errors = resp.errors; | ||
const insertedIds = []; | ||
for (let i = 0, n = documentResponses.length; i < n; i++) { | ||
const resp = documentResponses[i]; | ||
if (resp.status === "OK") { | ||
insertedIds.push(resp._id); | ||
} | ||
else if (resp.errorIdx) { | ||
resp.error = errors[resp.errorIdx]; | ||
delete resp.errorIdx; | ||
} | ||
} | ||
return [documentResponses, insertedIds, err?.detailedErrorDescriptors[0]]; | ||
}; | ||
@@ -526,3 +571,3 @@ // -- Bulk Write ------------------------------------------------------------------------------------------ | ||
} | ||
throw (0, errors_1.mkRespErrorFromResponse)(errors_1.BulkWriteError, desc.command, desc.rawResponse, results); | ||
throw (0, errors_1.mkRespErrorFromResponse)(errors_1.BulkWriteError, desc.command, desc.rawResponse, { partialResult: results }); | ||
} | ||
@@ -558,3 +603,3 @@ return results; | ||
if (failCommands.length > 0) { | ||
throw (0, errors_1.mkRespErrorFromResponses)(errors_1.BulkWriteError, failCommands, failRaw, results); | ||
throw (0, errors_1.mkRespErrorFromResponses)(errors_1.BulkWriteError, failCommands, failRaw, { partialResult: results }); | ||
} | ||
@@ -561,0 +606,0 @@ return results; |
@@ -9,4 +9,4 @@ "use strict"; | ||
class FindCursor { | ||
constructor(namespace, httpClient, filter, options) { | ||
Object.defineProperty(this, "_namespace", { | ||
constructor(keyspace, httpClient, filter, options) { | ||
Object.defineProperty(this, "_keyspace", { | ||
enumerable: true, | ||
@@ -64,3 +64,3 @@ configurable: true, | ||
}); | ||
this._namespace = namespace; | ||
this._keyspace = keyspace; | ||
this._httpClient = httpClient; | ||
@@ -73,4 +73,7 @@ this._filter = filter; | ||
} | ||
get keyspace() { | ||
return this._keyspace; | ||
} | ||
get namespace() { | ||
return this._namespace; | ||
return this._keyspace; | ||
} | ||
@@ -130,3 +133,3 @@ get closed() { | ||
clone() { | ||
return new FindCursor(this._namespace, this._httpClient, this._filter, this._options); | ||
return new FindCursor(this._keyspace, this._httpClient, this._filter, this._options); | ||
} | ||
@@ -241,3 +244,3 @@ readBufferedDocuments(max) { | ||
if (this._nextPageState) { | ||
options.pagingState = this._nextPageState; | ||
options.pageState = this._nextPageState; | ||
} | ||
@@ -254,3 +257,3 @@ if (this._options.skip) { | ||
const command = { | ||
find: { filter: this._filter } | ||
find: { filter: this._filter }, | ||
}; | ||
@@ -268,3 +271,3 @@ if (this._options.sort) { | ||
this._nextPageState = resp.data?.nextPageState || null; | ||
this._buffer = resp.data.documents; | ||
this._buffer = resp.data?.documents ?? []; | ||
this._sortVector ?? (this._sortVector = resp.status?.sortVector); | ||
@@ -271,0 +274,0 @@ this._options.includeSortVector = false; |
@@ -15,5 +15,7 @@ "use strict"; | ||
}; | ||
var _Db_defaultOpts, _Db_token, _Db_httpClient; | ||
var _Db_defaultOpts, _Db_token, _Db_httpClient, _Db_endpoint; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.validateDbOpts = exports.mkDb = exports.Db = void 0; | ||
exports.Db = void 0; | ||
exports.mkDb = mkDb; | ||
exports.validateDbOpts = validateDbOpts; | ||
const data_api_1 = require("../data-api"); | ||
@@ -30,3 +32,4 @@ const api_1 = require("../api"); | ||
_Db_httpClient.set(this, void 0); | ||
Object.defineProperty(this, "_namespace", { | ||
_Db_endpoint.set(this, void 0); | ||
Object.defineProperty(this, "_keyspace", { | ||
enumerable: true, | ||
@@ -49,6 +52,6 @@ configurable: true, | ||
}; | ||
this._namespace = { | ||
this._keyspace = { | ||
ref: (rootOpts.environment === 'astra') | ||
? combinedDbOpts.namespace ?? api_1.DEFAULT_NAMESPACE | ||
: combinedDbOpts.namespace | ||
? (0, common_1.resolveKeyspace)(combinedDbOpts) ?? api_1.DEFAULT_KEYSPACE | ||
: (0, common_1.resolveKeyspace)(combinedDbOpts), | ||
}; | ||
@@ -63,3 +66,3 @@ __classPrivateFieldSet(this, _Db_httpClient, new api_1.DataAPIHttpClient({ | ||
fetchCtx: rootOpts.fetchCtx, | ||
namespace: this._namespace, | ||
keyspace: this._keyspace, | ||
userAgent: rootOpts.userAgent, | ||
@@ -69,8 +72,15 @@ emissionStrategy: api_1.EmissionStrategy.Normal, | ||
this._id = (0, utils_1.extractDbIdFromUrl)(endpoint); | ||
__classPrivateFieldSet(this, _Db_endpoint, endpoint, "f"); | ||
} | ||
get keyspace() { | ||
if (!this._keyspace.ref) { | ||
throw new Error('No keyspace set for DB (can\'t do db.keyspace, or perform any operation requiring it). Use `db.useKeyspace`, or pass the keyspace as an option parameter explicitly.'); | ||
} | ||
return this._keyspace.ref; | ||
} | ||
get namespace() { | ||
if (!this._namespace.ref) { | ||
throw new Error('No namespace set for DB (can\'t do db.namespace)'); | ||
if (!this._keyspace.ref) { | ||
throw new Error('No keyspace set for DB (can\'t do db.namespace, or perform any operation requiring it). Use `db.useKeyspace`, or pass the keyspace as an option parameter explicitly.'); | ||
} | ||
return this._namespace.ref; | ||
return this._keyspace.ref; | ||
} | ||
@@ -83,5 +93,8 @@ get id() { | ||
} | ||
useNamespace(namespace) { | ||
this._namespace.ref = namespace; | ||
useKeyspace(keyspace) { | ||
this._keyspace.ref = keyspace; | ||
} | ||
useNamespace(keyspace) { | ||
this._keyspace.ref = keyspace; | ||
} | ||
admin(options) { | ||
@@ -94,3 +107,3 @@ const environment = options?.environment ?? 'astra'; | ||
if (environment === 'astra') { | ||
return new astra_db_admin_1.AstraDbAdmin(this, __classPrivateFieldGet(this, _Db_defaultOpts, "f"), options, __classPrivateFieldGet(this, _Db_token, "f")); | ||
return new astra_db_admin_1.AstraDbAdmin(this, __classPrivateFieldGet(this, _Db_defaultOpts, "f"), options, __classPrivateFieldGet(this, _Db_token, "f"), __classPrivateFieldGet(this, _Db_endpoint, "f")); | ||
} | ||
@@ -107,3 +120,3 @@ return new data_api_db_admin_1.DataAPIDbAdmin(this, __classPrivateFieldGet(this, _Db_httpClient, "f"), options); | ||
const collections = await this.listCollections({ | ||
namespace: options?.namespace, | ||
keyspace: (0, common_1.resolveKeyspace)(options), | ||
maxTimeMS: options?.maxTimeMS, | ||
@@ -126,10 +139,10 @@ nameOnly: true, | ||
const timeoutManager = __classPrivateFieldGet(this, _Db_httpClient, "f").timeoutManager(options?.maxTimeMS); | ||
const namespace = options?.namespace ?? this.namespace; | ||
const keyspace = (0, common_1.resolveKeyspace)(options) ?? this.keyspace; | ||
if (options?.checkExists !== false) { | ||
const collections = await this.listCollections({ namespace, maxTimeMS: timeoutManager.msRemaining() }); | ||
const collections = await this.listCollections({ keyspace: keyspace, maxTimeMS: timeoutManager.msRemaining() }); | ||
if (collections.some(c => c.name === collectionName)) { | ||
throw new data_api_1.CollectionAlreadyExistsError(options?.namespace ?? this.namespace, collectionName); | ||
throw new data_api_1.CollectionAlreadyExistsError((0, common_1.resolveKeyspace)(options) ?? this.keyspace, collectionName); | ||
} | ||
} | ||
await __classPrivateFieldGet(this, _Db_httpClient, "f").executeCommand(command, { namespace, timeoutManager }); | ||
await __classPrivateFieldGet(this, _Db_httpClient, "f").executeCommand(command, { keyspace: keyspace, timeoutManager }); | ||
return this.collection(collectionName, options); | ||
@@ -163,3 +176,3 @@ } | ||
exports.Db = Db; | ||
_Db_defaultOpts = new WeakMap(), _Db_token = new WeakMap(), _Db_httpClient = new WeakMap(); | ||
_Db_defaultOpts = new WeakMap(), _Db_token = new WeakMap(), _Db_httpClient = new WeakMap(), _Db_endpoint = new WeakMap(); | ||
function mkDb(rootOpts, endpointOrId, regionOrOptions, maybeOptions) { | ||
@@ -171,3 +184,3 @@ const dbOpts = (typeof regionOrOptions === 'string') | ||
if (typeof regionOrOptions === 'string' && (endpointOrId.startsWith('https://') || endpointOrId.startsWith('http://'))) { | ||
throw new Error('Unexpected db() argument: database id can\'t start with "http(s)://". Did you mean to call `.db(endpoint, { namespace })`?'); | ||
throw new Error('Unexpected db() argument: database id can\'t start with "http(s)://". Did you mean to call `.db(endpoint, { keyspace })`?'); | ||
} | ||
@@ -179,3 +192,2 @@ const endpoint = (typeof regionOrOptions === 'string') | ||
} | ||
exports.mkDb = mkDb; | ||
function validateDbOpts(opts) { | ||
@@ -186,10 +198,11 @@ (0, utils_1.validateOption)('dbOptions', opts, 'object'); | ||
} | ||
(0, utils_1.validateOption)('dbOptions.namespace', opts.namespace, 'string', false, (namespace) => { | ||
if (!namespace.match(/^\w{1,48}$/)) { | ||
throw new Error('Invalid namespace option; expected a string of 1-48 alphanumeric characters'); | ||
} | ||
}); | ||
for (const prop of ['keyspace', 'namespace']) { | ||
(0, utils_1.validateOption)(`dbOptions.${prop}`, opts[prop], 'string', false, (keyspace) => { | ||
if (!keyspace.match(/^\w{1,48}$/)) { | ||
throw new Error(`Invalid ${prop} option; expected a string of 1-48 alphanumeric characters`); | ||
} | ||
}); | ||
} | ||
(0, utils_1.validateOption)('dbOptions.monitorCommands', opts.monitorCommands, 'boolean'); | ||
(0, utils_1.validateOption)('dbOptions.dataApiPath', opts.dataApiPath, 'string'); | ||
} | ||
exports.validateDbOpts = validateDbOpts; |
@@ -11,3 +11,3 @@ "use strict"; | ||
constructor(resp) { | ||
super(`HTTP error: ${resp.status}${resp.body ? `; ${resp.body}` : ''}`); | ||
super(`HTTP error (${resp.status}): ${resp.body ? resp.body : resp.statusText}`); | ||
Object.defineProperty(this, "status", { | ||
@@ -79,3 +79,3 @@ enumerable: true, | ||
super(message); | ||
this.name = 'CursorAlreadyInitializedError'; | ||
this.name = 'CursorIsStartedError'; | ||
} | ||
@@ -85,4 +85,10 @@ } | ||
class CollectionNotFoundError extends DataAPIError { | ||
constructor(namespace, collectionName) { | ||
super(`Collection '${namespace}.${collectionName}' not found`); | ||
constructor(keyspace, collectionName) { | ||
super(`Collection '${keyspace}.${collectionName}' not found`); | ||
Object.defineProperty(this, "keyspace", { | ||
enumerable: true, | ||
configurable: true, | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, "namespace", { | ||
@@ -100,3 +106,3 @@ enumerable: true, | ||
}); | ||
this.namespace = namespace; | ||
this.keyspace = this.namespace = keyspace; | ||
this.collectionName = collectionName; | ||
@@ -108,4 +114,10 @@ this.name = 'CollectionNotFoundError'; | ||
class CollectionAlreadyExistsError extends DataAPIError { | ||
constructor(namespace, collectionName) { | ||
super(`Collection '${namespace}.${collectionName}' already exists`); | ||
constructor(keyspace, collectionName) { | ||
super(`Collection '${keyspace}.${collectionName}' already exists`); | ||
Object.defineProperty(this, "keyspace", { | ||
enumerable: true, | ||
configurable: true, | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, "namespace", { | ||
@@ -123,3 +135,3 @@ enumerable: true, | ||
}); | ||
this.namespace = namespace; | ||
this.keyspace = this.namespace = keyspace; | ||
this.collectionName = collectionName; | ||
@@ -131,3 +143,7 @@ this.name = 'CollectionAlreadyExistsError'; | ||
class DataAPIResponseError extends DataAPIError { | ||
constructor(message, errorDescriptors, detailedErrorDescriptors) { | ||
constructor(detailedErrDescriptors) { | ||
const errorDescriptors = detailedErrDescriptors.flatMap(d => d.errorDescriptors); | ||
const message = (errorDescriptors[0]?.message) | ||
? `${errorDescriptors[0].message}${errorDescriptors.length > 1 ? ` (+ ${errorDescriptors.length - 1} more errors)` : ''}` | ||
: `Something went wrong (${errorDescriptors.length} errors)`; | ||
super(message); | ||
@@ -154,3 +170,3 @@ Object.defineProperty(this, "message", { | ||
this.errorDescriptors = errorDescriptors; | ||
this.detailedErrorDescriptors = detailedErrorDescriptors; | ||
this.detailedErrorDescriptors = detailedErrDescriptors; | ||
this.name = 'DataAPIResponseError'; | ||
@@ -181,2 +197,6 @@ } | ||
}); | ||
// | ||
// // declare public readonly documentResponses: InsertManyDocumentResponse<SomeDoc>[]; | ||
// | ||
// // declare public readonly failedCount: number; | ||
} | ||
@@ -221,8 +241,8 @@ } | ||
exports.BulkWriteError = BulkWriteError; | ||
const mkRespErrorFromResponse = (err, command, raw, partialResult) => { | ||
return (0, exports.mkRespErrorFromResponses)(err, [command], [raw], partialResult); | ||
const mkRespErrorFromResponse = (err, command, raw, attributes) => { | ||
return (0, exports.mkRespErrorFromResponses)(err, [command], [raw], attributes); | ||
}; | ||
exports.mkRespErrorFromResponse = mkRespErrorFromResponse; | ||
const mkRespErrorFromResponses = (err, commands, raw, partialResult) => { | ||
const detailedDescriptors = []; | ||
const mkRespErrorFromResponses = (err, commands, raw, attributes) => { | ||
const detailedErrDescriptors = []; | ||
for (let i = 0, n = commands.length; i < n; i++) { | ||
@@ -237,14 +257,10 @@ const command = commands[i], response = raw[i]; | ||
}); | ||
const detailedDescriptor = { errorDescriptors: descriptors, command, rawResponse: response }; | ||
detailedDescriptors.push(detailedDescriptor); | ||
const detailedErrDescriptor = { errorDescriptors: descriptors, command, rawResponse: response }; | ||
detailedErrDescriptors.push(detailedErrDescriptor); | ||
} | ||
} | ||
const errorDescriptors = detailedDescriptors.flatMap(d => d.errorDescriptors); | ||
const message = errorDescriptors[0]?.message || 'Something unexpected occurred'; | ||
const instance = new err(message, errorDescriptors, detailedDescriptors); | ||
if (partialResult) { | ||
instance.partialResult = partialResult; | ||
} | ||
const instance = new err(detailedErrDescriptors); | ||
Object.assign(instance, attributes ?? {}); | ||
return instance; | ||
}; | ||
exports.mkRespErrorFromResponses = mkRespErrorFromResponses; |
@@ -15,2 +15,8 @@ "use strict"; | ||
}); | ||
Object.defineProperty(this, "keyspace", { | ||
enumerable: true, | ||
configurable: true, | ||
writable: true, | ||
value: void 0 | ||
}); | ||
Object.defineProperty(this, "namespace", { | ||
@@ -41,3 +47,3 @@ enumerable: true, | ||
this.command = info.command; | ||
this.namespace = info.namespace || api_1.DEFAULT_NAMESPACE; | ||
this.keyspace = this.namespace = info.keyspace || api_1.DEFAULT_KEYSPACE; | ||
this.collection = info.collection; | ||
@@ -63,3 +69,3 @@ this.commandName = Object.keys(info.command)[0]; | ||
class CommandSucceededEvent extends CommandEvent { | ||
constructor(info, reply, started) { | ||
constructor(info, reply, warnings, started) { | ||
super(info); | ||
@@ -78,3 +84,10 @@ Object.defineProperty(this, "duration", { | ||
}); | ||
Object.defineProperty(this, "warnings", { | ||
enumerable: true, | ||
configurable: true, | ||
writable: true, | ||
value: void 0 | ||
}); | ||
this.duration = (0, api_1.hrTimeMs)() - started; | ||
this.warnings = warnings; | ||
this.resp = reply; | ||
@@ -81,0 +94,0 @@ } |
@@ -117,3 +117,3 @@ "use strict"; | ||
exports.ObjectId = ObjectId; | ||
const MACHINE_ID = ~~(Math.random() * 0xFFFFFF); | ||
const RAND_ID = ~~(Math.random() * 0xFFFFFF); | ||
const PID = ((typeof process === 'undefined' || typeof process.pid !== 'number') ? ~~(Math.random() * 100000) : process.pid) % 0xFFFF; | ||
@@ -133,5 +133,5 @@ const hexTable = Array.from({ length: 256 }, (_, i) => { | ||
hexString += hexTable[(time & 0xFF)]; | ||
hexString += hexTable[((MACHINE_ID >> 16) & 0xFF)]; | ||
hexString += hexTable[((MACHINE_ID >> 8) & 0xFF)]; | ||
hexString += hexTable[(MACHINE_ID & 0xFF)]; | ||
hexString += hexTable[((RAND_ID >> 16) & 0xFF)]; | ||
hexString += hexTable[((RAND_ID >> 8) & 0xFF)]; | ||
hexString += hexTable[(RAND_ID & 0xFF)]; | ||
hexString += hexTable[((PID >> 8) & 0xFF)]; | ||
@@ -138,0 +138,0 @@ hexString += hexTable[(PID & 0xFF)]; |
@@ -20,5 +20,7 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.DataAPIHttpError = exports.CollectionNotFoundError = exports.UpdateManyError = exports.CursorIsStartedError = exports.BulkWriteError = exports.InsertManyError = exports.TooManyDocumentsToCountError = exports.DeleteManyError = exports.CollectionAlreadyExistsError = exports.DataAPIError = exports.CumulativeDataAPIError = exports.DataAPIResponseError = exports.DataAPITimeoutError = exports.Db = void 0; | ||
__exportStar(require("./collection"), exports); | ||
__exportStar(require("./cursor"), exports); | ||
exports.DataAPIHttpError = exports.CollectionNotFoundError = exports.UpdateManyError = exports.CursorIsStartedError = exports.BulkWriteError = exports.InsertManyError = exports.TooManyDocumentsToCountError = exports.DeleteManyError = exports.CollectionAlreadyExistsError = exports.DataAPIError = exports.CumulativeDataAPIError = exports.DataAPIResponseError = exports.DataAPITimeoutError = exports.Db = exports.FindCursor = exports.Collection = void 0; | ||
var collection_1 = require("./collection"); | ||
Object.defineProperty(exports, "Collection", { enumerable: true, get: function () { return collection_1.Collection; } }); | ||
var cursor_1 = require("./cursor"); | ||
Object.defineProperty(exports, "FindCursor", { enumerable: true, get: function () { return cursor_1.FindCursor; } }); | ||
var db_1 = require("./db"); | ||
@@ -25,0 +27,0 @@ Object.defineProperty(exports, "Db", { enumerable: true, get: function () { return db_1.Db; } }); |
@@ -5,7 +5,9 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.normalizeSort = exports.validateOption = exports.replaceAstraUrlIdAndRegion = exports.extractDbIdFromUrl = void 0; | ||
exports.normalizeSort = void 0; | ||
exports.extractDbIdFromUrl = extractDbIdFromUrl; | ||
exports.replaceAstraUrlIdAndRegion = replaceAstraUrlIdAndRegion; | ||
exports.validateOption = validateOption; | ||
function extractDbIdFromUrl(uri) { | ||
return new URL(uri).hostname.match(/^[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}/)?.[0]; | ||
} | ||
exports.extractDbIdFromUrl = extractDbIdFromUrl; | ||
function replaceAstraUrlIdAndRegion(uri, id, region) { | ||
@@ -18,3 +20,2 @@ const url = new URL(uri); | ||
} | ||
exports.replaceAstraUrlIdAndRegion = replaceAstraUrlIdAndRegion; | ||
function validateOption(name, obj, types, require = false, test) { | ||
@@ -34,3 +35,2 @@ types = Array.isArray(types) ? types : [types]; | ||
} | ||
exports.validateOption = validateOption; | ||
const normalizeSort = (sort) => { | ||
@@ -37,0 +37,0 @@ const ret = {}; |
@@ -35,3 +35,3 @@ "use strict"; | ||
__classPrivateFieldSet(this, _AstraAdmin_httpClient, new api_1.DevOpsAPIHttpClient({ | ||
baseUrl: combinedAdminOpts.endpointUrl || api_1.DEFAULT_DEVOPS_API_ENDPOINT, | ||
baseUrl: combinedAdminOpts.endpointUrl || api_1.DEFAULT_DEVOPS_API_ENDPOINTS.prod, | ||
monitorCommands: combinedAdminOpts.monitorCommands, | ||
@@ -59,6 +59,14 @@ emitter: rootOpts.emitter, | ||
const params = {}; | ||
typeof options?.include === 'string' && (params['include'] = options.include); | ||
typeof options?.provider === 'string' && (params['provider'] = options.provider); | ||
typeof options?.limit === 'number' && (params['limit'] = String(options.skip)); | ||
typeof options?.skip === 'number' && (params['starting_after'] = String(options.skip)); | ||
if (typeof options?.include === 'string') { | ||
(params['include'] = options.include); | ||
} | ||
if (typeof options?.provider === 'string') { | ||
(params['provider'] = options.provider); | ||
} | ||
if (typeof options?.limit === 'number') { | ||
(params['limit'] = String(options.skip)); | ||
} | ||
if (typeof options?.skip === 'number') { | ||
(params['starting_after'] = String(options.skip)); | ||
} | ||
const resp = await __classPrivateFieldGet(this, _AstraAdmin_httpClient, "f").request({ | ||
@@ -76,3 +84,3 @@ method: api_1.HttpMethods.Get, | ||
dbType: 'vector', | ||
keyspace: config.namespace || api_1.DEFAULT_NAMESPACE, | ||
keyspace: (0, common_1.resolveKeyspace)(config) || api_1.DEFAULT_KEYSPACE, | ||
...config, | ||
@@ -91,3 +99,3 @@ }; | ||
}); | ||
const db = (0, db_1.mkDb)(__classPrivateFieldGet(this, _AstraAdmin_defaultOpts, "f"), resp.headers.location, definition.region, { ...options?.dbOptions, namespace: definition.keyspace }); | ||
const db = (0, db_1.mkDb)(__classPrivateFieldGet(this, _AstraAdmin_defaultOpts, "f"), resp.headers.location, definition.region, { ...options?.dbOptions, keyspace: definition.keyspace }); | ||
return db.admin(__classPrivateFieldGet(this, _AstraAdmin_defaultOpts, "f").adminOptions); | ||
@@ -94,0 +102,0 @@ } |
@@ -24,3 +24,3 @@ "use strict"; | ||
class AstraDbAdmin extends db_admin_1.DbAdmin { | ||
constructor(db, rootOpts, adminOpts, dbToken) { | ||
constructor(db, rootOpts, adminOpts, dbToken, endpoint) { | ||
super(); | ||
@@ -38,4 +38,5 @@ _AstraDbAdmin_httpClient.set(this, void 0); | ||
: _adminToken; | ||
const environment = (0, utils_1.extractAstraEnvironment)(endpoint); | ||
__classPrivateFieldSet(this, _AstraDbAdmin_httpClient, new api_1.DevOpsAPIHttpClient({ | ||
baseUrl: combinedAdminOpts.endpointUrl ?? api_1.DEFAULT_DEVOPS_API_ENDPOINT, | ||
baseUrl: combinedAdminOpts.endpointUrl ?? api_1.DEFAULT_DEVOPS_API_ENDPOINTS[environment], | ||
monitorCommands: combinedAdminOpts.monitorCommands, | ||
@@ -56,3 +57,3 @@ fetchCtx: rootOpts.fetchCtx, | ||
async findEmbeddingProviders(options) { | ||
const resp = await __classPrivateFieldGet(this, _AstraDbAdmin_db, "f").command({ findEmbeddingProviders: {} }, { namespace: null, maxTimeMS: options?.maxTimeMS }); | ||
const resp = await __classPrivateFieldGet(this, _AstraDbAdmin_db, "f").command({ findEmbeddingProviders: {} }, { keyspace: null, maxTimeMS: options?.maxTimeMS }); | ||
return resp.status; | ||
@@ -67,9 +68,15 @@ } | ||
} | ||
async listKeyspaces(options) { | ||
return this.info(options).then(i => [i.info.keyspace, ...i.info.additionalKeyspaces ?? []].filter(Boolean)); | ||
} | ||
async listNamespaces(options) { | ||
return this.info(options).then(i => [i.info.keyspace ?? api_1.DEFAULT_NAMESPACE, ...i.info.additionalKeyspaces ?? []].filter(Boolean)); | ||
return this.listKeyspaces(options); | ||
} | ||
async createNamespace(namespace, options) { | ||
async createKeyspace(keyspace, options) { | ||
if (options?.updateDbKeyspace) { | ||
__classPrivateFieldGet(this, _AstraDbAdmin_db, "f").useKeyspace(keyspace); | ||
} | ||
await __classPrivateFieldGet(this, _AstraDbAdmin_httpClient, "f").requestLongRunning({ | ||
method: api_1.HttpMethods.Post, | ||
path: `/databases/${__classPrivateFieldGet(this, _AstraDbAdmin_db, "f").id}/keyspaces/${namespace}`, | ||
path: `/databases/${__classPrivateFieldGet(this, _AstraDbAdmin_db, "f").id}/keyspaces/${keyspace}`, | ||
}, { | ||
@@ -82,10 +89,10 @@ id: __classPrivateFieldGet(this, _AstraDbAdmin_db, "f").id, | ||
}); | ||
if (options?.updateDbNamespace) { | ||
__classPrivateFieldGet(this, _AstraDbAdmin_db, "f").useNamespace(namespace); | ||
} | ||
} | ||
async dropNamespace(namespace, options) { | ||
async createNamespace(keyspace, options) { | ||
return this.createKeyspace(keyspace, { ...options, updateDbKeyspace: options?.updateDbNamespace }); | ||
} | ||
async dropKeyspace(keyspace, options) { | ||
await __classPrivateFieldGet(this, _AstraDbAdmin_httpClient, "f").requestLongRunning({ | ||
method: api_1.HttpMethods.Delete, | ||
path: `/databases/${__classPrivateFieldGet(this, _AstraDbAdmin_db, "f").id}/keyspaces/${namespace}`, | ||
path: `/databases/${__classPrivateFieldGet(this, _AstraDbAdmin_db, "f").id}/keyspaces/${keyspace}`, | ||
}, { | ||
@@ -99,2 +106,5 @@ id: __classPrivateFieldGet(this, _AstraDbAdmin_db, "f").id, | ||
} | ||
async dropNamespace(keyspace, options) { | ||
return this.dropKeyspace(keyspace, options); | ||
} | ||
async drop(options) { | ||
@@ -101,0 +111,0 @@ await __classPrivateFieldGet(this, _AstraDbAdmin_httpClient, "f").requestLongRunning({ |
@@ -34,10 +34,17 @@ "use strict"; | ||
async findEmbeddingProviders(options) { | ||
const resp = await __classPrivateFieldGet(this, _DataAPIDbAdmin_httpClient, "f").executeCommand({ findEmbeddingProviders: {} }, { namespace: null, maxTimeMS: options?.maxTimeMS }); | ||
const resp = await __classPrivateFieldGet(this, _DataAPIDbAdmin_httpClient, "f").executeCommand({ findEmbeddingProviders: {} }, { keyspace: null, maxTimeMS: options?.maxTimeMS }); | ||
return resp.status; | ||
} | ||
async listKeyspaces(options) { | ||
const resp = await __classPrivateFieldGet(this, _DataAPIDbAdmin_httpClient, "f").executeCommand({ findKeyspaces: {} }, { maxTimeMS: options?.maxTimeMS, keyspace: null }); | ||
return resp.status.keyspaces; | ||
} | ||
async listNamespaces(options) { | ||
const resp = await __classPrivateFieldGet(this, _DataAPIDbAdmin_httpClient, "f").executeCommand({ findNamespaces: {} }, { maxTimeMS: options?.maxTimeMS, namespace: null }); | ||
const resp = await __classPrivateFieldGet(this, _DataAPIDbAdmin_httpClient, "f").executeCommand({ findNamespaces: {} }, { maxTimeMS: options?.maxTimeMS, keyspace: null }); | ||
return resp.status.namespaces; | ||
} | ||
async createNamespace(namespace, options) { | ||
async createKeyspace(keyspace, options) { | ||
if (options?.updateDbKeyspace) { | ||
__classPrivateFieldGet(this, _DataAPIDbAdmin_db, "f").useKeyspace(keyspace); | ||
} | ||
const replication = options?.replication ?? { | ||
@@ -47,10 +54,20 @@ class: 'SimpleStrategy', | ||
}; | ||
await __classPrivateFieldGet(this, _DataAPIDbAdmin_httpClient, "f").executeCommand({ createNamespace: { name: namespace, options: { replication } } }, { maxTimeMS: options?.maxTimeMS, namespace: null }); | ||
await __classPrivateFieldGet(this, _DataAPIDbAdmin_httpClient, "f").executeCommand({ createKeyspace: { name: keyspace, options: { replication } } }, { maxTimeMS: options?.maxTimeMS, keyspace: null }); | ||
} | ||
async createNamespace(keyspace, options) { | ||
if (options?.updateDbNamespace) { | ||
__classPrivateFieldGet(this, _DataAPIDbAdmin_db, "f").useNamespace(namespace); | ||
__classPrivateFieldGet(this, _DataAPIDbAdmin_db, "f").useKeyspace(keyspace); | ||
} | ||
const replication = options?.replication ?? { | ||
class: 'SimpleStrategy', | ||
replicationFactor: 1, | ||
}; | ||
await __classPrivateFieldGet(this, _DataAPIDbAdmin_httpClient, "f").executeCommand({ createNamespace: { name: keyspace, options: { replication } } }, { maxTimeMS: options?.maxTimeMS, keyspace: null }); | ||
} | ||
async dropNamespace(namespace, options) { | ||
await __classPrivateFieldGet(this, _DataAPIDbAdmin_httpClient, "f").executeCommand({ dropNamespace: { name: namespace } }, { maxTimeMS: options?.maxTimeMS, namespace: null }); | ||
async dropKeyspace(keyspace, options) { | ||
await __classPrivateFieldGet(this, _DataAPIDbAdmin_httpClient, "f").executeCommand({ dropKeyspace: { name: keyspace } }, { maxTimeMS: options?.maxTimeMS, keyspace: null }); | ||
} | ||
async dropNamespace(keyspace, options) { | ||
await __classPrivateFieldGet(this, _DataAPIDbAdmin_httpClient, "f").executeCommand({ dropNamespace: { name: keyspace } }, { maxTimeMS: options?.maxTimeMS, keyspace: null }); | ||
} | ||
get _httpClient() { | ||
@@ -57,0 +74,0 @@ return __classPrivateFieldGet(this, _DataAPIDbAdmin_httpClient, "f"); |
@@ -32,3 +32,7 @@ "use strict"; | ||
constructor(resp, data) { | ||
const message = data?.errors?.find((e) => e.message)?.message ?? 'Something went wrong'; | ||
const errors = data?.errors ?? []; | ||
const maybeMsg = errors.find((e) => e.message)?.message; | ||
const message = (maybeMsg) | ||
? `${maybeMsg}${errors.length > 1 ? ` (+ ${errors.length - 1} more errors)` : ''}` | ||
: `Something went wrong (${errors.length} errors)`; | ||
super(message); | ||
@@ -35,0 +39,0 @@ Object.defineProperty(this, "errors", { |
@@ -81,3 +81,3 @@ "use strict"; | ||
class AdminCommandSucceededEvent extends AdminCommandEvent { | ||
constructor(info, longRunning, data, started) { | ||
constructor(info, longRunning, data, warnings, started) { | ||
super(info, longRunning); | ||
@@ -96,3 +96,10 @@ Object.defineProperty(this, "duration", { | ||
}); | ||
Object.defineProperty(this, "warnings", { | ||
enumerable: true, | ||
configurable: true, | ||
writable: true, | ||
value: void 0 | ||
}); | ||
this.duration = (0, api_1.hrTimeMs)() - started; | ||
this.warnings = warnings; | ||
this.resBody = data || undefined; | ||
@@ -99,0 +106,0 @@ } |
@@ -5,3 +5,4 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.validateAdminOpts = void 0; | ||
exports.validateAdminOpts = validateAdminOpts; | ||
exports.extractAstraEnvironment = extractAstraEnvironment; | ||
const utils_1 = require("../data-api/utils"); | ||
@@ -14,2 +15,13 @@ function validateAdminOpts(opts) { | ||
} | ||
exports.validateAdminOpts = validateAdminOpts; | ||
function extractAstraEnvironment(endpoint) { | ||
switch (true) { | ||
case endpoint.includes('apps.astra-dev.datastax.com'): | ||
return 'dev'; | ||
case endpoint.includes('apps.astra-test.datastax.com'): | ||
return 'test'; | ||
case endpoint.includes('apps.astra.datastax.com'): | ||
return 'prod'; | ||
default: | ||
throw new Error(`Cannot extract astra environment for endpoint '${endpoint}'`); | ||
} | ||
} |
@@ -19,3 +19,7 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.DataAPIEnvironments = exports.UsernamePasswordTokenProvider = exports.StaticTokenProvider = exports.TokenProvider = void 0; | ||
exports.DataAPIEnvironments = exports.UsernamePasswordTokenProvider = exports.StaticTokenProvider = exports.TokenProvider = exports.DEFAULT_KEYSPACE = exports.FetchH2 = exports.FetchNative = void 0; | ||
var api_1 = require("./api"); | ||
Object.defineProperty(exports, "FetchNative", { enumerable: true, get: function () { return api_1.FetchNative; } }); | ||
Object.defineProperty(exports, "FetchH2", { enumerable: true, get: function () { return api_1.FetchH2; } }); | ||
Object.defineProperty(exports, "DEFAULT_KEYSPACE", { enumerable: true, get: function () { return api_1.DEFAULT_KEYSPACE; } }); | ||
__exportStar(require("./data-api"), exports); | ||
@@ -22,0 +26,0 @@ __exportStar(require("./client"), exports); |
@@ -8,5 +8,5 @@ // This file is read by tools that parse documentation comments conforming to the TSDoc standard. | ||
"packageName": "@microsoft/api-extractor", | ||
"packageVersion": "7.43.0" | ||
"packageVersion": "7.47.9" | ||
} | ||
] | ||
} |
@@ -7,2 +7,2 @@ "use strict"; | ||
exports.LIB_NAME = 'astra-db-ts'; | ||
exports.LIB_VERSION = '1.4.1'; | ||
exports.LIB_VERSION = '1.5.0'; |
{ | ||
"name": "@datastax/astra-db-ts", | ||
"version": "1.4.1", | ||
"version": "1.5.0", | ||
"description": "Astra DB TS Client", | ||
@@ -30,8 +30,2 @@ "contributors": [ | ||
"types": "dist/astra-db-ts.d.ts", | ||
"mocha": { | ||
"timeout": 30000, | ||
"require": [ | ||
"tests/setup.ts" | ||
] | ||
}, | ||
"directories": { | ||
@@ -55,4 +49,3 @@ "lib": "src", | ||
"build": "sh scripts/build.sh", | ||
"list-embedding-providers": "chmod +x scripts/list-embedding-providers.sh && scripts/list-embedding-providers.sh", | ||
"version": "sh scripts/version.sh" | ||
"version": "sh scripts/utils/version.sh" | ||
}, | ||
@@ -63,10 +56,13 @@ "bugs": { | ||
"devDependencies": { | ||
"@microsoft/api-extractor": "^7.43.0", | ||
"@eslint/eslintrc": "^3.1.0", | ||
"@eslint/js": "^9.10.0", | ||
"@microsoft/api-extractor": "^7.47.9", | ||
"@types/mocha": "^9.1.1", | ||
"@types/node": "^17.0.36", | ||
"@types/object-hash": "^3.0.6", | ||
"@typescript-eslint/eslint-plugin": "^7.6.0", | ||
"@typescript-eslint/parser": "^7.6.0", | ||
"@typescript-eslint/eslint-plugin": "^8.6.0", | ||
"@typescript-eslint/parser": "^8.6.0", | ||
"dotenv": "^16.0.1", | ||
"eslint": "^8.57.0", | ||
"eslint": "^9.10.0", | ||
"globals": "^15.9.0", | ||
"nyc": "^15.1.0", | ||
@@ -76,3 +72,3 @@ "strip-comments": "^2.0.1", | ||
"tsc-alias": "^1.8.8", | ||
"typescript": "^5.3.3" | ||
"typescript": "^5.6.2" | ||
}, | ||
@@ -79,0 +75,0 @@ "dependencies": { |
Sorry, the diff of this file is too big to display
502043
49
12460
16