@event-driven-io/pongo 0.16.2 → 0.16.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-CYDDN3CZ.js +76 -0
- package/dist/chunk-CYDDN3CZ.js.map +1 -0
- package/dist/{chunk-OXJNRAMF.cjs → chunk-PUUNCOTH.cjs} +4 -4
- package/dist/chunk-PUUNCOTH.cjs.map +1 -0
- package/dist/cli.cjs +3 -3
- package/dist/cli.js +2 -2
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/shim.cjs +1 -1
- package/dist/shim.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-OXJNRAMF.cjs.map +0 -1
- package/dist/chunk-UETA4FKN.js +0 -76
- package/dist/chunk-UETA4FKN.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/postgres/sqlBuilder/index.ts","../src/core/collection/pongoCollection.ts","../src/postgres/dbClient.ts","../src/core/collection/query.ts","../src/core/errors/index.ts","../src/core/pongoClient.ts","../src/core/pongoDb.ts"],"names":["isPostgresClientOptions","options","NodePostgresConnectorType","postgresDb","connectionString","dbName","databaseName","getDatabaseNameOrDefault","pool","dumbo","collections","command","sql","transactionExecutorOrDefault","db","query","collectionName","pongoCollection","postgresSQLBuilder","handle","schemaComponent","c","runPostgreSQLMigrations","dbsSchema","dbSchema","objectEntries","e","proxyPongoDbWithSchema","pongoDbSchemaComponent","components","pongoCollectionSchemaComponent","enlistIntoTransactionIfActive","transaction","defaultSqlExecutor","SqlFor","schema","errors","sqlExecutor","shouldMigrate","createCollection","ensureCollectionCreated","collection","document","_id","uuid","_version","successful","operationResult","documents","rows","doc","result","d","filter","update","existingDoc","replacement","id","version","operationOptions","byId","existing","expectedVersion","expectedVersionValue","deepEquals","newDoc","insertResult","replaceResult","row","count","single","newName","pongoCollectionPostgreSQLMigrations","QueryOperators","OperatorMap","isOperator","key","hasOperators","value","isNumber","val","isString","PongoError","_PongoError","errorCode","message","ConcurrencyError","_ConcurrencyError","getPongoDb","type"],"mappings":"AAAA,g3CAQO,4BCMoB,ICedA,CAAAA,CACXC,CAAAA,EAEAA,CAAAA,CAAQ,aAAA,GAAkBC,gCAAAA,CAEfC,CAAAA,aACXF,CAAAA,EAC+B,CAC/B,GAAM,CAAE,gBAAA,CAAAG,CAAAA,CAAkB,MAAA,CAAAC,CAAO,CAAA,CAAIJ,CAAAA,CAC/BK,CAAAA,kBAAeD,CAAAA,SAAUE,6CAAAA,CAAyC,GAAA,CAElEC,CAAAA,CAAOC,0BAAAA,CACX,gBAAA,CAAAL,CAAAA,CACA,GAAGH,CAAAA,CAAQ,iBACb,CAAC,CAAA,CAEKS,CAAAA,CAAc,IAAI,GAAA,CAElBC,CAAAA,CAAU,KAAA,CACdC,CAAAA,CACAX,CAAAA,CAAAA,EAAAA,CAGE,MAAMY,CAAAA,CAA6BC,CAAAA,CAAIb,CAAAA,CAASO,CAAAA,CAAK,OAAO,CAAA,CAAA,CAC5D,OAAA,CAAgBI,CAAG,CAAA,CAEjBG,CAAAA,CAAQ,KAAA,CACZH,CAAAA,CACAX,CAAAA,CAAAA,EAAAA,CAEC,MAAMY,CAAAA,CAA6BC,CAAAA,CAAIb,CAAAA,CAASO,CAAAA,CAAK,OAAO,CAAA,CAAA,CAAG,KAAA,CAC9DI,CACF,CAAA,CAEIE,CAAAA,CAAiC,CACrC,aAAA,CAAeb,CAAAA,CAAQ,aAAA,CACvB,YAAA,CAAAK,CAAAA,CACA,OAAA,CAAS,CAAA,CAAA,EAAM,OAAA,CAAQ,OAAA,CAAQ,CAAA,CAC/B,KAAA,CAAO,CAAA,CAAA,EAAME,CAAAA,CAAK,KAAA,CAAM,CAAA,CAExB,WAAA,CAAa,CAAA,CAAA,EAAM,CAAC,GAAGE,CAAAA,CAAY,MAAA,CAAO,CAAC,CAAA,CAC3C,UAAA,CAAaM,CAAAA,EACXC,CAAAA,CAAgB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,CAAA,CAAIxF,CAAAA,CAEhC,EAAA,CAAI,CAACD,CAAAA,CAAwBC,CAAO,CAAA,CAClC,MAAM,IAAI,KAAA,CAAM,CAAA,qBAAA,EAAwBwF,CAAI,CAAA,CAAA;ANC5C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA8CE,GAAA;AAAA;AAsBA,oBAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWqD,oCAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoCrD,oCAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWqD,oCAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA8BrD,oCAAA;AAAA;AAAA;AAAA;AAuBA,SAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQqD,oCAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAmDF,oCAAA","file":"/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/chunk-PUUNCOTH.cjs","sourcesContent":["import {\n isSQL,\n JSONSerializer,\n rawSql,\n sql,\n sqlMigration,\n type SQL,\n type SQLMigration,\n} from '@event-driven-io/dumbo';\nimport {\n expectedVersionValue,\n type DeleteOneOptions,\n type OptionalUnlessRequiredIdAndVersion,\n type PongoCollectionSQLBuilder,\n type PongoFilter,\n type PongoUpdate,\n type ReplaceOneOptions,\n type UpdateOneOptions,\n type WithoutId,\n} from '../../core';\nimport { constructFilterQuery } from './filter';\nimport { buildUpdateQuery } from './update';\n\nconst createCollection = (collectionName: string): SQL =>\n sql(\n `CREATE TABLE IF NOT EXISTS %I (\n _id TEXT PRIMARY KEY, \n data JSONB NOT NULL, \n metadata JSONB NOT NULL DEFAULT '{}',\n _version BIGINT NOT NULL DEFAULT 1,\n _partition TEXT NOT NULL DEFAULT 'png_global',\n _archived BOOLEAN NOT NULL DEFAULT FALSE,\n _created TIMESTAMPTZ NOT NULL DEFAULT now(),\n _updated TIMESTAMPTZ NOT NULL DEFAULT now()\n )`,\n collectionName,\n );\n\nexport const pongoCollectionPostgreSQLMigrations = (collectionName: string) => [\n sqlMigration(`pongoCollection:${collectionName}:001:createtable`, [\n createCollection(collectionName),\n ]),\n];\n\nexport const postgresSQLBuilder = (\n collectionName: string,\n): PongoCollectionSQLBuilder => ({\n migrations: (): SQLMigration[] =>\n pongoCollectionPostgreSQLMigrations(collectionName),\n createCollection: (): SQL => createCollection(collectionName),\n insertOne: <T>(document: OptionalUnlessRequiredIdAndVersion<T>): SQL => {\n return sql(\n 'INSERT INTO %I (_id, data, _version) VALUES (%L, %L, %L) ON CONFLICT(_id) DO NOTHING;',\n collectionName,\n document._id,\n JSONSerializer.serialize(document),\n document._version ?? 1n,\n );\n },\n insertMany: <T>(documents: OptionalUnlessRequiredIdAndVersion<T>[]): SQL => {\n const values = documents\n .map((doc) =>\n sql(\n '(%L, %L, %L)',\n doc._id,\n JSONSerializer.serialize(doc),\n doc._version ?? 1n,\n ),\n )\n .join(', ');\n return sql(\n `INSERT INTO %I (_id, data, _version) VALUES %s \n ON CONFLICT(_id) DO NOTHING\n RETURNING _id;`,\n collectionName,\n values,\n );\n },\n updateOne: <T>(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n options?: UpdateOneOptions,\n ): SQL => {\n const expectedVersion = expectedVersionValue(options?.expectedVersion);\n const expectedVersionUpdate =\n expectedVersion != null ? 'AND %I._version = %L' : '';\n const expectedVersionParams =\n expectedVersion != null ? [collectionName, expectedVersion] : [];\n\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n const updateQuery = isSQL(update) ? update : buildUpdateQuery(update);\n\n return sql(\n `WITH existing AS (\n SELECT _id, _version as current_version\n FROM %I %s \n LIMIT 1\n ),\n updated AS (\n UPDATE %I \n SET \n data = %s || jsonb_build_object('_id', %I._id) || jsonb_build_object('_version', (_version + 1)::text),\n _version = _version + 1\n FROM existing \n WHERE %I._id = existing._id ${expectedVersionUpdate}\n RETURNING %I._id, %I._version\n )\n SELECT \n existing._id,\n COALESCE(updated._version, existing.current_version) AS version,\n COUNT(existing._id) over() AS matched,\n COUNT(updated._id) over() AS modified\n FROM existing\n LEFT JOIN updated \n ON existing._id = updated._id;`,\n collectionName,\n where(filterQuery),\n collectionName,\n updateQuery,\n collectionName,\n collectionName,\n ...expectedVersionParams,\n collectionName,\n collectionName,\n );\n },\n replaceOne: <T>(\n filter: PongoFilter<T> | SQL,\n document: WithoutId<T>,\n options?: ReplaceOneOptions,\n ): SQL => {\n const expectedVersion = expectedVersionValue(options?.expectedVersion);\n const expectedVersionUpdate =\n expectedVersion != null ? 'AND %I._version = %L' : '';\n const expectedVersionParams =\n expectedVersion != null ? [collectionName, expectedVersion] : [];\n\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n\n return sql(\n `WITH existing AS (\n SELECT _id, _version as current_version\n FROM %I %s \n LIMIT 1\n ),\n updated AS (\n UPDATE %I \n SET \n data = %L || jsonb_build_object('_id', %I._id) || jsonb_build_object('_version', (_version + 1)::text),\n _version = _version + 1\n FROM existing \n WHERE %I._id = existing._id ${expectedVersionUpdate}\n RETURNING %I._id, %I._version\n )\n SELECT \n existing._id,\n COALESCE(updated._version, existing.current_version) AS version,\n COUNT(existing._id) over() AS matched,\n COUNT(updated._id) over() AS modified\n FROM existing\n LEFT JOIN updated \n ON existing._id = updated._id;`,\n collectionName,\n where(filterQuery),\n collectionName,\n JSONSerializer.serialize(document),\n collectionName,\n collectionName,\n ...expectedVersionParams,\n collectionName,\n collectionName,\n );\n },\n updateMany: <T>(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n ): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n const updateQuery = isSQL(update) ? update : buildUpdateQuery(update);\n\n return sql(\n `UPDATE %I \n SET \n data = %s || jsonb_build_object('_version', (_version + 1)::text),\n _version = _version + 1\n %s;`,\n collectionName,\n updateQuery,\n where(filterQuery),\n );\n },\n deleteOne: <T>(\n filter: PongoFilter<T> | SQL,\n options?: DeleteOneOptions,\n ): SQL => {\n const expectedVersion = expectedVersionValue(options?.expectedVersion);\n const expectedVersionUpdate =\n expectedVersion != null ? 'AND %I._version = %L' : '';\n const expectedVersionParams =\n expectedVersion != null ? [collectionName, expectedVersion] : [];\n\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n\n return sql(\n `WITH existing AS (\n SELECT _id\n FROM %I %s \n LIMIT 1\n ),\n deleted AS (\n DELETE FROM %I\n USING existing\n WHERE %I._id = existing._id ${expectedVersionUpdate}\n RETURNING %I._id\n )\n SELECT \n existing._id,\n COUNT(existing._id) over() AS matched,\n COUNT(deleted._id) over() AS deleted\n FROM existing\n LEFT JOIN deleted \n ON existing._id = deleted._id;`,\n collectionName,\n where(filterQuery),\n collectionName,\n collectionName,\n ...expectedVersionParams,\n collectionName,\n );\n },\n deleteMany: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n\n return sql('DELETE FROM %I %s', collectionName, where(filterQuery));\n },\n findOne: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n\n return sql(\n 'SELECT data FROM %I %s LIMIT 1;',\n collectionName,\n where(filterQuery),\n );\n },\n find: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n return sql('SELECT data FROM %I %s;', collectionName, where(filterQuery));\n },\n countDocuments: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n return sql(\n 'SELECT COUNT(1) as count FROM %I %s;',\n collectionName,\n where(filterQuery),\n );\n },\n rename: (newName: string): SQL =>\n sql('ALTER TABLE %I RENAME TO %I;', collectionName, newName),\n drop: (targetName: string = collectionName): SQL =>\n sql('DROP TABLE IF EXISTS %I', targetName),\n});\n\nconst where = (filter: string): SQL =>\n filter.length > 0 ? sql('WHERE %s', filter) : rawSql('');\n","import {\n runPostgreSQLMigrations,\n schemaComponent,\n single,\n type DatabaseTransaction,\n type Dumbo,\n type MigrationStyle,\n type QueryResult,\n type QueryResultRow,\n type SchemaComponent,\n type SQL,\n type SQLExecutor,\n type SQLMigration,\n} from '@event-driven-io/dumbo';\nimport { v7 as uuid } from 'uuid';\nimport {\n deepEquals,\n expectedVersionValue,\n operationResult,\n type CollectionOperationOptions,\n type DeleteManyOptions,\n type DeleteOneOptions,\n type DocumentHandler,\n type HandleOptions,\n type InsertManyOptions,\n type InsertOneOptions,\n type OptionalUnlessRequiredIdAndVersion,\n type PongoCollection,\n type PongoDb,\n type PongoDeleteResult,\n type PongoDocument,\n type PongoFilter,\n type PongoHandleResult,\n type PongoInsertManyResult,\n type PongoInsertOneResult,\n type PongoUpdate,\n type PongoUpdateManyResult,\n type PongoUpdateResult,\n type ReplaceOneOptions,\n type UpdateManyOptions,\n type UpdateOneOptions,\n type WithIdAndVersion,\n type WithoutId,\n type WithVersion,\n} from '..';\nimport { pongoCollectionPostgreSQLMigrations } from '../../postgres';\n\nexport type PongoCollectionOptions<ConnectorType extends string = string> = {\n db: PongoDb<ConnectorType>;\n collectionName: string;\n pool: Dumbo;\n sqlBuilder: PongoCollectionSQLBuilder;\n schema?: { autoMigration?: MigrationStyle };\n errors?: { throwOnOperationFailures?: boolean };\n};\n\nconst enlistIntoTransactionIfActive = async <\n ConnectorType extends string = string,\n>(\n db: PongoDb<ConnectorType>,\n options: CollectionOperationOptions | undefined,\n): Promise<DatabaseTransaction | null> => {\n const transaction = options?.session?.transaction;\n\n if (!transaction || !transaction.isActive) return null;\n\n return await transaction.enlistDatabase(db);\n};\n\nexport const transactionExecutorOrDefault = async <\n ConnectorType extends string = string,\n>(\n db: PongoDb<ConnectorType>,\n options: CollectionOperationOptions | undefined,\n defaultSqlExecutor: SQLExecutor,\n): Promise<SQLExecutor> => {\n const existingTransaction = await enlistIntoTransactionIfActive(db, options);\n return existingTransaction?.execute ?? defaultSqlExecutor;\n};\n\nexport const pongoCollection = <\n T extends PongoDocument,\n ConnectorType extends string = string,\n>({\n db,\n collectionName,\n pool,\n sqlBuilder: SqlFor,\n schema,\n errors,\n}: PongoCollectionOptions<ConnectorType>): PongoCollection<T> => {\n const sqlExecutor = pool.execute;\n const command = async <Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ) =>\n (\n await transactionExecutorOrDefault(db, options, sqlExecutor)\n ).command<Result>(sql);\n\n const query = async <T extends QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ) =>\n (await transactionExecutorOrDefault(db, options, sqlExecutor)).query<T>(\n sql,\n );\n\n let shouldMigrate = schema?.autoMigration !== 'None';\n\n const createCollection = (options?: CollectionOperationOptions) => {\n shouldMigrate = false;\n\n if (options?.session) return command(SqlFor.createCollection(), options);\n else return command(SqlFor.createCollection());\n };\n\n const ensureCollectionCreated = (options?: CollectionOperationOptions) => {\n if (!shouldMigrate) {\n return Promise.resolve();\n }\n\n return createCollection(options);\n };\n\n const collection = {\n dbName: db.databaseName,\n collectionName,\n createCollection: async (options?: CollectionOperationOptions) => {\n await createCollection(options);\n },\n insertOne: async (\n document: OptionalUnlessRequiredIdAndVersion<T>,\n options?: InsertOneOptions,\n ): Promise<PongoInsertOneResult> => {\n await ensureCollectionCreated(options);\n\n const _id = (document._id as string | undefined | null) ?? uuid();\n const _version = document._version ?? 1n;\n\n const result = await command(\n SqlFor.insertOne({\n ...document,\n _id,\n _version,\n } as OptionalUnlessRequiredIdAndVersion<T>),\n options,\n );\n\n const successful = (result.rowCount ?? 0) > 0;\n\n return operationResult<PongoInsertOneResult>(\n {\n successful,\n insertedId: successful ? _id : null,\n nextExpectedVersion: _version,\n },\n { operationName: 'insertOne', collectionName, errors },\n );\n },\n insertMany: async (\n documents: OptionalUnlessRequiredIdAndVersion<T>[],\n options?: InsertManyOptions,\n ): Promise<PongoInsertManyResult> => {\n await ensureCollectionCreated(options);\n\n const rows = documents.map((doc) => ({\n ...doc,\n _id: (doc._id as string | undefined | null) ?? uuid(),\n _version: doc._version ?? 1n,\n }));\n\n const result = await command(\n SqlFor.insertMany(rows as OptionalUnlessRequiredIdAndVersion<T>[]),\n options,\n );\n\n return operationResult<PongoInsertManyResult>(\n {\n successful: result.rowCount === rows.length,\n insertedCount: result.rowCount ?? 0,\n insertedIds: result.rows.map((d) => d._id as string),\n },\n { operationName: 'insertMany', collectionName, errors },\n );\n },\n updateOne: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: UpdateOneOptions,\n ): Promise<PongoUpdateResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command<UpdateSqlResult>(\n SqlFor.updateOne(filter, update, options),\n options,\n );\n\n return operationResult<PongoUpdateResult>(\n {\n successful:\n result.rows.length > 0 &&\n result.rows[0]!.modified === result.rows[0]!.matched,\n modifiedCount: Number(result.rows[0]?.modified ?? 0),\n matchedCount: Number(result.rows[0]?.matched ?? 0),\n nextExpectedVersion: result.rows[0]?.version ?? 0n,\n },\n { operationName: 'updateOne', collectionName, errors },\n );\n },\n replaceOne: async (\n filter: PongoFilter<T>,\n document: WithoutId<T>,\n options?: ReplaceOneOptions,\n ): Promise<PongoUpdateResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command<UpdateSqlResult>(\n SqlFor.replaceOne(filter, document, options),\n options,\n );\n return operationResult<PongoUpdateResult>(\n {\n successful: result.rows.length > 0 && result.rows[0]!.modified > 0,\n modifiedCount: Number(result.rows[0]?.modified ?? 0),\n matchedCount: Number(result.rows[0]?.matched ?? 0),\n nextExpectedVersion: result.rows[0]?.version ?? 0n,\n },\n { operationName: 'replaceOne', collectionName, errors },\n );\n },\n updateMany: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: UpdateManyOptions,\n ): Promise<PongoUpdateManyResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.updateMany(filter, update), options);\n\n return operationResult<PongoUpdateManyResult>(\n {\n successful: true,\n modifiedCount: result.rowCount ?? 0,\n matchedCount: result.rowCount ?? 0,\n },\n { operationName: 'updateMany', collectionName, errors },\n );\n },\n deleteOne: async (\n filter?: PongoFilter<T>,\n options?: DeleteOneOptions,\n ): Promise<PongoDeleteResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command<DeleteSqlResult>(\n SqlFor.deleteOne(filter ?? {}, options),\n options,\n );\n return operationResult<PongoDeleteResult>(\n {\n successful: result.rows.length > 0 && result.rows[0]!.deleted! > 0,\n deletedCount: Number(result.rows[0]?.deleted ?? 0),\n matchedCount: Number(result.rows[0]?.matched ?? 0),\n },\n { operationName: 'deleteOne', collectionName, errors },\n );\n },\n deleteMany: async (\n filter?: PongoFilter<T>,\n options?: DeleteManyOptions,\n ): Promise<PongoDeleteResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.deleteMany(filter ?? {}), options);\n\n return operationResult<PongoDeleteResult>(\n {\n successful: (result.rowCount ?? 0) > 0,\n deletedCount: result.rowCount ?? 0,\n matchedCount: result.rowCount ?? 0,\n },\n { operationName: 'deleteMany', collectionName, errors },\n );\n },\n findOne: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<WithIdAndVersion<T> | null> => {\n await ensureCollectionCreated(options);\n\n const result = await query(SqlFor.findOne(filter ?? {}), options);\n return (result.rows[0]?.data ?? null) as WithIdAndVersion<T> | null;\n },\n findOneAndDelete: async (\n filter: PongoFilter<T>,\n options?: DeleteOneOptions,\n ): Promise<WithIdAndVersion<T> | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.deleteOne(filter, options);\n return existingDoc;\n },\n findOneAndReplace: async (\n filter: PongoFilter<T>,\n replacement: WithoutId<T>,\n options?: ReplaceOneOptions,\n ): Promise<WithIdAndVersion<T> | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.replaceOne(filter, replacement, options);\n\n return existingDoc;\n },\n findOneAndUpdate: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: UpdateOneOptions,\n ): Promise<WithIdAndVersion<T> | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.updateOne(filter, update, options);\n\n return existingDoc;\n },\n handle: async (\n id: string,\n handle: DocumentHandler<T>,\n options?: HandleOptions,\n ): Promise<PongoHandleResult<T>> => {\n const { expectedVersion: version, ...operationOptions } = options ?? {};\n await ensureCollectionCreated(options);\n\n const byId: PongoFilter<T> = { _id: id };\n\n const existing = (await collection.findOne(\n byId,\n options,\n )) as WithVersion<T> | null;\n\n const expectedVersion = expectedVersionValue(version);\n\n if (\n (existing == null && version === 'DOCUMENT_EXISTS') ||\n (existing == null && expectedVersion != null) ||\n (existing != null && version === 'DOCUMENT_DOES_NOT_EXIST') ||\n (existing != null &&\n expectedVersion !== null &&\n existing._version !== expectedVersion)\n ) {\n return operationResult<PongoHandleResult<T>>(\n {\n successful: false,\n document: existing as T,\n },\n { operationName: 'handle', collectionName, errors },\n );\n }\n\n const result = await handle(\n existing !== null ? ({ ...existing } as T) : null,\n );\n\n if (deepEquals(existing as T | null, result))\n return operationResult<PongoHandleResult<T>>(\n {\n successful: true,\n document: existing as T | null,\n },\n { operationName: 'handle', collectionName, errors },\n );\n\n if (!existing && result) {\n const newDoc = { ...result, _id: id };\n const insertResult = await collection.insertOne(\n { ...newDoc, _id: id } as OptionalUnlessRequiredIdAndVersion<T>,\n {\n ...operationOptions,\n expectedVersion: 'DOCUMENT_DOES_NOT_EXIST',\n },\n );\n return {\n ...insertResult,\n document: {\n ...newDoc,\n _version: insertResult.nextExpectedVersion,\n } as T,\n };\n }\n\n if (existing && !result) {\n const deleteResult = await collection.deleteOne(byId, {\n ...operationOptions,\n expectedVersion: expectedVersion ?? 'DOCUMENT_EXISTS',\n });\n return { ...deleteResult, document: null };\n }\n\n if (existing && result) {\n const replaceResult = await collection.replaceOne(byId, result, {\n ...operationOptions,\n expectedVersion: expectedVersion ?? 'DOCUMENT_EXISTS',\n });\n return {\n ...replaceResult,\n document: {\n ...result,\n _version: replaceResult.nextExpectedVersion,\n } as T,\n };\n }\n\n return operationResult<PongoHandleResult<T>>(\n {\n successful: true,\n document: existing as T,\n },\n { operationName: 'handle', collectionName, errors },\n );\n },\n find: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<WithIdAndVersion<T>[]> => {\n await ensureCollectionCreated(options);\n\n const result = await query(SqlFor.find(filter ?? {}));\n return result.rows.map((row) => row.data as WithIdAndVersion<T>);\n },\n countDocuments: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<number> => {\n await ensureCollectionCreated(options);\n\n const { count } = await single(\n query<{ count: number }>(SqlFor.countDocuments(filter ?? {})),\n );\n return count;\n },\n drop: async (options?: CollectionOperationOptions): Promise<boolean> => {\n await ensureCollectionCreated(options);\n const result = await command(SqlFor.drop());\n return (result?.rowCount ?? 0) > 0;\n },\n rename: async (\n newName: string,\n options?: CollectionOperationOptions,\n ): Promise<PongoCollection<T>> => {\n await ensureCollectionCreated(options);\n await command(SqlFor.rename(newName));\n collectionName = newName;\n return collection;\n },\n\n sql: {\n async query<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<Result[]> {\n await ensureCollectionCreated(options);\n\n const result = await query<Result>(sql, options);\n return result.rows;\n },\n async command<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<QueryResult<Result>> {\n await ensureCollectionCreated(options);\n\n return command(sql, options);\n },\n },\n schema: {\n get component(): SchemaComponent {\n return schemaComponent('pongo:schema_component:collection', {\n migrations: SqlFor.migrations,\n });\n },\n migrate: () => runPostgreSQLMigrations(pool, SqlFor.migrations()), // TODO: This needs to change to support more connectors\n },\n };\n\n return collection;\n};\n\nexport const pongoCollectionSchemaComponent = (collectionName: string) =>\n schemaComponent('pongo:schema_component:collection', {\n migrations: () => pongoCollectionPostgreSQLMigrations(collectionName), // TODO: This needs to change to support more connectors\n });\n\nexport type PongoCollectionSQLBuilder = {\n migrations: () => SQLMigration[];\n createCollection: () => SQL;\n insertOne: <T>(document: OptionalUnlessRequiredIdAndVersion<T>) => SQL;\n insertMany: <T>(documents: OptionalUnlessRequiredIdAndVersion<T>[]) => SQL;\n updateOne: <T>(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n options?: UpdateOneOptions,\n ) => SQL;\n replaceOne: <T>(\n filter: PongoFilter<T> | SQL,\n document: WithoutId<T>,\n options?: ReplaceOneOptions,\n ) => SQL;\n updateMany: <T>(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n ) => SQL;\n deleteOne: <T>(\n filter: PongoFilter<T> | SQL,\n options?: DeleteOneOptions,\n ) => SQL;\n deleteMany: <T>(filter: PongoFilter<T> | SQL) => SQL;\n findOne: <T>(filter: PongoFilter<T> | SQL) => SQL;\n find: <T>(filter: PongoFilter<T> | SQL) => SQL;\n countDocuments: <T>(filter: PongoFilter<T> | SQL) => SQL;\n rename: (newName: string) => SQL;\n drop: () => SQL;\n};\n\ntype UpdateSqlResult = {\n matched: bigint;\n modified: bigint;\n version: bigint;\n};\n\ntype DeleteSqlResult = {\n matched: bigint | null;\n deleted: bigint | null;\n};\n","import {\n dumbo,\n getDatabaseNameOrDefault,\n NodePostgresConnectorType,\n runPostgreSQLMigrations,\n schemaComponent,\n SQL,\n type PostgresConnector,\n type PostgresPoolOptions,\n type QueryResult,\n type QueryResultRow,\n type SchemaComponent,\n} from '@event-driven-io/dumbo';\nimport type { Document } from 'mongodb';\nimport {\n objectEntries,\n pongoCollection,\n pongoCollectionSchemaComponent,\n proxyPongoDbWithSchema,\n transactionExecutorOrDefault,\n type CollectionOperationOptions,\n type PongoCollection,\n type PongoDb,\n type PongoDbClientOptions,\n} from '../core';\nimport { postgresSQLBuilder } from './sqlBuilder';\n\nexport type PostgresDbClientOptions = PongoDbClientOptions<PostgresConnector>;\n\nexport const isPostgresClientOptions = (\n options: PongoDbClientOptions,\n): options is PostgresDbClientOptions =>\n options.connectorType === NodePostgresConnectorType;\n\nexport const postgresDb = (\n options: PostgresDbClientOptions,\n): PongoDb<PostgresConnector> => {\n const { connectionString, dbName } = options;\n const databaseName = dbName ?? getDatabaseNameOrDefault(connectionString);\n\n const pool = dumbo<PostgresPoolOptions>({\n connectionString,\n ...options.connectionOptions,\n });\n\n const collections = new Map<string, PongoCollection<Document>>();\n\n const command = async <Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ) =>\n (\n await transactionExecutorOrDefault(db, options, pool.execute)\n ).command<Result>(sql);\n\n const query = async <T extends QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ) =>\n (await transactionExecutorOrDefault(db, options, pool.execute)).query<T>(\n sql,\n );\n\n const db: PongoDb<PostgresConnector> = {\n connectorType: options.connectorType,\n databaseName,\n connect: () => Promise.resolve(),\n close: () => pool.close(),\n\n collections: () => [...collections.values()],\n collection: (collectionName) =>\n pongoCollection({\n collectionName,\n db,\n pool,\n sqlBuilder: postgresSQLBuilder(collectionName),\n schema: options.schema ? options.schema : {},\n errors: options.errors ? options.errors : {},\n }),\n transaction: () => pool.transaction(),\n withTransaction: (handle) => pool.withTransaction(handle),\n\n schema: {\n get component(): SchemaComponent {\n return schemaComponent('pongoDb', {\n components: [...collections.values()].map((c) => c.schema.component),\n });\n },\n migrate: () =>\n runPostgreSQLMigrations(\n pool,\n [...collections.values()].flatMap((c) =>\n // TODO: This needs to change to support more connectors\n c.schema.component.migrations({ connector: 'PostgreSQL:pg' }),\n ),\n ),\n },\n\n sql: {\n async query<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<Result[]> {\n const result = await query<Result>(sql, options);\n return result.rows;\n },\n async command<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<QueryResult<Result>> {\n return command(sql, options);\n },\n },\n };\n\n const dbsSchema = options?.schema?.definition?.dbs;\n\n if (dbsSchema) {\n const dbSchema = objectEntries(dbsSchema)\n .map((e) => e[1])\n .find((db) => db.name === dbName || db.name === databaseName);\n\n if (dbSchema) return proxyPongoDbWithSchema(db, dbSchema, collections);\n }\n\n return db;\n};\n\nexport const pongoDbSchemaComponent = (\n collections: string[] | SchemaComponent[],\n) => {\n const components =\n collections.length > 0 && typeof collections[0] === 'string'\n ? collections.map((collectionName) =>\n pongoCollectionSchemaComponent(collectionName as string),\n )\n : (collections as SchemaComponent[]);\n\n return schemaComponent('pongo:schema_component:db', {\n components,\n });\n};\n","export const QueryOperators = {\n $eq: '$eq',\n $gt: '$gt',\n $gte: '$gte',\n $lt: '$lt',\n $lte: '$lte',\n $ne: '$ne',\n $in: '$in',\n $nin: '$nin',\n $elemMatch: '$elemMatch',\n $all: '$all',\n $size: '$size',\n};\n\nexport const OperatorMap = {\n $gt: '>',\n $gte: '>=',\n $lt: '<',\n $lte: '<=',\n $ne: '!=',\n};\n\nexport const isOperator = (key: string) => key.startsWith('$');\n\nexport const hasOperators = (value: Record<string, unknown>) =>\n Object.keys(value).some(isOperator);\n","export const isNumber = (val: unknown): val is number =>\n typeof val === 'number' && val === val;\n\nexport const isString = (val: unknown): val is string =>\n typeof val === 'string';\n\nexport class PongoError extends Error {\n public errorCode: number;\n\n constructor(\n options?: { errorCode: number; message?: string } | string | number,\n ) {\n const errorCode =\n options && typeof options === 'object' && 'errorCode' in options\n ? options.errorCode\n : isNumber(options)\n ? options\n : 500;\n const message =\n options && typeof options === 'object' && 'message' in options\n ? options.message\n : isString(options)\n ? options\n : `Error with status code '${errorCode}' ocurred during Pongo processing`;\n\n super(message);\n this.errorCode = errorCode;\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, PongoError.prototype);\n }\n}\n\nexport class ConcurrencyError extends PongoError {\n constructor(message?: string) {\n super({\n errorCode: 412,\n message: message ?? `Expected document state does not match current one!`,\n });\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, ConcurrencyError.prototype);\n }\n}\n","import {\n NodePostgresConnectorType,\n type MigrationStyle,\n type NodePostgresConnection,\n} from '@event-driven-io/dumbo';\nimport pg from 'pg';\nimport type { PostgresDbClientOptions } from '../postgres';\nimport { getPongoDb, type AllowedDbClientOptions } from './pongoDb';\nimport { pongoSession } from './pongoSession';\nimport {\n proxyClientWithSchema,\n type PongoClientSchema,\n type PongoClientWithSchema,\n} from './schema';\nimport type { PongoClient, PongoDb, PongoSession } from './typing';\n\nexport type PooledPongoClientOptions =\n | {\n pool: pg.Pool;\n }\n | {\n pooled: true;\n }\n | {\n pool: pg.Pool;\n pooled: true;\n }\n | object;\n\nexport type NotPooledPongoOptions =\n | {\n client: pg.Client;\n }\n | {\n pooled: false;\n }\n | {\n client: pg.Client;\n pooled: false;\n }\n | {\n connection: NodePostgresConnection;\n pooled?: false;\n };\n\nexport type PongoClientOptions<\n TypedClientSchema extends PongoClientSchema = PongoClientSchema,\n> = {\n schema?: { autoMigration?: MigrationStyle; definition?: TypedClientSchema };\n errors?: { throwOnOperationFailures?: boolean };\n connectionOptions?: PooledPongoClientOptions | NotPooledPongoOptions;\n};\n\nexport const pongoClient = <\n TypedClientSchema extends PongoClientSchema = PongoClientSchema,\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(\n connectionString: string,\n options: PongoClientOptions<TypedClientSchema> = {},\n): PongoClient & PongoClientWithSchema<TypedClientSchema> => {\n const dbClients = new Map<string, PongoDb>();\n\n const dbClient = getPongoDb<DbClientOptions>(\n clientToDbOptions({\n connectionString,\n clientOptions: options,\n }),\n );\n dbClients.set(dbClient.databaseName, dbClient);\n\n const pongoClient: PongoClient = {\n connect: async () => {\n await dbClient.connect();\n return pongoClient;\n },\n close: async () => {\n for (const db of dbClients.values()) {\n await db.close();\n }\n },\n db: (dbName?: string): PongoDb => {\n if (!dbName) return dbClient;\n\n return (\n dbClients.get(dbName) ??\n dbClients\n .set(\n dbName,\n getPongoDb<DbClientOptions>(\n clientToDbOptions({\n connectionString,\n dbName,\n clientOptions: options,\n }),\n ),\n )\n .get(dbName)!\n );\n },\n startSession: pongoSession,\n withSession: async <T>(\n callback: (session: PongoSession) => Promise<T>,\n ): Promise<T> => {\n const session = pongoSession();\n\n try {\n return await callback(session);\n } finally {\n await session.endSession();\n }\n },\n };\n\n return proxyClientWithSchema(pongoClient, options?.schema?.definition);\n};\n\nexport const clientToDbOptions = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(options: {\n connectionString: string;\n dbName?: string;\n clientOptions: PongoClientOptions;\n}): DbClientOptions => {\n const postgreSQLOptions: PostgresDbClientOptions = {\n connectorType: NodePostgresConnectorType,\n connectionString: options.connectionString,\n dbName: options.dbName,\n ...options.clientOptions,\n };\n\n return postgreSQLOptions as DbClientOptions;\n};\n","import {\n isPostgresClientOptions,\n postgresDb,\n type PostgresDbClientOptions,\n} from '../postgres';\nimport type { PongoClientOptions } from './pongoClient';\nimport type { PongoDb } from './typing';\n\nexport type PongoDbClientOptions<ConnectorType extends string = string> = {\n connectorType: ConnectorType;\n connectionString: string;\n dbName: string | undefined;\n} & PongoClientOptions;\n\nexport type AllowedDbClientOptions = PostgresDbClientOptions;\n\nexport const getPongoDb = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(\n options: DbClientOptions,\n): PongoDb => {\n const { connectorType: type } = options;\n // This is the place where in the future could come resolution of other database types\n if (!isPostgresClientOptions(options))\n throw new Error(`Unsupported db type: ${type}`);\n\n return postgresDb(options);\n};\n"]}
|
package/dist/cli.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var
|
|
2
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var _chunkPUUNCOTHcjs = require('./chunk-PUUNCOTH.cjs');var _commander = require('commander');var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);var w=o=>{if(o.length===0)return o;let e=o.charAt(0).toUpperCase()+o.slice(1);return e.endsWith("s")&&(e=e.slice(0,-1)),e},l=(o=["users"])=>{let e=o.map(n=>`export type ${w(n)} = { name: string; description: string; date: Date }`).join(`
|
|
3
3
|
`),i=o.map(n=>` ${n}: pongoSchema.collection<${w(n)}>('${n}'),`).join(`
|
|
4
4
|
`);return`import { pongoSchema } from '@event-driven-io/pongo';
|
|
5
5
|
|
|
@@ -21,8 +21,8 @@ ${l()}`,G=`Error: Config should have a default database defined (without name or
|
|
|
21
21
|
|
|
22
22
|
${l()}`,D=`Error: Database should have defined at least one collection, e.g.
|
|
23
23
|
|
|
24
|
-
${l()}`,L=async o=>{let e=new URL(o,`file://${process.cwd()}/`);try{let i=await Promise.resolve().then(() => _interopRequireWildcard(require(e.href))),n=B(i);return typeof n=="string"&&(console.error(n),process.exit(1)),n}catch (e2){console.error(`Error: Couldn't load file: ${e.href}`),process.exit(1)}},W=(o,e)=>{try{_fs2.default.writeFileSync(o,l(e),"utf8"),console.log(`Configuration file stored at: ${o}`)}catch(i){console.error(`Error: Couldn't store config file: ${o}!`),console.error(i),process.exit(1)}},B=o=>{if(!o.default)return I;if(!o.default.schema)return _;if(!o.default.schema.dbs)return $;let i=
|
|
24
|
+
${l()}`,L=async o=>{let e=new URL(o,`file://${process.cwd()}/`);try{let i=await Promise.resolve().then(() => _interopRequireWildcard(require(e.href))),n=B(i);return typeof n=="string"&&(console.error(n),process.exit(1)),n}catch (e2){console.error(`Error: Couldn't load file: ${e.href}`),process.exit(1)}},W=(o,e)=>{try{_fs2.default.writeFileSync(o,l(e),"utf8"),console.log(`Configuration file stored at: ${o}`)}catch(i){console.error(`Error: Couldn't store config file: ${o}!`),console.error(i),process.exit(1)}},B=o=>{if(!o.default)return I;if(!o.default.schema)return _;if(!o.default.schema.dbs)return $;let i=_chunkPUUNCOTHcjs.t.call(void 0, o.default.schema.dbs).map(t=>t[1]).find(t=>t.name===void 0);return i?!i.collections||_chunkPUUNCOTHcjs.t.call(void 0, i.collections).map(t=>t[1]).length===0?D:_chunkPUUNCOTHcjs.F.call(void 0, i):G},v=new (0, _commander.Command)("config").description("Manage Pongo configuration");v.command("sample").description("Generate or print sample configuration").option("-col, --collection <name>","Specify the collection name",(o,e)=>e.concat([o]),[]).option("-f, --file <path>","Path to configuration file with collection list").option("-g, --generate","Generate sample config file").option("-p, --print","Print sample config file").action(o=>{let e=o.collection.length>0?o.collection:["users"];!("print"in o)&&!("generate"in o)&&(console.error(`Error: Please provide either:
|
|
25
25
|
--print param to print sample config or
|
|
26
26
|
--generate to generate sample config file`),process.exit(1)),"print"in o?console.log(`${l(e)}`):"generate"in o&&(o.file||(console.error("Error: You need to provide a config file through a --file"),process.exit(1)),W(o.file,e))});var _dumbo = require('@event-driven-io/dumbo');var d=new (0, _commander.Command)("migrate").description("Manage database migrations");d.command("run").description("Run database migrations").option("-cs, --connection-string <string>","Connection string for the database").option("-col, --collection <name>","Specify the collection name",(o,e)=>e.concat([o]),[]).option("-f, --config <path>","Path to configuration file with Pongo config").option("-dr, --dryRun","Perform dry run without commiting changes",!1).action(async o=>{let{collection:e,dryRun:i}=o,n=_nullishCoalesce(o.connectionString, () => (process.env.DB_CONNECTION_STRING)),t;n||(console.error(`Error: Connection string is required. Provide it either as a "--connection-string" parameter or through the DB_CONNECTION_STRING environment variable.
|
|
27
|
-
For instance: --connection-string postgresql://postgres:postgres@localhost:5432/postgres`),process.exit(1)),o.config?t=(await L(o.config)).collections.map(c=>c.name):e?t=e:(console.error('Error: You need to provide at least one collection name. Provide it either through "--config" file or as a "--collection" parameter.'),process.exit(1));let r=_dumbo.dumbo.call(void 0, {connectionString:n}),s=t.flatMap(g=>
|
|
27
|
+
For instance: --connection-string postgresql://postgres:postgres@localhost:5432/postgres`),process.exit(1)),o.config?t=(await L(o.config)).collections.map(c=>c.name):e?t=e:(console.error('Error: You need to provide at least one collection name. Provide it either through "--config" file or as a "--collection" parameter.'),process.exit(1));let r=_dumbo.dumbo.call(void 0, {connectionString:n}),s=t.flatMap(g=>_chunkPUUNCOTHcjs.h.call(void 0, g).migrations({connector:"PostgreSQL:pg"}));await _dumbo.runPostgreSQLMigrations.call(void 0, r,s,{dryRun:i})});d.command("sql").description("Generate SQL for database migration").option("-col, --collection <name>","Specify the collection name",(o,e)=>e.concat([o]),[]).option("-f, --config <path>","Path to configuration file with Pongo config").option("--print","Print the SQL to the console (default)",!0).action(async o=>{let{collection:e}=o,i;o.config?i=(await L(o.config)).collections.map(s=>s.name):e?i=e:(console.error('Error: You need to provide at least one collection name. Provide it either through "--config" file or as a "--collection" parameter.'),process.exit(1));let t=[..._dumbo.migrationTableSchemaComponent.migrations({connector:"PostgreSQL:pg"}),...i.flatMap(r=>_chunkPUUNCOTHcjs.h.call(void 0, r).migrations({connector:"PostgreSQL:pg"}))];console.log("Printing SQL:"),console.log(_dumbo.combineMigrations.call(void 0, ...t))});var _chalk = require('chalk'); var _chalk2 = _interopRequireDefault(_chalk);var _clitable3 = require('cli-table3'); var _clitable32 = _interopRequireDefault(_clitable3);var _repl = require('repl'); var _repl2 = _interopRequireDefault(_repl);var p,H=(o,e)=>e.map(n=>Math.max(n.length,...o.map(r=>r[n]?String(r[n]).length:0))+2),M=!1,K=o=>M=o===void 0||o===!0,X=o=>Array.isArray(o)&&M?N(o):_dumbo.prettyJson.call(void 0, o),N=o=>{if(o.length===0)return _chalk2.default.yellow("No documents found.");let e=o.flatMap(t=>typeof t=="object"?Object.keys(t):typeof t).filter((t,r,s)=>s.indexOf(t)===r),i=H(o,e),n=new (0, _clitable32.default)({head:e.map(t=>_chalk2.default.cyan(t)),colWidths:i});return o.forEach(t=>{n.push(e.map(r=>t[r]!==void 0?Array.isArray(t[r])?N(t[r]):_dumbo.prettyJson.call(void 0, t[r]):typeof t=="object"?"":t!=null&&t!=null?_dumbo.prettyJson.call(void 0, t):""))}),n.toString()},P=o=>{process.env.DUMBO_LOG_LEVEL=o},O=o=>{process.env.DUMBO_LOG_STYLE=o},Z=o=>{o!==void 0&&P(o),O(_dumbo.LogStyle.PRETTY)},oo=async o=>{P(_nullishCoalesce(process.env.DUMBO_LOG_LEVEL, () => (o.logging.logLevel))),O(_nullishCoalesce(process.env.DUMBO_LOG_STYLE, () => (o.logging.logStyle))),console.log(_chalk2.default.green("Starting Pongo Shell (version: 0.16.3)")),o.logging.printOptions&&(console.log(_chalk2.default.green("With Options:")),console.log(_dumbo.prettyJson.call(void 0, o)));let e=_nullishCoalesce(_nullishCoalesce(o.connectionString, () => (process.env.DB_CONNECTION_STRING)), () => ("postgresql://postgres:postgres@localhost:5432/postgres"));(_nullishCoalesce(o.connectionString, () => (process.env.DB_CONNECTION_STRING)))||console.log(_chalk2.default.yellow("No connection string provided, using: 'postgresql://postgres:postgres@localhost:5432/postgres'"));let i=await _dumbo.checkConnection.call(void 0, e);i.successful||(i.errorType==="ConnectionRefused"?console.error(_chalk2.default.red("Connection was refused. Check if the PostgreSQL server is running and accessible.")):i.errorType==="Authentication"?console.error(_chalk2.default.red("Authentication failed. Check the username and password in the connection string.")):console.error(_chalk2.default.red("Error connecting to PostgreSQL server")),console.log(_chalk2.default.red("Exiting Pongo Shell...")),process.exit()),console.log(_chalk2.default.green("Successfully connected")),console.log(_chalk2.default.green("Use db.<collection>.<method>() to query."));let n=_repl2.default.start({prompt:_chalk2.default.green("pongo> "),useGlobal:!0,breakEvalOnSigint:!0,writer:X}),t;if(o.schema.collections.length>0){let r={};for(let c of o.schema.collections)r[c]=_chunkPUUNCOTHcjs.C.collection(c);let s=_chunkPUUNCOTHcjs.C.client({database:_chunkPUUNCOTHcjs.C.db(o.schema.database,r)}),g=_chunkPUUNCOTHcjs.H.call(void 0, e,{schema:{definition:s,autoMigration:o.schema.autoMigration}});t=g.database;for(let c of o.schema.collections)n.context[c]=g.database[c];p=g}else p=_chunkPUUNCOTHcjs.H.call(void 0, e,{schema:{autoMigration:o.schema.autoMigration}}),t=p.db(o.schema.database);n.context.pongo=p,n.context.db=t,n.context.SQL=_dumbo.SQL,n.context.setLogLevel=P,n.context.setLogStyle=O,n.context.prettifyLogs=Z,n.context.printResultsAsTable=K,n.context.LogStyle=_dumbo.LogStyle,n.context.LogLevel=_dumbo.LogLevel,n.on("exit",async()=>{await S(),process.exit()}),n.on("SIGINT",async()=>{await S(),process.exit()})},S=async()=>{console.log(_chalk2.default.yellow("Exiting Pongo Shell...")),await p.close()};process.on("uncaughtException",S);process.on("SIGINT",S);var R=new (0, _commander.Command)("shell").description("Start an interactive Pongo shell").option("-cs, --connectionString <string>","Connection string for the database").option("-db, --database <string>","Database name to connect","postgres").option("-col, --collection <name>","Specify the collection name",(o,e)=>e.concat([o]),[]).option("-no-migrations, --disable-auto-migrations","Disable automatic migrations").option("-o, --print-options","Print shell options").option("-ll, --log-level <logLevel>","Log level: DISABLED, INFO, LOG, WARN, ERROR","DISABLED").option("-ls, --log-style","Log style: RAW, PRETTY","RAW").option("-p, --pretty-log","Turn on logging with prettified output").action(async o=>{let{collection:e,database:i}=o,n=o.connectionString;await oo({logging:{printOptions:o.printOptions===!0,logStyle:o.prettyLog?_dumbo.LogStyle.PRETTY:_nullishCoalesce(o.logStyle, () => (_dumbo.LogStyle.RAW)),logLevel:o.logLevel?o.logLevel:o.prettyLog?_dumbo.LogLevel.INFO:_dumbo.LogLevel.DISABLED},schema:{collections:e,database:i,autoMigration:o.disableAutoMigrations?"None":"CreateOrUpdate"},connectionString:n})});var m=new _commander.Command;m.name("pongo").description("CLI tool for Pongo");m.addCommand(v);m.addCommand(d);m.addCommand(R);m.parse(process.argv);var Oo=m;exports.default = Oo;
|
|
28
28
|
//# sourceMappingURL=cli.cjs.map
|
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{C as f,F as E,H as C,h as y,t as b}from"./chunk-
|
|
2
|
+
import{C as f,F as E,H as C,h as y,t as b}from"./chunk-CYDDN3CZ.js";import{Command as eo}from"commander";import{Command as T}from"commander";import A from"node:fs";var w=o=>{if(o.length===0)return o;let e=o.charAt(0).toUpperCase()+o.slice(1);return e.endsWith("s")&&(e=e.slice(0,-1)),e},l=(o=["users"])=>{let e=o.map(n=>`export type ${w(n)} = { name: string; description: string; date: Date }`).join(`
|
|
3
3
|
`),i=o.map(n=>` ${n}: pongoSchema.collection<${w(n)}>('${n}'),`).join(`
|
|
4
4
|
`);return`import { pongoSchema } from '@event-driven-io/pongo';
|
|
5
5
|
|
|
@@ -24,5 +24,5 @@ ${l()}`,D=`Error: Database should have defined at least one collection, e.g.
|
|
|
24
24
|
${l()}`,L=async o=>{let e=new URL(o,`file://${process.cwd()}/`);try{let i=await import(e.href),n=B(i);return typeof n=="string"&&(console.error(n),process.exit(1)),n}catch{console.error(`Error: Couldn't load file: ${e.href}`),process.exit(1)}},W=(o,e)=>{try{A.writeFileSync(o,l(e),"utf8"),console.log(`Configuration file stored at: ${o}`)}catch(i){console.error(`Error: Couldn't store config file: ${o}!`),console.error(i),process.exit(1)}},B=o=>{if(!o.default)return I;if(!o.default.schema)return _;if(!o.default.schema.dbs)return $;let i=b(o.default.schema.dbs).map(t=>t[1]).find(t=>t.name===void 0);return i?!i.collections||b(i.collections).map(t=>t[1]).length===0?D:E(i):G},v=new T("config").description("Manage Pongo configuration");v.command("sample").description("Generate or print sample configuration").option("-col, --collection <name>","Specify the collection name",(o,e)=>e.concat([o]),[]).option("-f, --file <path>","Path to configuration file with collection list").option("-g, --generate","Generate sample config file").option("-p, --print","Print sample config file").action(o=>{let e=o.collection.length>0?o.collection:["users"];!("print"in o)&&!("generate"in o)&&(console.error(`Error: Please provide either:
|
|
25
25
|
--print param to print sample config or
|
|
26
26
|
--generate to generate sample config file`),process.exit(1)),"print"in o?console.log(`${l(e)}`):"generate"in o&&(o.file||(console.error("Error: You need to provide a config file through a --file"),process.exit(1)),W(o.file,e))});import{combineMigrations as Q,dumbo as U,migrationTableSchemaComponent as q,runPostgreSQLMigrations as Y}from"@event-driven-io/dumbo";import{Command as k}from"commander";var d=new k("migrate").description("Manage database migrations");d.command("run").description("Run database migrations").option("-cs, --connection-string <string>","Connection string for the database").option("-col, --collection <name>","Specify the collection name",(o,e)=>e.concat([o]),[]).option("-f, --config <path>","Path to configuration file with Pongo config").option("-dr, --dryRun","Perform dry run without commiting changes",!1).action(async o=>{let{collection:e,dryRun:i}=o,n=o.connectionString??process.env.DB_CONNECTION_STRING,t;n||(console.error(`Error: Connection string is required. Provide it either as a "--connection-string" parameter or through the DB_CONNECTION_STRING environment variable.
|
|
27
|
-
For instance: --connection-string postgresql://postgres:postgres@localhost:5432/postgres`),process.exit(1)),o.config?t=(await L(o.config)).collections.map(c=>c.name):e?t=e:(console.error('Error: You need to provide at least one collection name. Provide it either through "--config" file or as a "--collection" parameter.'),process.exit(1));let r=U({connectionString:n}),s=t.flatMap(g=>y(g).migrations({connector:"PostgreSQL:pg"}));await Y(r,s,{dryRun:i})});d.command("sql").description("Generate SQL for database migration").option("-col, --collection <name>","Specify the collection name",(o,e)=>e.concat([o]),[]).option("-f, --config <path>","Path to configuration file with Pongo config").option("--print","Print the SQL to the console (default)",!0).action(async o=>{let{collection:e}=o,i;o.config?i=(await L(o.config)).collections.map(s=>s.name):e?i=e:(console.error('Error: You need to provide at least one collection name. Provide it either through "--config" file or as a "--collection" parameter.'),process.exit(1));let t=[...q.migrations({connector:"PostgreSQL:pg"}),...i.flatMap(r=>y(r).migrations({connector:"PostgreSQL:pg"}))];console.log("Printing SQL:"),console.log(Q(...t))});import{checkConnection as F,LogLevel as x,LogStyle as h,prettyJson as u,SQL as j}from"@event-driven-io/dumbo";import a from"chalk";import V from"cli-table3";import{Command as J}from"commander";import z from"node:repl";var p,H=(o,e)=>e.map(n=>Math.max(n.length,...o.map(r=>r[n]?String(r[n]).length:0))+2),M=!1,K=o=>M=o===void 0||o===!0,X=o=>Array.isArray(o)&&M?N(o):u(o),N=o=>{if(o.length===0)return a.yellow("No documents found.");let e=o.flatMap(t=>typeof t=="object"?Object.keys(t):typeof t).filter((t,r,s)=>s.indexOf(t)===r),i=H(o,e),n=new V({head:e.map(t=>a.cyan(t)),colWidths:i});return o.forEach(t=>{n.push(e.map(r=>t[r]!==void 0?Array.isArray(t[r])?N(t[r]):u(t[r]):typeof t=="object"?"":t!=null&&t!=null?u(t):""))}),n.toString()},P=o=>{process.env.DUMBO_LOG_LEVEL=o},O=o=>{process.env.DUMBO_LOG_STYLE=o},Z=o=>{o!==void 0&&P(o),O(h.PRETTY)},oo=async o=>{P(process.env.DUMBO_LOG_LEVEL??o.logging.logLevel),O(process.env.DUMBO_LOG_STYLE??o.logging.logStyle),console.log(a.green("Starting Pongo Shell (version: 0.16.
|
|
27
|
+
For instance: --connection-string postgresql://postgres:postgres@localhost:5432/postgres`),process.exit(1)),o.config?t=(await L(o.config)).collections.map(c=>c.name):e?t=e:(console.error('Error: You need to provide at least one collection name. Provide it either through "--config" file or as a "--collection" parameter.'),process.exit(1));let r=U({connectionString:n}),s=t.flatMap(g=>y(g).migrations({connector:"PostgreSQL:pg"}));await Y(r,s,{dryRun:i})});d.command("sql").description("Generate SQL for database migration").option("-col, --collection <name>","Specify the collection name",(o,e)=>e.concat([o]),[]).option("-f, --config <path>","Path to configuration file with Pongo config").option("--print","Print the SQL to the console (default)",!0).action(async o=>{let{collection:e}=o,i;o.config?i=(await L(o.config)).collections.map(s=>s.name):e?i=e:(console.error('Error: You need to provide at least one collection name. Provide it either through "--config" file or as a "--collection" parameter.'),process.exit(1));let t=[...q.migrations({connector:"PostgreSQL:pg"}),...i.flatMap(r=>y(r).migrations({connector:"PostgreSQL:pg"}))];console.log("Printing SQL:"),console.log(Q(...t))});import{checkConnection as F,LogLevel as x,LogStyle as h,prettyJson as u,SQL as j}from"@event-driven-io/dumbo";import a from"chalk";import V from"cli-table3";import{Command as J}from"commander";import z from"node:repl";var p,H=(o,e)=>e.map(n=>Math.max(n.length,...o.map(r=>r[n]?String(r[n]).length:0))+2),M=!1,K=o=>M=o===void 0||o===!0,X=o=>Array.isArray(o)&&M?N(o):u(o),N=o=>{if(o.length===0)return a.yellow("No documents found.");let e=o.flatMap(t=>typeof t=="object"?Object.keys(t):typeof t).filter((t,r,s)=>s.indexOf(t)===r),i=H(o,e),n=new V({head:e.map(t=>a.cyan(t)),colWidths:i});return o.forEach(t=>{n.push(e.map(r=>t[r]!==void 0?Array.isArray(t[r])?N(t[r]):u(t[r]):typeof t=="object"?"":t!=null&&t!=null?u(t):""))}),n.toString()},P=o=>{process.env.DUMBO_LOG_LEVEL=o},O=o=>{process.env.DUMBO_LOG_STYLE=o},Z=o=>{o!==void 0&&P(o),O(h.PRETTY)},oo=async o=>{P(process.env.DUMBO_LOG_LEVEL??o.logging.logLevel),O(process.env.DUMBO_LOG_STYLE??o.logging.logStyle),console.log(a.green("Starting Pongo Shell (version: 0.16.3)")),o.logging.printOptions&&(console.log(a.green("With Options:")),console.log(u(o)));let e=o.connectionString??process.env.DB_CONNECTION_STRING??"postgresql://postgres:postgres@localhost:5432/postgres";(o.connectionString??process.env.DB_CONNECTION_STRING)||console.log(a.yellow("No connection string provided, using: 'postgresql://postgres:postgres@localhost:5432/postgres'"));let i=await F(e);i.successful||(i.errorType==="ConnectionRefused"?console.error(a.red("Connection was refused. Check if the PostgreSQL server is running and accessible.")):i.errorType==="Authentication"?console.error(a.red("Authentication failed. Check the username and password in the connection string.")):console.error(a.red("Error connecting to PostgreSQL server")),console.log(a.red("Exiting Pongo Shell...")),process.exit()),console.log(a.green("Successfully connected")),console.log(a.green("Use db.<collection>.<method>() to query."));let n=z.start({prompt:a.green("pongo> "),useGlobal:!0,breakEvalOnSigint:!0,writer:X}),t;if(o.schema.collections.length>0){let r={};for(let c of o.schema.collections)r[c]=f.collection(c);let s=f.client({database:f.db(o.schema.database,r)}),g=C(e,{schema:{definition:s,autoMigration:o.schema.autoMigration}});t=g.database;for(let c of o.schema.collections)n.context[c]=g.database[c];p=g}else p=C(e,{schema:{autoMigration:o.schema.autoMigration}}),t=p.db(o.schema.database);n.context.pongo=p,n.context.db=t,n.context.SQL=j,n.context.setLogLevel=P,n.context.setLogStyle=O,n.context.prettifyLogs=Z,n.context.printResultsAsTable=K,n.context.LogStyle=h,n.context.LogLevel=x,n.on("exit",async()=>{await S(),process.exit()}),n.on("SIGINT",async()=>{await S(),process.exit()})},S=async()=>{console.log(a.yellow("Exiting Pongo Shell...")),await p.close()};process.on("uncaughtException",S);process.on("SIGINT",S);var R=new J("shell").description("Start an interactive Pongo shell").option("-cs, --connectionString <string>","Connection string for the database").option("-db, --database <string>","Database name to connect","postgres").option("-col, --collection <name>","Specify the collection name",(o,e)=>e.concat([o]),[]).option("-no-migrations, --disable-auto-migrations","Disable automatic migrations").option("-o, --print-options","Print shell options").option("-ll, --log-level <logLevel>","Log level: DISABLED, INFO, LOG, WARN, ERROR","DISABLED").option("-ls, --log-style","Log style: RAW, PRETTY","RAW").option("-p, --pretty-log","Turn on logging with prettified output").action(async o=>{let{collection:e,database:i}=o,n=o.connectionString;await oo({logging:{printOptions:o.printOptions===!0,logStyle:o.prettyLog?h.PRETTY:o.logStyle??h.RAW,logLevel:o.logLevel?o.logLevel:o.prettyLog?x.INFO:x.DISABLED},schema:{collections:e,database:i,autoMigration:o.disableAutoMigrations?"None":"CreateOrUpdate"},connectionString:n})});var m=new eo;m.name("pongo").description("CLI tool for Pongo");m.addCommand(v);m.addCommand(d);m.addCommand(R);m.parse(process.argv);var Oo=m;export{Oo as default};
|
|
28
28
|
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts","../src/commandLine/configFile.ts","../src/commandLine/migrate.ts","../src/commandLine/shell.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { Command } from 'commander';\nimport { configCommand, migrateCommand, shellCommand } from './commandLine';\n\nconst program = new Command();\n\nprogram.name('pongo').description('CLI tool for Pongo');\n\nprogram.addCommand(configCommand);\nprogram.addCommand(migrateCommand);\nprogram.addCommand(shellCommand);\n\nprogram.parse(process.argv);\n\nexport default program;\n","import { Command } from 'commander';\nimport fs from 'node:fs';\nimport {\n objectEntries,\n toDbSchemaMetadata,\n type PongoDbSchemaMetadata,\n type PongoSchemaConfig,\n} from '../core';\n\nconst formatTypeName = (input: string): string => {\n if (input.length === 0) {\n return input;\n }\n\n let formatted = input.charAt(0).toUpperCase() + input.slice(1);\n\n if (formatted.endsWith('s')) {\n formatted = formatted.slice(0, -1);\n }\n\n return formatted;\n};\n\nconst sampleConfig = (collectionNames: string[] = ['users']) => {\n const types = collectionNames\n .map(\n (name) =>\n `export type ${formatTypeName(name)} = { name: string; description: string; date: Date }`,\n )\n .join('\\n');\n\n const collections = collectionNames\n .map(\n (name) =>\n ` ${name}: pongoSchema.collection<${formatTypeName(name)}>('${name}'),`,\n )\n .join('\\n');\n\n return `import { pongoSchema } from '@event-driven-io/pongo';\n\n${types}\n\nexport default {\n schema: pongoSchema.client({\n database: pongoSchema.db({\n${collections}\n }),\n }),\n};`;\n};\n\nconst missingDefaultExport = `Error: Config should contain default export, e.g.\\n\\n${sampleConfig()}`;\nconst missingSchema = `Error: Config should contain schema property, e.g.\\n\\n${sampleConfig()}`;\nconst missingDbs = `Error: Config should have at least a single database defined, e.g.\\n\\n${sampleConfig()}`;\nconst missingDefaultDb = `Error: Config should have a default database defined (without name or or with default database name), e.g.\\n\\n${sampleConfig()}`;\nconst missingCollections = `Error: Database should have defined at least one collection, e.g.\\n\\n${sampleConfig()}`;\n\nexport const loadConfigFile = async (\n configPath: string,\n): Promise<PongoDbSchemaMetadata> => {\n const configUrl = new URL(configPath, `file://${process.cwd()}/`);\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const imported: Partial<{ default: PongoSchemaConfig }> = await import(\n configUrl.href\n );\n\n const parsed = parseDefaultDbSchema(imported);\n\n if (typeof parsed === 'string') {\n console.error(parsed);\n process.exit(1);\n }\n\n return parsed;\n } catch {\n console.error(`Error: Couldn't load file: ${configUrl.href}`);\n process.exit(1);\n }\n};\n\nexport const generateConfigFile = (\n configPath: string,\n collectionNames: string[],\n): void => {\n try {\n fs.writeFileSync(configPath, sampleConfig(collectionNames), 'utf8');\n console.log(`Configuration file stored at: ${configPath}`);\n } catch (error) {\n console.error(`Error: Couldn't store config file: ${configPath}!`);\n console.error(error);\n process.exit(1);\n }\n};\n\nexport const parseDefaultDbSchema = (\n imported: Partial<{ default: PongoSchemaConfig }>,\n): PongoDbSchemaMetadata | string => {\n if (!imported.default) {\n return missingDefaultExport;\n }\n\n if (!imported.default.schema) {\n return missingSchema;\n }\n\n if (!imported.default.schema.dbs) {\n return missingDbs;\n }\n\n const dbs = objectEntries(imported.default.schema.dbs).map((db) => db[1]);\n\n const defaultDb = dbs.find((db) => db.name === undefined);\n\n if (!defaultDb) {\n return missingDefaultDb;\n }\n\n if (!defaultDb.collections) {\n return missingCollections;\n }\n\n const collections = objectEntries(defaultDb.collections).map((col) => col[1]);\n\n if (collections.length === 0) {\n return missingCollections;\n }\n\n return toDbSchemaMetadata(defaultDb);\n};\n\ntype SampleConfigOptions =\n | {\n collection: string[];\n print?: boolean;\n }\n | {\n collection: string[];\n generate?: boolean;\n file?: string;\n };\n\nexport const configCommand = new Command('config').description(\n 'Manage Pongo configuration',\n);\n\nconfigCommand\n .command('sample')\n .description('Generate or print sample configuration')\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option(\n '-f, --file <path>',\n 'Path to configuration file with collection list',\n )\n .option('-g, --generate', 'Generate sample config file')\n .option('-p, --print', 'Print sample config file')\n .action((options: SampleConfigOptions) => {\n const collectionNames =\n options.collection.length > 0 ? options.collection : ['users'];\n\n if (!('print' in options) && !('generate' in options)) {\n console.error(\n 'Error: Please provide either:\\n--print param to print sample config or\\n--generate to generate sample config file',\n );\n process.exit(1);\n }\n\n if ('print' in options) {\n console.log(`${sampleConfig(collectionNames)}`);\n } else if ('generate' in options) {\n if (!options.file) {\n console.error(\n 'Error: You need to provide a config file through a --file',\n );\n process.exit(1);\n }\n\n generateConfigFile(options.file, collectionNames);\n }\n });\n","import {\n combineMigrations,\n dumbo,\n migrationTableSchemaComponent,\n runPostgreSQLMigrations,\n} from '@event-driven-io/dumbo';\nimport { Command } from 'commander';\nimport { pongoCollectionSchemaComponent } from '../core';\nimport { loadConfigFile } from './configFile';\n\ninterface MigrateRunOptions {\n collection: string[];\n connectionString: string;\n config?: string;\n dryRun?: boolean;\n}\n\ninterface MigrateSqlOptions {\n print?: boolean;\n write?: string;\n config?: string;\n collection: string[];\n}\n\nexport const migrateCommand = new Command('migrate').description(\n 'Manage database migrations',\n);\n\nmigrateCommand\n .command('run')\n .description('Run database migrations')\n .option(\n '-cs, --connection-string <string>',\n 'Connection string for the database',\n )\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option('-f, --config <path>', 'Path to configuration file with Pongo config')\n .option('-dr, --dryRun', 'Perform dry run without commiting changes', false)\n .action(async (options: MigrateRunOptions) => {\n const { collection, dryRun } = options;\n const connectionString =\n options.connectionString ?? process.env.DB_CONNECTION_STRING;\n let collectionNames: string[];\n\n if (!connectionString) {\n console.error(\n 'Error: Connection string is required. Provide it either as a \"--connection-string\" parameter or through the DB_CONNECTION_STRING environment variable.' +\n '\\nFor instance: --connection-string postgresql://postgres:postgres@localhost:5432/postgres',\n );\n process.exit(1);\n }\n\n if (options.config) {\n const config = await loadConfigFile(options.config);\n\n collectionNames = config.collections.map((c) => c.name);\n } else if (collection) {\n collectionNames = collection;\n } else {\n console.error(\n 'Error: You need to provide at least one collection name. Provide it either through \"--config\" file or as a \"--collection\" parameter.',\n );\n process.exit(1);\n }\n\n const pool = dumbo({ connectionString });\n\n const migrations = collectionNames.flatMap((collectionsName) =>\n pongoCollectionSchemaComponent(collectionsName).migrations({\n connector: 'PostgreSQL:pg', // TODO: Provide connector here\n }),\n );\n\n await runPostgreSQLMigrations(pool, migrations, {\n dryRun,\n });\n });\n\nmigrateCommand\n .command('sql')\n .description('Generate SQL for database migration')\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option('-f, --config <path>', 'Path to configuration file with Pongo config')\n .option('--print', 'Print the SQL to the console (default)', true)\n //.option('--write <filename>', 'Write the SQL to a specified file')\n .action(async (options: MigrateSqlOptions) => {\n const { collection } = options;\n\n let collectionNames: string[];\n\n if (options.config) {\n const config = await loadConfigFile(options.config);\n\n collectionNames = config.collections.map((c) => c.name);\n } else if (collection) {\n collectionNames = collection;\n } else {\n console.error(\n 'Error: You need to provide at least one collection name. Provide it either through \"--config\" file or as a \"--collection\" parameter.',\n );\n process.exit(1);\n }\n\n const coreMigrations = migrationTableSchemaComponent.migrations({\n connector: 'PostgreSQL:pg',\n });\n const migrations = [\n ...coreMigrations,\n ...collectionNames.flatMap((collectionName) =>\n pongoCollectionSchemaComponent(collectionName).migrations({\n connector: 'PostgreSQL:pg', // TODO: Provide connector here\n }),\n ),\n ];\n\n console.log('Printing SQL:');\n console.log(combineMigrations(...migrations));\n });\n","import {\n checkConnection,\n LogLevel,\n LogStyle,\n prettyJson,\n SQL,\n type MigrationStyle,\n} from '@event-driven-io/dumbo';\nimport chalk from 'chalk';\nimport Table from 'cli-table3';\nimport { Command } from 'commander';\nimport repl from 'node:repl';\nimport {\n pongoClient,\n pongoSchema,\n type PongoClient,\n type PongoCollectionSchema,\n type PongoDb,\n} from '../core';\n\nlet pongo: PongoClient;\n\nconst calculateColumnWidths = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n results: any[],\n columnNames: string[],\n): number[] => {\n const columnWidths = columnNames.map((col) => {\n const maxWidth = Math.max(\n col.length, // Header size\n ...results.map((result) =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n result[col] ? String(result[col]).length : 0,\n ),\n );\n return maxWidth + 2; // Add padding\n });\n return columnWidths;\n};\n\nlet shouldDisplayResultsAsTable = false;\n\nconst printResultsAsTable = (print?: boolean) =>\n (shouldDisplayResultsAsTable = print === undefined || print === true);\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst printOutput = (obj: any): string =>\n Array.isArray(obj) && shouldDisplayResultsAsTable\n ? displayResultsAsTable(obj)\n : prettyJson(obj);\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst displayResultsAsTable = (results: any[]): string => {\n if (results.length === 0) {\n return chalk.yellow('No documents found.');\n }\n\n const columnNames = results\n\n .flatMap((result) =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n typeof result === 'object' ? Object.keys(result) : typeof result,\n )\n .filter((value, index, array) => array.indexOf(value) === index);\n\n const columnWidths = calculateColumnWidths(results, columnNames);\n\n const table = new Table({\n head: columnNames.map((col) => chalk.cyan(col)),\n colWidths: columnWidths,\n });\n\n results.forEach((result) => {\n table.push(\n columnNames.map((col) =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n result[col] !== undefined\n ? // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n Array.isArray(result[col])\n ? // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n displayResultsAsTable(result[col])\n : // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n prettyJson(result[col])\n : typeof result === 'object'\n ? ''\n : result != undefined && result != undefined\n ? prettyJson(result)\n : '',\n ),\n );\n });\n\n return table.toString();\n};\n\nconst setLogLevel = (logLevel: string) => {\n process.env.DUMBO_LOG_LEVEL = logLevel;\n};\n\nconst setLogStyle = (logLevel: string) => {\n process.env.DUMBO_LOG_STYLE = logLevel;\n};\n\nconst prettifyLogs = (logLevel?: string) => {\n if (logLevel !== undefined) setLogLevel(logLevel);\n setLogStyle(LogStyle.PRETTY);\n};\n\nconst startRepl = async (options: {\n logging: {\n printOptions: boolean;\n logLevel: LogLevel;\n logStyle: LogStyle;\n };\n schema: {\n database: string;\n collections: string[];\n autoMigration: MigrationStyle;\n };\n connectionString: string | undefined;\n}) => {\n // TODO: This will change when we have proper tracing and logging config\n // For now, that's enough\n setLogLevel(process.env.DUMBO_LOG_LEVEL ?? options.logging.logLevel);\n setLogStyle(process.env.DUMBO_LOG_STYLE ?? options.logging.logStyle);\n\n console.log(chalk.green('Starting Pongo Shell (version: 0.16.2)'));\n\n if (options.logging.printOptions) {\n console.log(chalk.green('With Options:'));\n console.log(prettyJson(options));\n }\n\n const connectionString =\n options.connectionString ??\n process.env.DB_CONNECTION_STRING ??\n 'postgresql://postgres:postgres@localhost:5432/postgres';\n\n if (!(options.connectionString ?? process.env.DB_CONNECTION_STRING)) {\n console.log(\n chalk.yellow(\n `No connection string provided, using: 'postgresql://postgres:postgres@localhost:5432/postgres'`,\n ),\n );\n }\n\n const connectionCheck = await checkConnection(connectionString);\n\n if (!connectionCheck.successful) {\n if (connectionCheck.errorType === 'ConnectionRefused') {\n console.error(\n chalk.red(\n `Connection was refused. Check if the PostgreSQL server is running and accessible.`,\n ),\n );\n } else if (connectionCheck.errorType === 'Authentication') {\n console.error(\n chalk.red(\n `Authentication failed. Check the username and password in the connection string.`,\n ),\n );\n } else {\n console.error(chalk.red('Error connecting to PostgreSQL server'));\n }\n console.log(chalk.red('Exiting Pongo Shell...'));\n process.exit();\n }\n\n console.log(chalk.green(`Successfully connected`));\n console.log(chalk.green('Use db.<collection>.<method>() to query.'));\n\n const shell = repl.start({\n prompt: chalk.green('pongo> '),\n useGlobal: true,\n breakEvalOnSigint: true,\n writer: printOutput,\n });\n\n let db: PongoDb;\n\n if (options.schema.collections.length > 0) {\n const collectionsSchema: Record<string, PongoCollectionSchema> = {};\n\n for (const collectionName of options.schema.collections) {\n collectionsSchema[collectionName] =\n pongoSchema.collection(collectionName);\n }\n\n const schema = pongoSchema.client({\n database: pongoSchema.db(options.schema.database, collectionsSchema),\n });\n\n const typedClient = pongoClient(connectionString, {\n schema: {\n definition: schema,\n autoMigration: options.schema.autoMigration,\n },\n });\n\n db = typedClient.database;\n\n for (const collectionName of options.schema.collections) {\n shell.context[collectionName] = typedClient.database[collectionName];\n }\n\n pongo = typedClient;\n } else {\n pongo = pongoClient(connectionString, {\n schema: { autoMigration: options.schema.autoMigration },\n });\n\n db = pongo.db(options.schema.database);\n }\n\n shell.context.pongo = pongo;\n shell.context.db = db;\n\n // helpers\n shell.context.SQL = SQL;\n shell.context.setLogLevel = setLogLevel;\n shell.context.setLogStyle = setLogStyle;\n shell.context.prettifyLogs = prettifyLogs;\n shell.context.printResultsAsTable = printResultsAsTable;\n shell.context.LogStyle = LogStyle;\n shell.context.LogLevel = LogLevel;\n\n // Intercept REPL output to display results as a table if they are arrays\n shell.on('exit', async () => {\n await teardown();\n process.exit();\n });\n\n shell.on('SIGINT', async () => {\n await teardown();\n process.exit();\n });\n};\n\nconst teardown = async () => {\n console.log(chalk.yellow('Exiting Pongo Shell...'));\n await pongo.close();\n};\n\nprocess.on('uncaughtException', teardown);\nprocess.on('SIGINT', teardown);\n\ninterface ShellOptions {\n database: string;\n collection: string[];\n connectionString?: string;\n disableAutoMigrations: boolean;\n logStyle?: string;\n logLevel?: string;\n prettyLog?: boolean;\n printOptions?: boolean;\n}\n\nconst shellCommand = new Command('shell')\n .description('Start an interactive Pongo shell')\n .option(\n '-cs, --connectionString <string>',\n 'Connection string for the database',\n )\n .option('-db, --database <string>', 'Database name to connect', 'postgres')\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option(\n '-no-migrations, --disable-auto-migrations',\n 'Disable automatic migrations',\n )\n .option('-o, --print-options', 'Print shell options')\n .option(\n '-ll, --log-level <logLevel>',\n 'Log level: DISABLED, INFO, LOG, WARN, ERROR',\n 'DISABLED',\n )\n .option('-ls, --log-style', 'Log style: RAW, PRETTY', 'RAW')\n .option('-p, --pretty-log', 'Turn on logging with prettified output')\n .action(async (options: ShellOptions) => {\n const { collection, database } = options;\n const connectionString = options.connectionString;\n\n await startRepl({\n logging: {\n printOptions: options.printOptions === true,\n logStyle: options.prettyLog\n ? LogStyle.PRETTY\n : ((options.logStyle as LogStyle | undefined) ?? LogStyle.RAW),\n logLevel: options.logLevel\n ? (options.logLevel as LogLevel)\n : options.prettyLog\n ? LogLevel.INFO\n : LogLevel.DISABLED,\n },\n schema: {\n collections: collection,\n database,\n autoMigration: options.disableAutoMigrations\n ? 'None'\n : 'CreateOrUpdate',\n },\n connectionString,\n });\n });\n\nexport { shellCommand };\n"],"mappings":";oEACA,O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AAC,CACH,CAAC,EHlTH,IAAMoB,EAAU,IAAIC,GAEpBD,EAAQ,KAAK,OAAO,EAAE,YAAY,oBAAoB,EAEtDA,EAAQ,WAAWE,CAAa,EAChCF,EAAQ,WAAWG,CAAc,EACjCH,EAAQ,WAAWI,CAAY,EAE/BJ,EAAQ,MAAM,QAAQ,IAAI,EAE1B,IAAOK,GAAQL","names":["Command","Command","fs","formatTypeName","input","formatted","sampleConfig","collectionNames","types","name","collections","missingDefaultExport","missingSchema","missingDbs","missingDefaultDb","missingCollections","loadConfigFile","configPath","configUrl","imported","parsed","parseDefaultDbSchema","generateConfigFile","fs","error","defaultDb","objectEntries","db","col","toDbSchemaMetadata","configCommand","Command","value","previous","options","combineMigrations","dumbo","migrationTableSchemaComponent","runPostgreSQLMigrations","Command","migrateCommand","Command","value","previous","options","collection","dryRun","connectionString","collectionNames","loadConfigFile","pool","dumbo","migrations","collectionsName","pongoCollectionSchemaComponent","runPostgreSQLMigrations","c","migrationTableSchemaComponent","collectionName","combineMigrations","checkConnection","LogLevel","LogStyle","prettyJson","SQL","chalk","Table","Command","repl","pongo","calculateColumnWidths","results","columnNames","col","result","shouldDisplayResultsAsTable","printResultsAsTable","print","printOutput","obj","displayResultsAsTable","prettyJson","chalk","value","index","array","columnWidths","table","Table","setLogLevel","logLevel","setLogStyle","prettifyLogs","LogStyle","startRepl","options","connectionString","connectionCheck","checkConnection","shell","repl","db","collectionsSchema","collectionName","pongoSchema","schema","typedClient","pongoClient","SQL","LogLevel","teardown","shellCommand","Command","previous","collection","database","program","Command","configCommand","migrateCommand","shellCommand","cli_default"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts","../src/commandLine/configFile.ts","../src/commandLine/migrate.ts","../src/commandLine/shell.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { Command } from 'commander';\nimport { configCommand, migrateCommand, shellCommand } from './commandLine';\n\nconst program = new Command();\n\nprogram.name('pongo').description('CLI tool for Pongo');\n\nprogram.addCommand(configCommand);\nprogram.addCommand(migrateCommand);\nprogram.addCommand(shellCommand);\n\nprogram.parse(process.argv);\n\nexport default program;\n","import { Command } from 'commander';\nimport fs from 'node:fs';\nimport {\n objectEntries,\n toDbSchemaMetadata,\n type PongoDbSchemaMetadata,\n type PongoSchemaConfig,\n} from '../core';\n\nconst formatTypeName = (input: string): string => {\n if (input.length === 0) {\n return input;\n }\n\n let formatted = input.charAt(0).toUpperCase() + input.slice(1);\n\n if (formatted.endsWith('s')) {\n formatted = formatted.slice(0, -1);\n }\n\n return formatted;\n};\n\nconst sampleConfig = (collectionNames: string[] = ['users']) => {\n const types = collectionNames\n .map(\n (name) =>\n `export type ${formatTypeName(name)} = { name: string; description: string; date: Date }`,\n )\n .join('\\n');\n\n const collections = collectionNames\n .map(\n (name) =>\n ` ${name}: pongoSchema.collection<${formatTypeName(name)}>('${name}'),`,\n )\n .join('\\n');\n\n return `import { pongoSchema } from '@event-driven-io/pongo';\n\n${types}\n\nexport default {\n schema: pongoSchema.client({\n database: pongoSchema.db({\n${collections}\n }),\n }),\n};`;\n};\n\nconst missingDefaultExport = `Error: Config should contain default export, e.g.\\n\\n${sampleConfig()}`;\nconst missingSchema = `Error: Config should contain schema property, e.g.\\n\\n${sampleConfig()}`;\nconst missingDbs = `Error: Config should have at least a single database defined, e.g.\\n\\n${sampleConfig()}`;\nconst missingDefaultDb = `Error: Config should have a default database defined (without name or or with default database name), e.g.\\n\\n${sampleConfig()}`;\nconst missingCollections = `Error: Database should have defined at least one collection, e.g.\\n\\n${sampleConfig()}`;\n\nexport const loadConfigFile = async (\n configPath: string,\n): Promise<PongoDbSchemaMetadata> => {\n const configUrl = new URL(configPath, `file://${process.cwd()}/`);\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const imported: Partial<{ default: PongoSchemaConfig }> = await import(\n configUrl.href\n );\n\n const parsed = parseDefaultDbSchema(imported);\n\n if (typeof parsed === 'string') {\n console.error(parsed);\n process.exit(1);\n }\n\n return parsed;\n } catch {\n console.error(`Error: Couldn't load file: ${configUrl.href}`);\n process.exit(1);\n }\n};\n\nexport const generateConfigFile = (\n configPath: string,\n collectionNames: string[],\n): void => {\n try {\n fs.writeFileSync(configPath, sampleConfig(collectionNames), 'utf8');\n console.log(`Configuration file stored at: ${configPath}`);\n } catch (error) {\n console.error(`Error: Couldn't store config file: ${configPath}!`);\n console.error(error);\n process.exit(1);\n }\n};\n\nexport const parseDefaultDbSchema = (\n imported: Partial<{ default: PongoSchemaConfig }>,\n): PongoDbSchemaMetadata | string => {\n if (!imported.default) {\n return missingDefaultExport;\n }\n\n if (!imported.default.schema) {\n return missingSchema;\n }\n\n if (!imported.default.schema.dbs) {\n return missingDbs;\n }\n\n const dbs = objectEntries(imported.default.schema.dbs).map((db) => db[1]);\n\n const defaultDb = dbs.find((db) => db.name === undefined);\n\n if (!defaultDb) {\n return missingDefaultDb;\n }\n\n if (!defaultDb.collections) {\n return missingCollections;\n }\n\n const collections = objectEntries(defaultDb.collections).map((col) => col[1]);\n\n if (collections.length === 0) {\n return missingCollections;\n }\n\n return toDbSchemaMetadata(defaultDb);\n};\n\ntype SampleConfigOptions =\n | {\n collection: string[];\n print?: boolean;\n }\n | {\n collection: string[];\n generate?: boolean;\n file?: string;\n };\n\nexport const configCommand = new Command('config').description(\n 'Manage Pongo configuration',\n);\n\nconfigCommand\n .command('sample')\n .description('Generate or print sample configuration')\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option(\n '-f, --file <path>',\n 'Path to configuration file with collection list',\n )\n .option('-g, --generate', 'Generate sample config file')\n .option('-p, --print', 'Print sample config file')\n .action((options: SampleConfigOptions) => {\n const collectionNames =\n options.collection.length > 0 ? options.collection : ['users'];\n\n if (!('print' in options) && !('generate' in options)) {\n console.error(\n 'Error: Please provide either:\\n--print param to print sample config or\\n--generate to generate sample config file',\n );\n process.exit(1);\n }\n\n if ('print' in options) {\n console.log(`${sampleConfig(collectionNames)}`);\n } else if ('generate' in options) {\n if (!options.file) {\n console.error(\n 'Error: You need to provide a config file through a --file',\n );\n process.exit(1);\n }\n\n generateConfigFile(options.file, collectionNames);\n }\n });\n","import {\n combineMigrations,\n dumbo,\n migrationTableSchemaComponent,\n runPostgreSQLMigrations,\n} from '@event-driven-io/dumbo';\nimport { Command } from 'commander';\nimport { pongoCollectionSchemaComponent } from '../core';\nimport { loadConfigFile } from './configFile';\n\ninterface MigrateRunOptions {\n collection: string[];\n connectionString: string;\n config?: string;\n dryRun?: boolean;\n}\n\ninterface MigrateSqlOptions {\n print?: boolean;\n write?: string;\n config?: string;\n collection: string[];\n}\n\nexport const migrateCommand = new Command('migrate').description(\n 'Manage database migrations',\n);\n\nmigrateCommand\n .command('run')\n .description('Run database migrations')\n .option(\n '-cs, --connection-string <string>',\n 'Connection string for the database',\n )\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option('-f, --config <path>', 'Path to configuration file with Pongo config')\n .option('-dr, --dryRun', 'Perform dry run without commiting changes', false)\n .action(async (options: MigrateRunOptions) => {\n const { collection, dryRun } = options;\n const connectionString =\n options.connectionString ?? process.env.DB_CONNECTION_STRING;\n let collectionNames: string[];\n\n if (!connectionString) {\n console.error(\n 'Error: Connection string is required. Provide it either as a \"--connection-string\" parameter or through the DB_CONNECTION_STRING environment variable.' +\n '\\nFor instance: --connection-string postgresql://postgres:postgres@localhost:5432/postgres',\n );\n process.exit(1);\n }\n\n if (options.config) {\n const config = await loadConfigFile(options.config);\n\n collectionNames = config.collections.map((c) => c.name);\n } else if (collection) {\n collectionNames = collection;\n } else {\n console.error(\n 'Error: You need to provide at least one collection name. Provide it either through \"--config\" file or as a \"--collection\" parameter.',\n );\n process.exit(1);\n }\n\n const pool = dumbo({ connectionString });\n\n const migrations = collectionNames.flatMap((collectionsName) =>\n pongoCollectionSchemaComponent(collectionsName).migrations({\n connector: 'PostgreSQL:pg', // TODO: Provide connector here\n }),\n );\n\n await runPostgreSQLMigrations(pool, migrations, {\n dryRun,\n });\n });\n\nmigrateCommand\n .command('sql')\n .description('Generate SQL for database migration')\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option('-f, --config <path>', 'Path to configuration file with Pongo config')\n .option('--print', 'Print the SQL to the console (default)', true)\n //.option('--write <filename>', 'Write the SQL to a specified file')\n .action(async (options: MigrateSqlOptions) => {\n const { collection } = options;\n\n let collectionNames: string[];\n\n if (options.config) {\n const config = await loadConfigFile(options.config);\n\n collectionNames = config.collections.map((c) => c.name);\n } else if (collection) {\n collectionNames = collection;\n } else {\n console.error(\n 'Error: You need to provide at least one collection name. Provide it either through \"--config\" file or as a \"--collection\" parameter.',\n );\n process.exit(1);\n }\n\n const coreMigrations = migrationTableSchemaComponent.migrations({\n connector: 'PostgreSQL:pg',\n });\n const migrations = [\n ...coreMigrations,\n ...collectionNames.flatMap((collectionName) =>\n pongoCollectionSchemaComponent(collectionName).migrations({\n connector: 'PostgreSQL:pg', // TODO: Provide connector here\n }),\n ),\n ];\n\n console.log('Printing SQL:');\n console.log(combineMigrations(...migrations));\n });\n","import {\n checkConnection,\n LogLevel,\n LogStyle,\n prettyJson,\n SQL,\n type MigrationStyle,\n} from '@event-driven-io/dumbo';\nimport chalk from 'chalk';\nimport Table from 'cli-table3';\nimport { Command } from 'commander';\nimport repl from 'node:repl';\nimport {\n pongoClient,\n pongoSchema,\n type PongoClient,\n type PongoCollectionSchema,\n type PongoDb,\n} from '../core';\n\nlet pongo: PongoClient;\n\nconst calculateColumnWidths = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n results: any[],\n columnNames: string[],\n): number[] => {\n const columnWidths = columnNames.map((col) => {\n const maxWidth = Math.max(\n col.length, // Header size\n ...results.map((result) =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n result[col] ? String(result[col]).length : 0,\n ),\n );\n return maxWidth + 2; // Add padding\n });\n return columnWidths;\n};\n\nlet shouldDisplayResultsAsTable = false;\n\nconst printResultsAsTable = (print?: boolean) =>\n (shouldDisplayResultsAsTable = print === undefined || print === true);\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst printOutput = (obj: any): string =>\n Array.isArray(obj) && shouldDisplayResultsAsTable\n ? displayResultsAsTable(obj)\n : prettyJson(obj);\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst displayResultsAsTable = (results: any[]): string => {\n if (results.length === 0) {\n return chalk.yellow('No documents found.');\n }\n\n const columnNames = results\n\n .flatMap((result) =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n typeof result === 'object' ? Object.keys(result) : typeof result,\n )\n .filter((value, index, array) => array.indexOf(value) === index);\n\n const columnWidths = calculateColumnWidths(results, columnNames);\n\n const table = new Table({\n head: columnNames.map((col) => chalk.cyan(col)),\n colWidths: columnWidths,\n });\n\n results.forEach((result) => {\n table.push(\n columnNames.map((col) =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n result[col] !== undefined\n ? // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n Array.isArray(result[col])\n ? // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n displayResultsAsTable(result[col])\n : // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n prettyJson(result[col])\n : typeof result === 'object'\n ? ''\n : result != undefined && result != undefined\n ? prettyJson(result)\n : '',\n ),\n );\n });\n\n return table.toString();\n};\n\nconst setLogLevel = (logLevel: string) => {\n process.env.DUMBO_LOG_LEVEL = logLevel;\n};\n\nconst setLogStyle = (logLevel: string) => {\n process.env.DUMBO_LOG_STYLE = logLevel;\n};\n\nconst prettifyLogs = (logLevel?: string) => {\n if (logLevel !== undefined) setLogLevel(logLevel);\n setLogStyle(LogStyle.PRETTY);\n};\n\nconst startRepl = async (options: {\n logging: {\n printOptions: boolean;\n logLevel: LogLevel;\n logStyle: LogStyle;\n };\n schema: {\n database: string;\n collections: string[];\n autoMigration: MigrationStyle;\n };\n connectionString: string | undefined;\n}) => {\n // TODO: This will change when we have proper tracing and logging config\n // For now, that's enough\n setLogLevel(process.env.DUMBO_LOG_LEVEL ?? options.logging.logLevel);\n setLogStyle(process.env.DUMBO_LOG_STYLE ?? options.logging.logStyle);\n\n console.log(chalk.green('Starting Pongo Shell (version: 0.16.3)'));\n\n if (options.logging.printOptions) {\n console.log(chalk.green('With Options:'));\n console.log(prettyJson(options));\n }\n\n const connectionString =\n options.connectionString ??\n process.env.DB_CONNECTION_STRING ??\n 'postgresql://postgres:postgres@localhost:5432/postgres';\n\n if (!(options.connectionString ?? process.env.DB_CONNECTION_STRING)) {\n console.log(\n chalk.yellow(\n `No connection string provided, using: 'postgresql://postgres:postgres@localhost:5432/postgres'`,\n ),\n );\n }\n\n const connectionCheck = await checkConnection(connectionString);\n\n if (!connectionCheck.successful) {\n if (connectionCheck.errorType === 'ConnectionRefused') {\n console.error(\n chalk.red(\n `Connection was refused. Check if the PostgreSQL server is running and accessible.`,\n ),\n );\n } else if (connectionCheck.errorType === 'Authentication') {\n console.error(\n chalk.red(\n `Authentication failed. Check the username and password in the connection string.`,\n ),\n );\n } else {\n console.error(chalk.red('Error connecting to PostgreSQL server'));\n }\n console.log(chalk.red('Exiting Pongo Shell...'));\n process.exit();\n }\n\n console.log(chalk.green(`Successfully connected`));\n console.log(chalk.green('Use db.<collection>.<method>() to query.'));\n\n const shell = repl.start({\n prompt: chalk.green('pongo> '),\n useGlobal: true,\n breakEvalOnSigint: true,\n writer: printOutput,\n });\n\n let db: PongoDb;\n\n if (options.schema.collections.length > 0) {\n const collectionsSchema: Record<string, PongoCollectionSchema> = {};\n\n for (const collectionName of options.schema.collections) {\n collectionsSchema[collectionName] =\n pongoSchema.collection(collectionName);\n }\n\n const schema = pongoSchema.client({\n database: pongoSchema.db(options.schema.database, collectionsSchema),\n });\n\n const typedClient = pongoClient(connectionString, {\n schema: {\n definition: schema,\n autoMigration: options.schema.autoMigration,\n },\n });\n\n db = typedClient.database;\n\n for (const collectionName of options.schema.collections) {\n shell.context[collectionName] = typedClient.database[collectionName];\n }\n\n pongo = typedClient;\n } else {\n pongo = pongoClient(connectionString, {\n schema: { autoMigration: options.schema.autoMigration },\n });\n\n db = pongo.db(options.schema.database);\n }\n\n shell.context.pongo = pongo;\n shell.context.db = db;\n\n // helpers\n shell.context.SQL = SQL;\n shell.context.setLogLevel = setLogLevel;\n shell.context.setLogStyle = setLogStyle;\n shell.context.prettifyLogs = prettifyLogs;\n shell.context.printResultsAsTable = printResultsAsTable;\n shell.context.LogStyle = LogStyle;\n shell.context.LogLevel = LogLevel;\n\n // Intercept REPL output to display results as a table if they are arrays\n shell.on('exit', async () => {\n await teardown();\n process.exit();\n });\n\n shell.on('SIGINT', async () => {\n await teardown();\n process.exit();\n });\n};\n\nconst teardown = async () => {\n console.log(chalk.yellow('Exiting Pongo Shell...'));\n await pongo.close();\n};\n\nprocess.on('uncaughtException', teardown);\nprocess.on('SIGINT', teardown);\n\ninterface ShellOptions {\n database: string;\n collection: string[];\n connectionString?: string;\n disableAutoMigrations: boolean;\n logStyle?: string;\n logLevel?: string;\n prettyLog?: boolean;\n printOptions?: boolean;\n}\n\nconst shellCommand = new Command('shell')\n .description('Start an interactive Pongo shell')\n .option(\n '-cs, --connectionString <string>',\n 'Connection string for the database',\n )\n .option('-db, --database <string>', 'Database name to connect', 'postgres')\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option(\n '-no-migrations, --disable-auto-migrations',\n 'Disable automatic migrations',\n )\n .option('-o, --print-options', 'Print shell options')\n .option(\n '-ll, --log-level <logLevel>',\n 'Log level: DISABLED, INFO, LOG, WARN, ERROR',\n 'DISABLED',\n )\n .option('-ls, --log-style', 'Log style: RAW, PRETTY', 'RAW')\n .option('-p, --pretty-log', 'Turn on logging with prettified output')\n .action(async (options: ShellOptions) => {\n const { collection, database } = options;\n const connectionString = options.connectionString;\n\n await startRepl({\n logging: {\n printOptions: options.printOptions === true,\n logStyle: options.prettyLog\n ? LogStyle.PRETTY\n : ((options.logStyle as LogStyle | undefined) ?? LogStyle.RAW),\n logLevel: options.logLevel\n ? (options.logLevel as LogLevel)\n : options.prettyLog\n ? LogLevel.INFO\n : LogLevel.DISABLED,\n },\n schema: {\n collections: collection,\n database,\n autoMigration: options.disableAutoMigrations\n ? 'None'\n : 'CreateOrUpdate',\n },\n connectionString,\n });\n });\n\nexport { shellCommand };\n"],"mappings":";oEACA,OAAS,WAAAA,OAAe,YCDxB,OAAS,WAAAC,MAAe,YACxB,OAAOC,MAAQ,UAQf,IAAMC,EAAkBC,GAA0B,CAChD,GAAIA,EAAM,SAAW,EACnB,OAAOA,EAGT,IAAIC,EAAYD,EAAM,OAAO,CAAC,EAAE,YAAY,EAAIA,EAAM,MAAM,CAAC,EAE7D,OAAIC,EAAU,SAAS,GAAG,IACxBA,EAAYA,EAAU,MAAM,EAAG,EAAE,GAG5BA,CACT,EAEMC,EAAe,CAACC,EAA4B,CAAC,OAAO,IAAM,CAC9D,IAAMC,EAAQD,EACX,IACEE,GACC,eAAeN,EAAeM,CAAI,CAAC,sDACvC,EACC,KAAK;AAAA,CAAI,EAENC,EAAcH,EACjB,IACEE,GACC,SAASA,CAAI,4BAA4BN,EAAeM,CAAI,CAAC,MAAMA,CAAI,KAC3E,EACC,KAAK;AAAA,CAAI,EAEZ,MAAO;AAAA;AAAA,EAEPD,CAAK;AAAA;AAAA;AAAA;AAAA;AAAA,EAKLE,CAAW;AAAA;AAAA;AAAA,GAIb,EAEMC,EAAuB;AAAA;AAAA,EAAwDL,EAAa,CAAC,GAC7FM,E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CACA,8BACF,EACC,OAAO,sBAAuB,qBAAqB,EACnD,OACC,8BACA,8CACA,UACF,EACC,OAAO,mBAAoB,yBAA0B,KAAK,EAC1D,OAAO,mBAAoB,wCAAwC,EACnE,OAAO,MAAOY,GAA0B,CACvC,GAAM,CAAE,WAAAmB,EAAY,SAAAC,CAAS,EAAIpB,EAC3BC,EAAmBD,EAAQ,iBAEjC,MAAMD,GAAU,CACd,QAAS,CACP,aAAcC,EAAQ,eAAiB,GACvC,SAAUA,EAAQ,UACdF,EAAS,OACPE,EAAQ,UAAqCF,EAAS,IAC5D,SAAUE,EAAQ,SACbA,EAAQ,SACTA,EAAQ,UACNc,EAAS,KACTA,EAAS,QACjB,EACA,OAAQ,CACN,YAAaK,EACb,SAAAC,EACA,cAAepB,EAAQ,sBACnB,OACA,gBACN,EACA,iBAAAC,CACF,CAAC,CACH,CAAC,EHlTH,IAAMoB,EAAU,IAAIC,GAEpBD,EAAQ,KAAK,OAAO,EAAE,YAAY,oBAAoB,EAEtDA,EAAQ,WAAWE,CAAa,EAChCF,EAAQ,WAAWG,CAAc,EACjCH,EAAQ,WAAWI,CAAY,EAE/BJ,EAAQ,MAAM,QAAQ,IAAI,EAE1B,IAAOK,GAAQL","names":["Command","Command","fs","formatTypeName","input","formatted","sampleConfig","collectionNames","types","name","collections","missingDefaultExport","missingSchema","missingDbs","missingDefaultDb","missingCollections","loadConfigFile","configPath","configUrl","imported","parsed","parseDefaultDbSchema","generateConfigFile","fs","error","defaultDb","objectEntries","db","col","toDbSchemaMetadata","configCommand","Command","value","previous","options","combineMigrations","dumbo","migrationTableSchemaComponent","runPostgreSQLMigrations","Command","migrateCommand","Command","value","previous","options","collection","dryRun","connectionString","collectionNames","loadConfigFile","pool","dumbo","migrations","collectionsName","pongoCollectionSchemaComponent","runPostgreSQLMigrations","c","migrationTableSchemaComponent","collectionName","combineMigrations","checkConnection","LogLevel","LogStyle","prettyJson","SQL","chalk","Table","Command","repl","pongo","calculateColumnWidths","results","columnNames","col","result","shouldDisplayResultsAsTable","printResultsAsTable","print","printOutput","obj","displayResultsAsTable","prettyJson","chalk","value","index","array","columnWidths","table","Table","setLogLevel","logLevel","setLogStyle","prettifyLogs","LogStyle","startRepl","options","connectionString","connectionCheck","checkConnection","shell","repl","db","collectionsSchema","collectionName","pongoSchema","schema","typedClient","pongoClient","SQL","LogLevel","teardown","shellCommand","Command","previous","collection","database","program","Command","configCommand","migrateCommand","shellCommand","cli_default"]}
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkPUUNCOTHcjs = require('./chunk-PUUNCOTH.cjs');exports.ConcurrencyError = _chunkPUUNCOTHcjs.p; exports.DOCUMENT_DOES_NOT_EXIST = _chunkPUUNCOTHcjs.w; exports.DOCUMENT_EXISTS = _chunkPUUNCOTHcjs.v; exports.NO_CONCURRENCY_CHECK = _chunkPUUNCOTHcjs.x; exports.ObjectId = _chunkPUUNCOTHcjs.u; exports.OperatorMap = _chunkPUUNCOTHcjs.j; exports.PongoError = _chunkPUUNCOTHcjs.o; exports.QueryOperators = _chunkPUUNCOTHcjs.i; exports.clientToDbOptions = _chunkPUUNCOTHcjs.I; exports.deepEquals = _chunkPUUNCOTHcjs.J; exports.expectedVersion = _chunkPUUNCOTHcjs.A; exports.expectedVersionValue = _chunkPUUNCOTHcjs.z; exports.getPongoDb = _chunkPUUNCOTHcjs.q; exports.hasOperators = _chunkPUUNCOTHcjs.l; exports.isEquatable = _chunkPUUNCOTHcjs.K; exports.isGeneralExpectedDocumentVersion = _chunkPUUNCOTHcjs.y; exports.isNumber = _chunkPUUNCOTHcjs.m; exports.isOperator = _chunkPUUNCOTHcjs.k; exports.isPostgresClientOptions = _chunkPUUNCOTHcjs.c; exports.isString = _chunkPUUNCOTHcjs.n; exports.objectEntries = _chunkPUUNCOTHcjs.t; exports.operationResult = _chunkPUUNCOTHcjs.B; exports.pongoClient = _chunkPUUNCOTHcjs.H; exports.pongoCollection = _chunkPUUNCOTHcjs.g; exports.pongoCollectionPostgreSQLMigrations = _chunkPUUNCOTHcjs.a; exports.pongoCollectionSchemaComponent = _chunkPUUNCOTHcjs.h; exports.pongoDbSchemaComponent = _chunkPUUNCOTHcjs.e; exports.pongoSchema = _chunkPUUNCOTHcjs.C; exports.pongoSession = _chunkPUUNCOTHcjs.s; exports.pongoTransaction = _chunkPUUNCOTHcjs.r; exports.postgresDb = _chunkPUUNCOTHcjs.d; exports.postgresSQLBuilder = _chunkPUUNCOTHcjs.b; exports.proxyClientWithSchema = _chunkPUUNCOTHcjs.E; exports.proxyPongoDbWithSchema = _chunkPUUNCOTHcjs.D; exports.toClientSchemaMetadata = _chunkPUUNCOTHcjs.G; exports.toDbSchemaMetadata = _chunkPUUNCOTHcjs.F; exports.transactionExecutorOrDefault = _chunkPUUNCOTHcjs.f;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{A,B,C,D,E,F,G,H,I,J,K,a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c,l as d,m as g,n as h,o as i,p as j,q as k,r as l,s as n,t as q,u as s,v as u,w as v,x as w,y,z}from"./chunk-
|
|
1
|
+
import{A,B,C,D,E,F,G,H,I,J,K,a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c,l as d,m as g,n as h,o as i,p as j,q as k,r as l,s as n,t as q,u as s,v as u,w as v,x as w,y,z}from"./chunk-CYDDN3CZ.js";export{j as ConcurrencyError,v as DOCUMENT_DOES_NOT_EXIST,u as DOCUMENT_EXISTS,w as NO_CONCURRENCY_CHECK,s as ObjectId,b as OperatorMap,i as PongoError,a as QueryOperators,I as clientToDbOptions,J as deepEquals,A as expectedVersion,z as expectedVersionValue,k as getPongoDb,d as hasOperators,K as isEquatable,y as isGeneralExpectedDocumentVersion,g as isNumber,c as isOperator,e as isPostgresClientOptions,h as isString,q as objectEntries,B as operationResult,H as pongoClient,t as pongoCollection,o as pongoCollectionPostgreSQLMigrations,x as pongoCollectionSchemaComponent,m as pongoDbSchemaComponent,C as pongoSchema,n as pongoSession,l as pongoTransaction,f as postgresDb,r as postgresSQLBuilder,E as proxyClientWithSchema,D as proxyPongoDbWithSchema,G as toClientSchemaMetadata,F as toDbSchemaMetadata,p as transactionExecutorOrDefault};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/shim.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;var _chunkPUUNCOTHcjs = require('./chunk-PUUNCOTH.cjs');var s= (_class =class{__init() {this.documents=null}__init2() {this.index=0}constructor(e){;_class.prototype.__init.call(this);_class.prototype.__init2.call(this);this.findDocumentsPromise=e}async toArray(){return this.findDocuments()}async forEach(e){let n=await this.findDocuments();for(let t of n)e(t);return Promise.resolve()}hasNext(){if(this.documents===null)throw Error("Error while fetching documents");return this.index<this.documents.length}async next(){let e=await this.findDocuments();return this.hasNext()?_nullishCoalesce(e[this.index++], () => (null)):null}async findDocuments(){return this.documents=await this.findDocumentsPromise,this.documents}}, _class);require('mongodb');var o=r=>_optionalChain([r, 'optionalAccess', _ => _.session])?{session:r.session}:void 0,d= exports.Collection =class{constructor(e){this.collection=e}get dbName(){return this.collection.dbName}get collectionName(){return this.collection.collectionName}get namespace(){return`${this.dbName}.${this.collectionName}`}get readConcern(){}get readPreference(){}get bsonOptions(){return{}}get writeConcern(){}get hint(){}set hint(e){throw new Error("Method not implemented.")}async insertOne(e,n){let t=await this.collection.insertOne(e,o(n));return{acknowledged:t.acknowledged,insertedId:t.insertedId}}async insertMany(e,n){let t=await this.collection.insertMany(e,o(n));return{acknowledged:t.acknowledged,insertedIds:t.insertedIds,insertedCount:t.insertedCount}}bulkWrite(e,n){throw new Error("Method not implemented.")}async updateOne(e,n,t){let i=await this.collection.updateOne(e,n,o(t));return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}replaceOne(e,n,t){return this.collection.replaceOne(e,n,o(t))}async updateMany(e,n,t){let i=await this.collection.updateMany(e,n,o(t));return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}async deleteOne(e,n){let t=await this.collection.deleteOne(e,o(n));return{acknowledged:t.acknowledged,deletedCount:t.deletedCount}}async deleteMany(e,n){let t=await this.collection.deleteMany(e,o(n));return{acknowledged:t.acknowledged,deletedCount:t.deletedCount}}async rename(e,n){return await this.collection.rename(e,o(n)),this}drop(e){return this.collection.drop(o(e))}async findOne(e,n){return await this.collection.findOne(e,o(n))}find(e,n){return new s(this.collection.find(e,o(n)))}options(e){throw new Error("Method not implemented.")}isCapped(e){throw new Error("Method not implemented.")}createIndex(e,n){throw new Error("Method not implemented.")}createIndexes(e,n){throw new Error("Method not implemented.")}dropIndex(e,n){throw new Error("Method not implemented.")}dropIndexes(e){throw new Error("Method not implemented.")}listIndexes(e){throw new Error("Method not implemented.")}indexExists(e,n){throw new Error("Method not implemented.")}indexInformation(e){throw new Error("Method not implemented.")}estimatedDocumentCount(e){return this.collection.countDocuments({},o(e))}countDocuments(e,n){return this.collection.countDocuments(e,o(n))}distinct(e,n,t){throw new Error("Method not implemented.")}indexes(e){throw new Error("Method not implemented.")}findOneAndDelete(e,n){return this.collection.findOneAndDelete(e,o(n))}findOneAndReplace(e,n,t){return this.collection.findOneAndReplace(e,n,o(t))}findOneAndUpdate(e,n,t){return this.collection.findOneAndUpdate(e,n,o(t))}aggregate(e,n){throw new Error("Method not implemented.")}watch(e,n){throw new Error("Method not implemented.")}initializeUnorderedBulkOp(e){throw new Error("Method not implemented.")}initializeOrderedBulkOp(e){throw new Error("Method not implemented.")}count(e,n){return this.collection.countDocuments(_nullishCoalesce(e, () => ({})),o(n))}listSearchIndexes(e,n){throw new Error("Method not implemented.")}createSearchIndex(e){throw new Error("Method not implemented.")}createSearchIndexes(e){throw new Error("Method not implemented.")}dropSearchIndex(e){throw new Error("Method not implemented.")}updateSearchIndex(e,n){throw new Error("Method not implemented.")}async createCollection(){await this.collection.createCollection()}async handle(e,n,t){return this.collection.handle(e.toString(),n,t)}};var l=class{constructor(e){this.pongoDb=e}get databaseName(){return this.pongoDb.databaseName}collection(e){return new d(this.pongoDb.collection(e))}};var u=class{constructor(e,n={}){this.pongoClient=_chunkPUUNCOTHcjs.H.call(void 0, e,n)}async connect(){return await this.pongoClient.connect(),this}async close(){await this.pongoClient.close()}db(e){return new l(this.pongoClient.db(e))}startSession(e){return _chunkPUUNCOTHcjs.s.call(void 0, )}async withSession(e,n){let t=typeof e=="function"?e:n,i=_chunkPUUNCOTHcjs.s.call(void 0, );try{return await t(i)}finally{await i.endSession()}}};exports.Collection = d; exports.Db = l; exports.FindCursor = s; exports.MongoClient = u;
|
|
2
2
|
//# sourceMappingURL=shim.cjs.map
|
package/dist/shim.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{H as p,s as a}from"./chunk-
|
|
1
|
+
import{H as p,s as a}from"./chunk-CYDDN3CZ.js";var s=class{findDocumentsPromise;documents=null;index=0;constructor(e){this.findDocumentsPromise=e}async toArray(){return this.findDocuments()}async forEach(e){let n=await this.findDocuments();for(let t of n)e(t);return Promise.resolve()}hasNext(){if(this.documents===null)throw Error("Error while fetching documents");return this.index<this.documents.length}async next(){let e=await this.findDocuments();return this.hasNext()?e[this.index++]??null:null}async findDocuments(){return this.documents=await this.findDocumentsPromise,this.documents}};import"mongodb";var o=r=>r?.session?{session:r.session}:void 0,d=class{collection;constructor(e){this.collection=e}get dbName(){return this.collection.dbName}get collectionName(){return this.collection.collectionName}get namespace(){return`${this.dbName}.${this.collectionName}`}get readConcern(){}get readPreference(){}get bsonOptions(){return{}}get writeConcern(){}get hint(){}set hint(e){throw new Error("Method not implemented.")}async insertOne(e,n){let t=await this.collection.insertOne(e,o(n));return{acknowledged:t.acknowledged,insertedId:t.insertedId}}async insertMany(e,n){let t=await this.collection.insertMany(e,o(n));return{acknowledged:t.acknowledged,insertedIds:t.insertedIds,insertedCount:t.insertedCount}}bulkWrite(e,n){throw new Error("Method not implemented.")}async updateOne(e,n,t){let i=await this.collection.updateOne(e,n,o(t));return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}replaceOne(e,n,t){return this.collection.replaceOne(e,n,o(t))}async updateMany(e,n,t){let i=await this.collection.updateMany(e,n,o(t));return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}async deleteOne(e,n){let t=await this.collection.deleteOne(e,o(n));return{acknowledged:t.acknowledged,deletedCount:t.deletedCount}}async deleteMany(e,n){let t=await this.collection.deleteMany(e,o(n));return{acknowledged:t.acknowledged,deletedCount:t.deletedCount}}async rename(e,n){return await this.collection.rename(e,o(n)),this}drop(e){return this.collection.drop(o(e))}async findOne(e,n){return await this.collection.findOne(e,o(n))}find(e,n){return new s(this.collection.find(e,o(n)))}options(e){throw new Error("Method not implemented.")}isCapped(e){throw new Error("Method not implemented.")}createIndex(e,n){throw new Error("Method not implemented.")}createIndexes(e,n){throw new Error("Method not implemented.")}dropIndex(e,n){throw new Error("Method not implemented.")}dropIndexes(e){throw new Error("Method not implemented.")}listIndexes(e){throw new Error("Method not implemented.")}indexExists(e,n){throw new Error("Method not implemented.")}indexInformation(e){throw new Error("Method not implemented.")}estimatedDocumentCount(e){return this.collection.countDocuments({},o(e))}countDocuments(e,n){return this.collection.countDocuments(e,o(n))}distinct(e,n,t){throw new Error("Method not implemented.")}indexes(e){throw new Error("Method not implemented.")}findOneAndDelete(e,n){return this.collection.findOneAndDelete(e,o(n))}findOneAndReplace(e,n,t){return this.collection.findOneAndReplace(e,n,o(t))}findOneAndUpdate(e,n,t){return this.collection.findOneAndUpdate(e,n,o(t))}aggregate(e,n){throw new Error("Method not implemented.")}watch(e,n){throw new Error("Method not implemented.")}initializeUnorderedBulkOp(e){throw new Error("Method not implemented.")}initializeOrderedBulkOp(e){throw new Error("Method not implemented.")}count(e,n){return this.collection.countDocuments(e??{},o(n))}listSearchIndexes(e,n){throw new Error("Method not implemented.")}createSearchIndex(e){throw new Error("Method not implemented.")}createSearchIndexes(e){throw new Error("Method not implemented.")}dropSearchIndex(e){throw new Error("Method not implemented.")}updateSearchIndex(e,n){throw new Error("Method not implemented.")}async createCollection(){await this.collection.createCollection()}async handle(e,n,t){return this.collection.handle(e.toString(),n,t)}};var l=class{constructor(e){this.pongoDb=e}get databaseName(){return this.pongoDb.databaseName}collection(e){return new d(this.pongoDb.collection(e))}};var u=class{pongoClient;constructor(e,n={}){this.pongoClient=p(e,n)}async connect(){return await this.pongoClient.connect(),this}async close(){await this.pongoClient.close()}db(e){return new l(this.pongoClient.db(e))}startSession(e){return a()}async withSession(e,n){let t=typeof e=="function"?e:n,i=a();try{return await t(i)}finally{await i.endSession()}}};export{d as Collection,l as Db,s as FindCursor,u as MongoClient};
|
|
2
2
|
//# sourceMappingURL=shim.js.map
|