UNPKG

@sphereon/ssi-sdk.agent-config

Version:

436 lines (429 loc) • 15.2 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { DataSources: () => DataSources, contextHasCredentialIssuer: () => contextHasCredentialIssuer, contextHasCredentialStatusVerifier: () => contextHasCredentialStatusVerifier, contextHasCredentialVerifier: () => contextHasCredentialVerifier, contextHasDataStore: () => contextHasDataStore, contextHasDataStoreORM: () => contextHasDataStoreORM, contextHasDidManager: () => contextHasDidManager, contextHasDidResolver: () => contextHasDidResolver, contextHasKeyManager: () => contextHasKeyManager, contextHasPlugin: () => contextHasPlugin, createAgent: () => createAgent, createAgentFromConfig: () => createAgentFromConfig, createObjects: () => createObjects, dropDatabase: () => dropDatabase, getAgent: () => getAgent, getConfig: () => getConfig, getDbConnection: () => getDbConnection, getDbType: () => getDbType, resetDatabase: () => resetDatabase, revertMigration: () => revertMigration, typeOrmDateTime: () => typeOrmDateTime, typeormDate: () => typeormDate }); module.exports = __toCommonJS(index_exports); // src/agentContextUtils.ts function contextHasPlugin(context, requiredMethod) { const methods = Array.isArray(requiredMethod) ? requiredMethod : [ requiredMethod ]; const allMethods = context.agent.availableMethods(); return methods.every((method) => allMethods.includes(method)); } __name(contextHasPlugin, "contextHasPlugin"); function contextHasKeyManager(context) { return contextHasPlugin(context, "keyManagerGet"); } __name(contextHasKeyManager, "contextHasKeyManager"); function contextHasDidManager(context) { return contextHasPlugin(context, "didManagerGet"); } __name(contextHasDidManager, "contextHasDidManager"); function contextHasDidResolver(context) { return contextHasPlugin(context, "resolveDid"); } __name(contextHasDidResolver, "contextHasDidResolver"); function contextHasCredentialIssuer(context) { return contextHasPlugin(context, [ "createVerifiableCredential", "createVerifiablePresentation" ]); } __name(contextHasCredentialIssuer, "contextHasCredentialIssuer"); function contextHasCredentialVerifier(context) { return contextHasPlugin(context, [ "verifyCredential", "verifyPresentation" ]); } __name(contextHasCredentialVerifier, "contextHasCredentialVerifier"); function contextHasCredentialStatusVerifier(context) { return contextHasPlugin(context, [ "checkCredentialStatus" ]); } __name(contextHasCredentialStatusVerifier, "contextHasCredentialStatusVerifier"); function contextHasDataStore(context) { return contextHasPlugin(context, [ "dataStoreGetVerifiableCredential", "dataStoreGetVerifiablePresentation" ]); } __name(contextHasDataStore, "contextHasDataStore"); function contextHasDataStoreORM(context) { return contextHasPlugin(context, [ "dataStoreORMGetVerifiableCredentials", "dataStoreORMGetVerifiablePresentations" ]); } __name(contextHasDataStoreORM, "contextHasDataStoreORM"); // src/dataSources.ts var import_debug = __toESM(require("debug"), 1); var import_DataSource = require("typeorm/data-source/DataSource.js"); var debug = (0, import_debug.default)(`sphereon:ssi-sdk:database`); var DataSources = class _DataSources { static { __name(this, "DataSources"); } get defaultDbType() { return this._defaultDbType; } set defaultDbType(value) { this._defaultDbType = value; } dataSources = /* @__PURE__ */ new Map(); configs = /* @__PURE__ */ new Map(); _defaultDbType = "sqlite"; static singleton; static singleInstance() { if (!_DataSources.singleton) { _DataSources.singleton = new _DataSources(); } return _DataSources.singleton; } static newInstance(configs) { return new _DataSources(configs); } constructor(configs) { ; (configs ?? /* @__PURE__ */ new Map()).forEach((config, name) => this.addConfig(name, config)); } addConfig(dbName, config) { this.configs.set(dbName, config); this._defaultDbType = config.type; return this; } deleteConfig(dbName) { this.configs.delete(dbName); return this; } has(dbName) { return this.configs.has(dbName) && this.dataSources.has(dbName); } delete(dbName) { this.deleteConfig(dbName); this.dataSources.delete(dbName); return this; } getConfig(dbName) { const config = this.configs.get(dbName); if (!config) { throw Error(`No DB config found for ${dbName}`); } return config; } getDbNames() { return [ ...this.configs.keys() ]; } async getDbConnection(dbName, allowAutomaticMigrations = true) { const config = this.getConfig(dbName); if (!this._defaultDbType) { this._defaultDbType = config.type; } let dataSource = this.dataSources.get(dbName); if (dataSource) { return dataSource; } dataSource = await new import_DataSource.DataSource({ ...config, name: dbName }).initialize(); this.dataSources.set(dbName, dataSource); if (config.synchronize) { debug(`WARNING: Automatic migrations need to be disabled in this app! Adjust the database configuration and set synchronize to false`); } else if (config.migrationsRun) { debug(`Migrations are currently managed from config. Please set migrationsRun and synchronize to false to get consistent behaviour. We run migrations from code explicitly`); } else if (allowAutomaticMigrations) { debug(`Running ${dataSource.migrations.length} migration(s) from code if needed...`); await dataSource.runMigrations(); debug(`${dataSource.migrations.length} migration(s) from code were inspected and applied`); } return dataSource; } }; var getDbConnection = /* @__PURE__ */ __name(async (connectionName, opts) => { if (!DataSources.singleInstance().has(connectionName) && opts?.config) { DataSources.singleInstance().addConfig(connectionName, opts?.config); } return DataSources.singleInstance().getDbConnection(connectionName); }, "getDbConnection"); var dropDatabase = /* @__PURE__ */ __name(async (dbName, opts) => { const { removeDataSource = false } = { ...opts }; if (!DataSources.singleInstance().has(dbName)) { return Promise.reject(Error(`No database present with name: ${dbName}`)); } const connection = await getDbConnection(dbName); await connection.dropDatabase(); if (removeDataSource) { DataSources.singleInstance().delete(dbName); } else if (!connection.isInitialized) { await connection.initialize(); } }, "dropDatabase"); var revertMigration = /* @__PURE__ */ __name(async (dataSource) => { if (dataSource.isInitialized) { await dataSource.undoLastMigration(); } else { console.error("DataSource is not initialized"); } }, "revertMigration"); var resetDatabase = /* @__PURE__ */ __name(async (dbName) => { await dropDatabase(dbName); const connection = await getDbConnection(dbName); await connection.runMigrations(); }, "resetDatabase"); // src/agentCreator.ts var import_core = require("@veramo/core"); // src/objectCreator.ts var import_jsonpointer = require("jsonpointer"); var import_url_parse = __toESM(require("url-parse"), 1); async function createObjects(config, pointers) { const objects = {}; async function resolveRefs(input) { if (Array.isArray(input)) { const resolved = []; for (const item of input) { resolved.push(await resolveRefs(item)); } return resolved; } if (typeof input === "object") { const resolved = {}; for (const property in input) { if (input.hasOwnProperty(property)) { if (property === "$ref") { const pointer = input[property]; return await objectFromPointer(pointer); } else if (property === "$require") { return await objectFromConfig(input); } else if (property === "$env") { return process.env[input[property]]; } else { resolved[property] = await resolveRefs(input[property]); } } } return resolved; } return input; } __name(resolveRefs, "resolveRefs"); async function objectFromConfig(objectConfig) { console.log("Requiring", objectConfig["$require"]); const parsed = (0, import_url_parse.default)(objectConfig["$require"], {}, true); let npmModule = parsed.pathname; const member = parsed.hash.length > 1 ? parsed.hash.slice(1) : void 0; console.log(`member: ${member}`); const type = parsed.query["t"] || "class"; const pointer = parsed.query["p"]; const args = objectConfig["$args"]; console.log({ module, member, type, query: parsed.query, pointer, args }); if (npmModule.slice(0, 2) === "./" || npmModule.slice(0, 3) === "../") { console.log("objectFromConfig: Resolving relative path", npmModule); const { resolve } = await import("path"); npmModule = resolve(npmModule); } const resolvedArgs = args !== void 0 ? await resolveRefs(args) : []; console.error(`npmModule: ${npmModule}`); return await Promise.resolve(await import( /*@metro-ignore*/ npmModule ).then((mod) => { if (member) { return mod[member]; } return mod; }).then((required) => { let object; if (type === "class") { object = new required(...resolvedArgs); } else if (type === "function") { object = required(...resolvedArgs); } else if (type === "object") { object = required; } else { console.error(`Likely we have a bug in agent object creation. type = ${type} is not of type class, function or object`); } if (!pointer) { return object; } if (!object) { return Promise.reject(Error(`Error creating ${npmModule}['${member}']: Object is undefined and pointer was present requiring an object.`)); } return (0, import_jsonpointer.get)(object, pointer); }).catch((e) => { console.error(e); return Promise.reject(Error(`Error creating ${npmModule}['${member}']: ${e.message}`)); })); } __name(objectFromConfig, "objectFromConfig"); async function objectFromPointer(pointer) { const existingObject = (0, import_jsonpointer.get)(objects, pointer); if (existingObject) { return existingObject; } else { const objectConfig = (0, import_jsonpointer.get)(config, pointer); if (!objectConfig) throw Error("Pointer not found: " + pointer); try { let object; if (objectConfig["$require"]) { object = await objectFromConfig(objectConfig); } else if (objectConfig["$env"]) { object = process.env[objectConfig["$env"]]; } else { object = await resolveRefs(objectConfig); } (0, import_jsonpointer.set)(objects, pointer, object); return object; } catch (e) { console.log(e); throw Error(e.message + ". While creating object from pointer: " + pointer); } } } __name(objectFromPointer, "objectFromPointer"); const result = {}; for (const key of Object.keys(pointers)) { if (pointers.hasOwnProperty(key)) { result[key] = await objectFromPointer(pointers[key]); } } return result; } __name(createObjects, "createObjects"); // src/agentCreator.ts var import_yaml = __toESM(require("yaml"), 1); async function createAgentFromConfig(config) { const { agent } = await createObjects(config, { agent: "/agent" }); return agent; } __name(createAgentFromConfig, "createAgentFromConfig"); async function createAgent(options) { return new import_core.Agent(options); } __name(createAgent, "createAgent"); var getConfig = /* @__PURE__ */ __name(async (filePath) => { let fileContent; try { const fs = await import( /* webpackIgnore: true */ "fs" ); fileContent = await fs.promises.readFile(filePath, "utf8"); } catch (e) { console.log("Config file not found: " + filePath); console.log('Use "veramo config create" to create one'); process.exit(1); } let config; try { config = import_yaml.default.parse(fileContent, { prettyErrors: true }); } catch (e) { console.error(`Unable to parse config file: ${e.message} ${e.linePos}`); process.exit(1); } if (config?.version != 3) { console.error("Unsupported configuration file version:", config.version); process.exit(1); } return config; }, "getConfig"); async function getAgent(fileName) { try { return await createAgentFromConfig(await getConfig(fileName)); } catch (e) { console.log("Unable to create agent from " + fileName + ".", e.message); process.exit(1); } } __name(getAgent, "getAgent"); // src/typeormTypes.ts var getDbType = /* @__PURE__ */ __name((opts) => { const type = (typeof process === "object" ? process?.env?.DB_TYPE : void 0) ?? DataSources.singleInstance().defaultDbType ?? opts?.defaultType; if (!type) { throw Error(`Could not determine DB type. Please set the DB_TYPE global variable or env var to one of 'postgres' or 'sqlite'`); } return type; }, "getDbType"); var typeOrmDateTime = /* @__PURE__ */ __name((opts) => { switch (getDbType(opts)) { case "postgres": return "timestamp"; case "sqlite": case "react-native": return "datetime"; default: throw Error(`DB type ${getDbType(opts)} not supported. Right now only sqlite, react-native and postgresql are supported`); } }, "typeOrmDateTime"); var typeormDate = /* @__PURE__ */ __name((opts) => { return "date"; }, "typeormDate"); //# sourceMappingURL=index.cjs.map