@orion-js/migrations 4.0.0-next.8 → 4.0.0

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/index.cjs CHANGED
@@ -75,33 +75,29 @@ __export(index_exports, {
75
75
  module.exports = __toCommonJS(index_exports);
76
76
 
77
77
  // src/Schema.ts
78
- var import_typed_model = require("@orion-js/typed-model");
79
- var _completedAt_dec, _name_dec, __id_dec, _MigrationSchema_decorators, _init;
80
- _MigrationSchema_decorators = [(0, import_typed_model.TypedSchema)()], __id_dec = [(0, import_typed_model.Prop)({ type: "string" })], _name_dec = [(0, import_typed_model.Prop)({ type: String })], _completedAt_dec = [(0, import_typed_model.Prop)({ type: Date })];
81
- var MigrationSchema = class {
82
- constructor() {
83
- __publicField(this, "_id", __runInitializers(_init, 8, this)), __runInitializers(_init, 11, this);
84
- __publicField(this, "name", __runInitializers(_init, 12, this)), __runInitializers(_init, 15, this);
85
- __publicField(this, "completedAt", __runInitializers(_init, 16, this)), __runInitializers(_init, 19, this);
78
+ var import_mongodb = require("@orion-js/mongodb");
79
+ var import_schema = require("@orion-js/schema");
80
+ var MigrationSchema = (0, import_schema.schemaWithName)("Migration", {
81
+ _id: {
82
+ type: (0, import_mongodb.typedId)("scnmg")
83
+ },
84
+ name: {
85
+ type: String
86
+ },
87
+ completedAt: {
88
+ type: Date
86
89
  }
87
- };
88
- _init = __decoratorStart(null);
89
- __decorateElement(_init, 5, "_id", __id_dec, MigrationSchema);
90
- __decorateElement(_init, 5, "name", _name_dec, MigrationSchema);
91
- __decorateElement(_init, 5, "completedAt", _completedAt_dec, MigrationSchema);
92
- MigrationSchema = __decorateElement(_init, 0, "MigrationSchema", _MigrationSchema_decorators, MigrationSchema);
93
- __runInitializers(_init, 1, MigrationSchema);
90
+ });
94
91
 
95
92
  // src/Repo.ts
96
- var import_mongodb = require("@orion-js/mongodb");
93
+ var import_mongodb2 = require("@orion-js/mongodb");
97
94
  var import_services = require("@orion-js/services");
98
- var _MigrationsRepo_decorators, _init2;
95
+ var _MigrationsRepo_decorators, _init;
99
96
  _MigrationsRepo_decorators = [(0, import_services.Service)()];
100
97
  var MigrationsRepo = class {
101
- collection = (0, import_mongodb.createCollection)({
98
+ collection = (0, import_mongodb2.createCollection)({
102
99
  name: "orionjs.migrations",
103
100
  schema: MigrationSchema,
104
- idPrefix: "scnmg-",
105
101
  indexes: []
106
102
  });
107
103
  async getCompletedMigrationNames() {
@@ -109,12 +105,15 @@ var MigrationsRepo = class {
109
105
  return migrations.map((m) => m.name);
110
106
  }
111
107
  async saveCompletedMigration(name) {
112
- await this.collection.insertOne({ name, completedAt: /* @__PURE__ */ new Date() });
108
+ await this.collection.insertOne({
109
+ name,
110
+ completedAt: /* @__PURE__ */ new Date()
111
+ });
113
112
  }
114
113
  };
115
- _init2 = __decoratorStart(null);
116
- MigrationsRepo = __decorateElement(_init2, 0, "MigrationsRepo", _MigrationsRepo_decorators, MigrationsRepo);
117
- __runInitializers(_init2, 1, MigrationsRepo);
114
+ _init = __decoratorStart(null);
115
+ MigrationsRepo = __decorateElement(_init, 0, "MigrationsRepo", _MigrationsRepo_decorators, MigrationsRepo);
116
+ __runInitializers(_init, 1, MigrationsRepo);
118
117
 
119
118
  // src/loadMigrations/index.ts
120
119
  var import_dogs = require("@orion-js/dogs");
@@ -124,7 +123,7 @@ var import_services2 = require("@orion-js/services");
124
123
  var import_services3 = require("@orion-js/services");
125
124
  var serviceMetadata = /* @__PURE__ */ new WeakMap();
126
125
  function MigrationService(options) {
127
- return function(target, context) {
126
+ return (target, context) => {
128
127
  (0, import_services3.Service)()(target, context);
129
128
  context.addInitializer(function() {
130
129
  serviceMetadata.set(this, { _serviceType: "migrations", options });
@@ -154,11 +153,11 @@ var import_services5 = require("@orion-js/services");
154
153
  // src/MigrationsService.ts
155
154
  var import_services4 = require("@orion-js/services");
156
155
  var import_logger = require("@orion-js/logger");
157
- var _migrationsRepo_dec, _MigrationsService_decorators, _init3;
156
+ var _migrationsRepo_dec, _MigrationsService_decorators, _init2;
158
157
  _MigrationsService_decorators = [(0, import_services4.Service)()], _migrationsRepo_dec = [(0, import_services4.Inject)(() => MigrationsRepo)];
159
158
  var MigrationsService = class {
160
159
  constructor() {
161
- __publicField(this, "migrationsRepo", __runInitializers(_init3, 8, this)), __runInitializers(_init3, 11, this);
160
+ __publicField(this, "migrationsRepo", __runInitializers(_init2, 8, this)), __runInitializers(_init2, 11, this);
162
161
  }
163
162
  async getNextMigration(migrationsList) {
164
163
  const completedNames = await this.migrationsRepo.getCompletedMigrationNames();
@@ -202,10 +201,10 @@ var MigrationsService = class {
202
201
  session.endSession();
203
202
  }
204
203
  };
205
- _init3 = __decoratorStart(null);
206
- __decorateElement(_init3, 5, "migrationsRepo", _migrationsRepo_dec, MigrationsService);
207
- MigrationsService = __decorateElement(_init3, 0, "MigrationsService", _MigrationsService_decorators, MigrationsService);
208
- __runInitializers(_init3, 1, MigrationsService);
204
+ _init2 = __decoratorStart(null);
205
+ __decorateElement(_init2, 5, "migrationsRepo", _migrationsRepo_dec, MigrationsService);
206
+ MigrationsService = __decorateElement(_init2, 0, "MigrationsService", _MigrationsService_decorators, MigrationsService);
207
+ __runInitializers(_init2, 1, MigrationsService);
209
208
 
210
209
  // src/loadMigrations/index.ts
211
210
  function loadMigrations(migrationServices, options) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/Schema.ts","../src/Repo.ts","../src/loadMigrations/index.ts","../src/service/index.ts","../src/MigrationsService.ts"],"sourcesContent":["export * from './Schema'\nexport * from './Repo'\nexport * from './loadMigrations'\nexport * from './service'\nexport * from './MigrationsService'\n","import {TypedSchema, Prop} from '@orion-js/typed-model'\n\nexport type MigrationId = `scnmg-${string}`\n\n@TypedSchema()\nexport class MigrationSchema {\n @Prop({type: 'string'})\n _id: MigrationId\n\n @Prop({type: String})\n name: string\n\n @Prop({type: Date})\n completedAt: Date\n}\n","import {createCollection} from '@orion-js/mongodb'\nimport {MigrationSchema} from './Schema'\nimport {Service} from '@orion-js/services'\n\n@Service()\nexport class MigrationsRepo {\n public collection = createCollection<MigrationSchema>({\n name: 'orionjs.migrations',\n schema: MigrationSchema,\n idPrefix: 'scnmg-',\n indexes: [],\n })\n\n async getCompletedMigrationNames() {\n const migrations = await this.collection.find().toArray()\n return migrations.map(m => m.name)\n }\n\n async saveCompletedMigration(name: string) {\n await this.collection.insertOne({name, completedAt: new Date()})\n }\n}\n","import {defineJob, startWorkers} from '@orion-js/dogs'\nimport {getMigrationsFromServices} from '../service'\nimport {getInstance} from '@orion-js/services'\nimport {MigrationsService} from '../MigrationsService'\n\nexport interface Options {\n lockTime?: number\n omitJob?: boolean\n}\n\nexport function loadMigrations(migrationServices: any[], options?: Options) {\n const migrations = getMigrationsFromServices(migrationServices)\n if (options?.omitJob) return migrations\n\n startWorkers({\n cooldownPeriod: 1000,\n lockTime: 1000 * 60 * 20, // 20 min\n workersCount: 1,\n pollInterval: 10 * 1000,\n jobs: {\n orionjsRunMigrations: defineJob({\n type: 'recurrent',\n runEvery: 30 * 1000,\n async resolve(_params, context) {\n const instance = getInstance(MigrationsService)\n await instance.runMigrations(migrations, context)\n },\n }),\n },\n })\n\n return migrations\n}\n","import {ExecutionContext} from '@orion-js/dogs'\nimport {getInstance} from '@orion-js/services'\nimport {Service} from '@orion-js/services'\n\nexport interface MigrationServiceOptions {\n name: string\n useMongoTransactions: false\n}\n\n// Define metadata storage using WeakMaps\nconst serviceMetadata = new WeakMap<any, {_serviceType: string; options: MigrationServiceOptions}>()\n\nexport function MigrationService(options: MigrationServiceOptions) {\n return function (target: any, context: ClassDecoratorContext<any>) {\n Service()(target, context)\n\n context.addInitializer(function (this) {\n serviceMetadata.set(this, {_serviceType: 'migrations', options: options})\n })\n }\n}\n\nexport type MigrationExecutable = {\n runMigration(context: ExecutionContext): Promise<void>\n} & MigrationServiceOptions\n\nexport function getMigrationsFromServices(services: any[]): MigrationExecutable[] {\n return services.map(service => {\n const instance = getInstance(service)\n const options = serviceMetadata.get(instance.constructor)\n if (!options._serviceType || options._serviceType !== 'migrations') {\n throw new Error(`Service ${service.name} is not a migration service`)\n }\n\n return {\n ...options.options,\n runMigration: async (context: ExecutionContext) => {\n const instance = getInstance(service) as any\n return await instance.runMigration(context)\n },\n }\n })\n}\n","import {Inject, Service} from '@orion-js/services'\nimport type {MigrationsRepo as MigrationsRepoType} from './Repo'\nimport {MigrationsRepo} from './Repo'\nimport {logger} from '@orion-js/logger'\nimport {MigrationExecutable} from './service'\nimport {ExecutionContext} from '@orion-js/dogs'\n\n@Service()\nexport class MigrationsService {\n @Inject(() => MigrationsRepo)\n private migrationsRepo: MigrationsRepoType\n\n async getNextMigration(migrationsList: MigrationExecutable[]) {\n const completedNames = await this.migrationsRepo.getCompletedMigrationNames()\n\n for (const migrationExecutable of migrationsList) {\n if (completedNames.includes(migrationExecutable.name)) continue\n return migrationExecutable\n }\n }\n\n async runMigrations(migrationsList: MigrationExecutable[], context: ExecutionContext) {\n const next = await this.getNextMigration(migrationsList)\n if (!next) return\n\n logger.info('[orionjs/migrations] Running migration...', {name: next.name})\n\n if (next.useMongoTransactions) {\n await this.runAsTransaction(next.runMigration, context)\n } else {\n await this.runMigration(next.runMigration, context)\n }\n\n logger.info('[orionjs/migrations] Migration executed correctly', {name: next.name})\n\n await this.migrationsRepo.saveCompletedMigration(next.name)\n\n await this.runMigrations(migrationsList, context)\n }\n\n async runMigration(\n func: (context: ExecutionContext) => Promise<void>,\n context: ExecutionContext,\n ) {\n try {\n await func(context)\n } catch (error) {\n logger.error('[orionjs/migrations] Error running migration', error)\n throw error\n }\n }\n\n async runAsTransaction(\n func: (context: ExecutionContext) => Promise<void>,\n context: ExecutionContext,\n ) {\n const {client} = this.migrationsRepo.collection.client\n const session = client.startSession()\n\n await session.withTransaction(async () => {\n try {\n await func(context)\n } catch (error) {\n logger.error('[orionjs/migrations] Error running migration, will abort transaction', error)\n throw error\n }\n })\n\n session.endSession()\n }\n}\n"],"mappings":";;;;;;;;;;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,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AAED,SAAO;AACT;","names":["_init","import_services","instance","import_services","import_services","_init"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/Schema.ts","../src/Repo.ts","../src/loadMigrations/index.ts","../src/service/index.ts","../src/MigrationsService.ts"],"sourcesContent":["export * from './Schema'\nexport * from './Repo'\nexport * from './loadMigrations'\nexport * from './service'\nexport * from './MigrationsService'\n","import {TypedId, typedId} from '@orion-js/mongodb'\nimport {InferSchemaType, schemaWithName} from '@orion-js/schema'\n\nexport type MigrationId = TypedId<'scnmg'>\n\nexport const MigrationSchema = schemaWithName('Migration', {\n _id: {\n type: typedId('scnmg'),\n },\n name: {\n type: String,\n },\n completedAt: {\n type: Date,\n },\n})\n\nexport type MigrationType = InferSchemaType<typeof MigrationSchema>\n","import {createCollection} from '@orion-js/mongodb'\nimport {MigrationSchema} from './Schema'\nimport {Service} from '@orion-js/services'\n\n@Service()\nexport class MigrationsRepo {\n public collection = createCollection({\n name: 'orionjs.migrations',\n schema: MigrationSchema,\n indexes: [],\n })\n\n async getCompletedMigrationNames() {\n const migrations = await this.collection.find().toArray()\n return migrations.map(m => m.name)\n }\n\n async saveCompletedMigration(name: string) {\n await this.collection.insertOne({\n name,\n completedAt: new Date(),\n })\n }\n}\n","import {defineJob, startWorkers} from '@orion-js/dogs'\nimport {getMigrationsFromServices} from '../service'\nimport {getInstance} from '@orion-js/services'\nimport {MigrationsService} from '../MigrationsService'\n\nexport interface Options {\n lockTime?: number\n omitJob?: boolean\n}\n\nexport function loadMigrations(migrationServices: any[], options?: Options) {\n const migrations = getMigrationsFromServices(migrationServices)\n if (options?.omitJob) return migrations\n\n startWorkers({\n cooldownPeriod: 1000,\n lockTime: 1000 * 60 * 20, // 20 min\n workersCount: 1,\n pollInterval: 10 * 1000,\n jobs: {\n orionjsRunMigrations: defineJob({\n type: 'recurrent',\n runEvery: 30 * 1000,\n async resolve(_params, context) {\n const instance = getInstance(MigrationsService)\n await instance.runMigrations(migrations, context)\n },\n }),\n },\n })\n\n return migrations\n}\n","import {ExecutionContext} from '@orion-js/dogs'\nimport {getInstance} from '@orion-js/services'\nimport {Service} from '@orion-js/services'\n\nexport interface MigrationServiceOptions {\n name: string\n useMongoTransactions: false\n}\n\n// Define metadata storage using WeakMaps\nconst serviceMetadata = new WeakMap<any, {_serviceType: string; options: MigrationServiceOptions}>()\n\nexport function MigrationService(options: MigrationServiceOptions) {\n return (target: any, context: ClassDecoratorContext<any>) => {\n Service()(target, context)\n\n context.addInitializer(function (this) {\n serviceMetadata.set(this, {_serviceType: 'migrations', options: options})\n })\n }\n}\n\nexport type MigrationExecutable = {\n runMigration(context: ExecutionContext): Promise<void>\n} & MigrationServiceOptions\n\nexport function getMigrationsFromServices(services: any[]): MigrationExecutable[] {\n return services.map(service => {\n const instance = getInstance(service)\n const options = serviceMetadata.get(instance.constructor)\n if (!options._serviceType || options._serviceType !== 'migrations') {\n throw new Error(`Service ${service.name} is not a migration service`)\n }\n\n return {\n ...options.options,\n runMigration: async (context: ExecutionContext) => {\n const instance = getInstance(service) as any\n return await instance.runMigration(context)\n },\n }\n })\n}\n","import {Inject, Service} from '@orion-js/services'\nimport type {MigrationsRepo as MigrationsRepoType} from './Repo'\nimport {MigrationsRepo} from './Repo'\nimport {logger} from '@orion-js/logger'\nimport {MigrationExecutable} from './service'\nimport {ExecutionContext} from '@orion-js/dogs'\n\n@Service()\nexport class MigrationsService {\n @Inject(() => MigrationsRepo)\n private migrationsRepo: MigrationsRepoType\n\n async getNextMigration(migrationsList: MigrationExecutable[]) {\n const completedNames = await this.migrationsRepo.getCompletedMigrationNames()\n\n for (const migrationExecutable of migrationsList) {\n if (completedNames.includes(migrationExecutable.name)) continue\n return migrationExecutable\n }\n }\n\n async runMigrations(migrationsList: MigrationExecutable[], context: ExecutionContext) {\n const next = await this.getNextMigration(migrationsList)\n if (!next) return\n\n logger.info('[orionjs/migrations] Running migration...', {name: next.name})\n\n if (next.useMongoTransactions) {\n await this.runAsTransaction(next.runMigration, context)\n } else {\n await this.runMigration(next.runMigration, context)\n }\n\n logger.info('[orionjs/migrations] Migration executed correctly', {name: next.name})\n\n await this.migrationsRepo.saveCompletedMigration(next.name)\n\n await this.runMigrations(migrationsList, context)\n }\n\n async runMigration(\n func: (context: ExecutionContext) => Promise<void>,\n context: ExecutionContext,\n ) {\n try {\n await func(context)\n } catch (error) {\n logger.error('[orionjs/migrations] Error running migration', error)\n throw error\n }\n }\n\n async runAsTransaction(\n func: (context: ExecutionContext) => Promise<void>,\n context: ExecutionContext,\n ) {\n const {client} = this.migrationsRepo.collection.client\n const session = client.startSession()\n\n await session.withTransaction(async () => {\n try {\n await func(context)\n } catch (error) {\n logger.error('[orionjs/migrations] Error running migration, will abort transaction', error)\n throw error\n }\n })\n\n session.endSession()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,qBAA+B;AAC/B,oBAA8C;AAIvC,IAAM,sBAAkB,8BAAe,aAAa;AAAA,EACzD,KAAK;AAAA,IACH,UAAM,wBAAQ,OAAO;AAAA,EACvB;AAAA,EACA,MAAM;AAAA,IACJ,MAAM;AAAA,EACR;AAAA,EACA,aAAa;AAAA,IACX,MAAM;AAAA,EACR;AACF,CAAC;;;ACfD,IAAAA,kBAA+B;AAE/B,sBAAsB;AAFtB;AAIA,kCAAC,yBAAQ;AACF,IAAM,iBAAN,MAAqB;AAAA,EACnB,iBAAa,kCAAiB;AAAA,IACnC,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,SAAS,CAAC;AAAA,EACZ,CAAC;AAAA,EAED,MAAM,6BAA6B;AACjC,UAAM,aAAa,MAAM,KAAK,WAAW,KAAK,EAAE,QAAQ;AACxD,WAAO,WAAW,IAAI,OAAK,EAAE,IAAI;AAAA,EACnC;AAAA,EAEA,MAAM,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iBAAiB;AAC9D,MAAI,mCAAS,QAAS,QAAO;AAE7B,gCAAa;AAAA,IACX,gBAAgB;AAAA,IAChB,UAAU,MAAO,KAAK;AAAA;AAAA,IACtB,cAAc;AAAA,IACd,cAAc,KAAK;AAAA,IACnB,MAAM;AAAA,MACJ,0BAAsB,uBAAU;AAAA,QAC9B,MAAM;AAAA,QACN,UAAU,KAAK;AAAA,QACf,MAAM,QAAQ,SAAS,SAAS;AAC9B,gBAAM,eAAW,8BAAY,iBAAiB;AAC9C,gBAAM,SAAS,cAAc,YAAY,OAAO;AAAA,QAClD;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AAED,SAAO;AACT;","names":["import_mongodb","import_services","instance","import_services","import_services","_init"]}
package/dist/index.d.cts CHANGED
@@ -1,15 +1,35 @@
1
+ import * as _orion_js_schema from '@orion-js/schema';
2
+ import { InferSchemaType } from '@orion-js/schema';
1
3
  import * as _orion_js_mongodb from '@orion-js/mongodb';
4
+ import { TypedId } from '@orion-js/mongodb';
2
5
  import { ExecutionContext } from '@orion-js/dogs';
3
6
 
4
- type MigrationId = `scnmg-${string}`;
5
- declare class MigrationSchema {
6
- _id: MigrationId;
7
- name: string;
8
- completedAt: Date;
9
- }
7
+ type MigrationId = TypedId<'scnmg'>;
8
+ declare const MigrationSchema: {
9
+ _id: {
10
+ type: _orion_js_schema.FieldType<`scnmg-${string}`>;
11
+ };
12
+ name: {
13
+ type: StringConstructor;
14
+ };
15
+ completedAt: {
16
+ type: DateConstructor;
17
+ };
18
+ };
19
+ type MigrationType = InferSchemaType<typeof MigrationSchema>;
10
20
 
11
21
  declare class MigrationsRepo {
12
- collection: _orion_js_mongodb.Collection<_orion_js_mongodb.DocumentWithId<MigrationSchema>>;
22
+ collection: _orion_js_mongodb.Collection<_orion_js_mongodb.InferSchemaTypeWithId<{
23
+ _id: {
24
+ type: _orion_js_schema.FieldType<`scnmg-${string}`>;
25
+ };
26
+ name: {
27
+ type: StringConstructor;
28
+ };
29
+ completedAt: {
30
+ type: DateConstructor;
31
+ };
32
+ }>>;
13
33
  getCompletedMigrationNames(): Promise<string[]>;
14
34
  saveCompletedMigration(name: string): Promise<void>;
15
35
  }
@@ -38,4 +58,4 @@ declare class MigrationsService {
38
58
  runAsTransaction(func: (context: ExecutionContext) => Promise<void>, context: ExecutionContext): Promise<void>;
39
59
  }
40
60
 
41
- export { type MigrationExecutable, type MigrationId, MigrationSchema, MigrationService, type MigrationServiceOptions, MigrationsRepo, MigrationsService, type Options, getMigrationsFromServices, loadMigrations };
61
+ export { type MigrationExecutable, type MigrationId, MigrationSchema, MigrationService, type MigrationServiceOptions, type MigrationType, MigrationsRepo, MigrationsService, type Options, getMigrationsFromServices, loadMigrations };
package/dist/index.d.ts CHANGED
@@ -1,15 +1,35 @@
1
+ import * as _orion_js_schema from '@orion-js/schema';
2
+ import { InferSchemaType } from '@orion-js/schema';
1
3
  import * as _orion_js_mongodb from '@orion-js/mongodb';
4
+ import { TypedId } from '@orion-js/mongodb';
2
5
  import { ExecutionContext } from '@orion-js/dogs';
3
6
 
4
- type MigrationId = `scnmg-${string}`;
5
- declare class MigrationSchema {
6
- _id: MigrationId;
7
- name: string;
8
- completedAt: Date;
9
- }
7
+ type MigrationId = TypedId<'scnmg'>;
8
+ declare const MigrationSchema: {
9
+ _id: {
10
+ type: _orion_js_schema.FieldType<`scnmg-${string}`>;
11
+ };
12
+ name: {
13
+ type: StringConstructor;
14
+ };
15
+ completedAt: {
16
+ type: DateConstructor;
17
+ };
18
+ };
19
+ type MigrationType = InferSchemaType<typeof MigrationSchema>;
10
20
 
11
21
  declare class MigrationsRepo {
12
- collection: _orion_js_mongodb.Collection<_orion_js_mongodb.DocumentWithId<MigrationSchema>>;
22
+ collection: _orion_js_mongodb.Collection<_orion_js_mongodb.InferSchemaTypeWithId<{
23
+ _id: {
24
+ type: _orion_js_schema.FieldType<`scnmg-${string}`>;
25
+ };
26
+ name: {
27
+ type: StringConstructor;
28
+ };
29
+ completedAt: {
30
+ type: DateConstructor;
31
+ };
32
+ }>>;
13
33
  getCompletedMigrationNames(): Promise<string[]>;
14
34
  saveCompletedMigration(name: string): Promise<void>;
15
35
  }
@@ -38,4 +58,4 @@ declare class MigrationsService {
38
58
  runAsTransaction(func: (context: ExecutionContext) => Promise<void>, context: ExecutionContext): Promise<void>;
39
59
  }
40
60
 
41
- export { type MigrationExecutable, type MigrationId, MigrationSchema, MigrationService, type MigrationServiceOptions, MigrationsRepo, MigrationsService, type Options, getMigrationsFromServices, loadMigrations };
61
+ export { type MigrationExecutable, type MigrationId, MigrationSchema, MigrationService, type MigrationServiceOptions, type MigrationType, MigrationsRepo, MigrationsService, type Options, getMigrationsFromServices, loadMigrations };
package/dist/index.js CHANGED
@@ -48,33 +48,29 @@ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "
48
48
  var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
49
49
 
50
50
  // src/Schema.ts
51
- import { TypedSchema, Prop } from "@orion-js/typed-model";
52
- var _completedAt_dec, _name_dec, __id_dec, _MigrationSchema_decorators, _init;
53
- _MigrationSchema_decorators = [TypedSchema()], __id_dec = [Prop({ type: "string" })], _name_dec = [Prop({ type: String })], _completedAt_dec = [Prop({ type: Date })];
54
- var MigrationSchema = class {
55
- constructor() {
56
- __publicField(this, "_id", __runInitializers(_init, 8, this)), __runInitializers(_init, 11, this);
57
- __publicField(this, "name", __runInitializers(_init, 12, this)), __runInitializers(_init, 15, this);
58
- __publicField(this, "completedAt", __runInitializers(_init, 16, this)), __runInitializers(_init, 19, this);
51
+ import { typedId } from "@orion-js/mongodb";
52
+ import { schemaWithName } from "@orion-js/schema";
53
+ var MigrationSchema = schemaWithName("Migration", {
54
+ _id: {
55
+ type: typedId("scnmg")
56
+ },
57
+ name: {
58
+ type: String
59
+ },
60
+ completedAt: {
61
+ type: Date
59
62
  }
60
- };
61
- _init = __decoratorStart(null);
62
- __decorateElement(_init, 5, "_id", __id_dec, MigrationSchema);
63
- __decorateElement(_init, 5, "name", _name_dec, MigrationSchema);
64
- __decorateElement(_init, 5, "completedAt", _completedAt_dec, MigrationSchema);
65
- MigrationSchema = __decorateElement(_init, 0, "MigrationSchema", _MigrationSchema_decorators, MigrationSchema);
66
- __runInitializers(_init, 1, MigrationSchema);
63
+ });
67
64
 
68
65
  // src/Repo.ts
69
66
  import { createCollection } from "@orion-js/mongodb";
70
67
  import { Service } from "@orion-js/services";
71
- var _MigrationsRepo_decorators, _init2;
68
+ var _MigrationsRepo_decorators, _init;
72
69
  _MigrationsRepo_decorators = [Service()];
73
70
  var MigrationsRepo = class {
74
71
  collection = createCollection({
75
72
  name: "orionjs.migrations",
76
73
  schema: MigrationSchema,
77
- idPrefix: "scnmg-",
78
74
  indexes: []
79
75
  });
80
76
  async getCompletedMigrationNames() {
@@ -82,12 +78,15 @@ var MigrationsRepo = class {
82
78
  return migrations.map((m) => m.name);
83
79
  }
84
80
  async saveCompletedMigration(name) {
85
- await this.collection.insertOne({ name, completedAt: /* @__PURE__ */ new Date() });
81
+ await this.collection.insertOne({
82
+ name,
83
+ completedAt: /* @__PURE__ */ new Date()
84
+ });
86
85
  }
87
86
  };
88
- _init2 = __decoratorStart(null);
89
- MigrationsRepo = __decorateElement(_init2, 0, "MigrationsRepo", _MigrationsRepo_decorators, MigrationsRepo);
90
- __runInitializers(_init2, 1, MigrationsRepo);
87
+ _init = __decoratorStart(null);
88
+ MigrationsRepo = __decorateElement(_init, 0, "MigrationsRepo", _MigrationsRepo_decorators, MigrationsRepo);
89
+ __runInitializers(_init, 1, MigrationsRepo);
91
90
 
92
91
  // src/loadMigrations/index.ts
93
92
  import { defineJob, startWorkers } from "@orion-js/dogs";
@@ -97,7 +96,7 @@ import { getInstance } from "@orion-js/services";
97
96
  import { Service as Service2 } from "@orion-js/services";
98
97
  var serviceMetadata = /* @__PURE__ */ new WeakMap();
99
98
  function MigrationService(options) {
100
- return function(target, context) {
99
+ return (target, context) => {
101
100
  Service2()(target, context);
102
101
  context.addInitializer(function() {
103
102
  serviceMetadata.set(this, { _serviceType: "migrations", options });
@@ -127,11 +126,11 @@ import { getInstance as getInstance2 } from "@orion-js/services";
127
126
  // src/MigrationsService.ts
128
127
  import { Inject, Service as Service3 } from "@orion-js/services";
129
128
  import { logger } from "@orion-js/logger";
130
- var _migrationsRepo_dec, _MigrationsService_decorators, _init3;
129
+ var _migrationsRepo_dec, _MigrationsService_decorators, _init2;
131
130
  _MigrationsService_decorators = [Service3()], _migrationsRepo_dec = [Inject(() => MigrationsRepo)];
132
131
  var MigrationsService = class {
133
132
  constructor() {
134
- __publicField(this, "migrationsRepo", __runInitializers(_init3, 8, this)), __runInitializers(_init3, 11, this);
133
+ __publicField(this, "migrationsRepo", __runInitializers(_init2, 8, this)), __runInitializers(_init2, 11, this);
135
134
  }
136
135
  async getNextMigration(migrationsList) {
137
136
  const completedNames = await this.migrationsRepo.getCompletedMigrationNames();
@@ -175,10 +174,10 @@ var MigrationsService = class {
175
174
  session.endSession();
176
175
  }
177
176
  };
178
- _init3 = __decoratorStart(null);
179
- __decorateElement(_init3, 5, "migrationsRepo", _migrationsRepo_dec, MigrationsService);
180
- MigrationsService = __decorateElement(_init3, 0, "MigrationsService", _MigrationsService_decorators, MigrationsService);
181
- __runInitializers(_init3, 1, MigrationsService);
177
+ _init2 = __decoratorStart(null);
178
+ __decorateElement(_init2, 5, "migrationsRepo", _migrationsRepo_dec, MigrationsService);
179
+ MigrationsService = __decorateElement(_init2, 0, "MigrationsService", _MigrationsService_decorators, MigrationsService);
180
+ __runInitializers(_init2, 1, MigrationsService);
182
181
 
183
182
  // src/loadMigrations/index.ts
184
183
  function loadMigrations(migrationServices, options) {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/Schema.ts","../src/Repo.ts","../src/loadMigrations/index.ts","../src/service/index.ts","../src/MigrationsService.ts"],"sourcesContent":["import {TypedSchema, Prop} from '@orion-js/typed-model'\n\nexport type MigrationId = `scnmg-${string}`\n\n@TypedSchema()\nexport class MigrationSchema {\n @Prop({type: 'string'})\n _id: MigrationId\n\n @Prop({type: String})\n name: string\n\n @Prop({type: Date})\n completedAt: Date\n}\n","import {createCollection} from '@orion-js/mongodb'\nimport {MigrationSchema} from './Schema'\nimport {Service} from '@orion-js/services'\n\n@Service()\nexport class MigrationsRepo {\n public collection = createCollection<MigrationSchema>({\n name: 'orionjs.migrations',\n schema: MigrationSchema,\n idPrefix: 'scnmg-',\n indexes: [],\n })\n\n async getCompletedMigrationNames() {\n const migrations = await this.collection.find().toArray()\n return migrations.map(m => m.name)\n }\n\n async saveCompletedMigration(name: string) {\n await this.collection.insertOne({name, completedAt: new Date()})\n }\n}\n","import {defineJob, startWorkers} from '@orion-js/dogs'\nimport {getMigrationsFromServices} from '../service'\nimport {getInstance} from '@orion-js/services'\nimport {MigrationsService} from '../MigrationsService'\n\nexport interface Options {\n lockTime?: number\n omitJob?: boolean\n}\n\nexport function loadMigrations(migrationServices: any[], options?: Options) {\n const migrations = getMigrationsFromServices(migrationServices)\n if (options?.omitJob) return migrations\n\n startWorkers({\n cooldownPeriod: 1000,\n lockTime: 1000 * 60 * 20, // 20 min\n workersCount: 1,\n pollInterval: 10 * 1000,\n jobs: {\n orionjsRunMigrations: defineJob({\n type: 'recurrent',\n runEvery: 30 * 1000,\n async resolve(_params, context) {\n const instance = getInstance(MigrationsService)\n await instance.runMigrations(migrations, context)\n },\n }),\n },\n })\n\n return migrations\n}\n","import {ExecutionContext} from '@orion-js/dogs'\nimport {getInstance} from '@orion-js/services'\nimport {Service} from '@orion-js/services'\n\nexport interface MigrationServiceOptions {\n name: string\n useMongoTransactions: false\n}\n\n// Define metadata storage using WeakMaps\nconst serviceMetadata = new WeakMap<any, {_serviceType: string; options: MigrationServiceOptions}>()\n\nexport function MigrationService(options: MigrationServiceOptions) {\n return function (target: any, context: ClassDecoratorContext<any>) {\n Service()(target, context)\n\n context.addInitializer(function (this) {\n serviceMetadata.set(this, {_serviceType: 'migrations', options: options})\n })\n }\n}\n\nexport type MigrationExecutable = {\n runMigration(context: ExecutionContext): Promise<void>\n} & MigrationServiceOptions\n\nexport function getMigrationsFromServices(services: any[]): MigrationExecutable[] {\n return services.map(service => {\n const instance = getInstance(service)\n const options = serviceMetadata.get(instance.constructor)\n if (!options._serviceType || options._serviceType !== 'migrations') {\n throw new Error(`Service ${service.name} is not a migration service`)\n }\n\n return {\n ...options.options,\n runMigration: async (context: ExecutionContext) => {\n const instance = getInstance(service) as any\n return await instance.runMigration(context)\n },\n }\n })\n}\n","import {Inject, Service} from '@orion-js/services'\nimport type {MigrationsRepo as MigrationsRepoType} from './Repo'\nimport {MigrationsRepo} from './Repo'\nimport {logger} from '@orion-js/logger'\nimport {MigrationExecutable} from './service'\nimport {ExecutionContext} from '@orion-js/dogs'\n\n@Service()\nexport class MigrationsService {\n @Inject(() => MigrationsRepo)\n private migrationsRepo: MigrationsRepoType\n\n async getNextMigration(migrationsList: MigrationExecutable[]) {\n const completedNames = await this.migrationsRepo.getCompletedMigrationNames()\n\n for (const migrationExecutable of migrationsList) {\n if (completedNames.includes(migrationExecutable.name)) continue\n return migrationExecutable\n }\n }\n\n async runMigrations(migrationsList: MigrationExecutable[], context: ExecutionContext) {\n const next = await this.getNextMigration(migrationsList)\n if (!next) return\n\n logger.info('[orionjs/migrations] Running migration...', {name: next.name})\n\n if (next.useMongoTransactions) {\n await this.runAsTransaction(next.runMigration, context)\n } else {\n await this.runMigration(next.runMigration, context)\n }\n\n logger.info('[orionjs/migrations] Migration executed correctly', {name: next.name})\n\n await this.migrationsRepo.saveCompletedMigration(next.name)\n\n await this.runMigrations(migrationsList, context)\n }\n\n async runMigration(\n func: (context: ExecutionContext) => Promise<void>,\n context: ExecutionContext,\n ) {\n try {\n await func(context)\n } catch (error) {\n logger.error('[orionjs/migrations] Error running migration', error)\n throw error\n }\n }\n\n async runAsTransaction(\n func: (context: ExecutionContext) => Promise<void>,\n context: ExecutionContext,\n ) {\n const {client} = this.migrationsRepo.collection.client\n const session = client.startSession()\n\n await session.withTransaction(async () => {\n try {\n await func(context)\n } catch (error) {\n logger.error('[orionjs/migrations] Error running migration, will abort transaction', error)\n throw error\n }\n })\n\n session.endSession()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAQ,aAAa,YAAW;AAAhC;AAIA,+BAAC,YAAY,IAEX,YAAC,KAAK,EAAC,MAAM,SAAQ,CAAC,IAGtB,aAAC,KAAK,EAAC,MAAM,OAAM,CAAC,IAGpB,oBAAC,KAAK,EAAC,MAAM,KAAI,CAAC;AAPb,IAAM,kBAAN,MAAsB;AAAA,EAAtB;AAEL;AAGA;AAGA;AAAA;AACF;AATO;AAEL,mCADA,UADW;AAKX,oCADA,WAJW;AAQX,2CADA,kBAPW;AAAA,kBAAN,+CADP,6BACa;AAAN,4BAAM;;;ACLb,SAAQ,wBAAuB;AAE/B,SAAQ,eAAc;AAFtB,gCAAAA;AAIA,8BAAC,QAAQ;AACF,IAAM,iBAAN,MAAqB;AAAA,EACnB,aAAa,iBAAkC;AAAA,IACpD,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,UAAU;AAAA,IACV,SAAS,CAAC;AAAA,EACZ,CAAC;AAAA,EAED,MAAM,6BAA6B;AACjC,UAAM,aAAa,MAAM,KAAK,WAAW,KAAK,EAAE,QAAQ;AACxD,WAAO,WAAW,IAAI,OAAK,EAAE,IAAI;AAAA,EACnC;AAAA,EAEA,MAAM,uBAAuB,MAAc;AACzC,UAAM,KAAK,WAAW,UAAU,EAAC,MAAM,aAAa,oBAAI,KAAK,EAAC,CAAC;AAAA,EACjE;AACF;AAhBOA,SAAA;AAAM,iBAAN,kBAAAA,QAAA,qBADP,4BACa;AAAN,kBAAAA,QAAA,GAAM;;;ACLb,SAAQ,WAAW,oBAAmB;;;ACCtC,SAAQ,mBAAkB;AAC1B,SAAQ,WAAAC,gBAAc;AAQtB,IAAM,kBAAkB,oBAAI,QAAu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,MAAM,QAAQ,SAAS,SAAS;AAC9B,gBAAM,WAAWE,aAAY,iBAAiB;AAC9C,gBAAM,SAAS,cAAc,YAAY,OAAO;AAAA,QAClD;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AAED,SAAO;AACT;","names":["_init","Service","instance","getInstance","Service","_init","Service","getInstance"]}
1
+ {"version":3,"sources":["../src/Schema.ts","../src/Repo.ts","../src/loadMigrations/index.ts","../src/service/index.ts","../src/MigrationsService.ts"],"sourcesContent":["import {TypedId, typedId} from '@orion-js/mongodb'\nimport {InferSchemaType, schemaWithName} from '@orion-js/schema'\n\nexport type MigrationId = TypedId<'scnmg'>\n\nexport const MigrationSchema = schemaWithName('Migration', {\n _id: {\n type: typedId('scnmg'),\n },\n name: {\n type: String,\n },\n completedAt: {\n type: Date,\n },\n})\n\nexport type MigrationType = InferSchemaType<typeof MigrationSchema>\n","import {createCollection} from '@orion-js/mongodb'\nimport {MigrationSchema} from './Schema'\nimport {Service} from '@orion-js/services'\n\n@Service()\nexport class MigrationsRepo {\n public collection = createCollection({\n name: 'orionjs.migrations',\n schema: MigrationSchema,\n indexes: [],\n })\n\n async getCompletedMigrationNames() {\n const migrations = await this.collection.find().toArray()\n return migrations.map(m => m.name)\n }\n\n async saveCompletedMigration(name: string) {\n await this.collection.insertOne({\n name,\n completedAt: new Date(),\n })\n }\n}\n","import {defineJob, startWorkers} from '@orion-js/dogs'\nimport {getMigrationsFromServices} from '../service'\nimport {getInstance} from '@orion-js/services'\nimport {MigrationsService} from '../MigrationsService'\n\nexport interface Options {\n lockTime?: number\n omitJob?: boolean\n}\n\nexport function loadMigrations(migrationServices: any[], options?: Options) {\n const migrations = getMigrationsFromServices(migrationServices)\n if (options?.omitJob) return migrations\n\n startWorkers({\n cooldownPeriod: 1000,\n lockTime: 1000 * 60 * 20, // 20 min\n workersCount: 1,\n pollInterval: 10 * 1000,\n jobs: {\n orionjsRunMigrations: defineJob({\n type: 'recurrent',\n runEvery: 30 * 1000,\n async resolve(_params, context) {\n const instance = getInstance(MigrationsService)\n await instance.runMigrations(migrations, context)\n },\n }),\n },\n })\n\n return migrations\n}\n","import {ExecutionContext} from '@orion-js/dogs'\nimport {getInstance} from '@orion-js/services'\nimport {Service} from '@orion-js/services'\n\nexport interface MigrationServiceOptions {\n name: string\n useMongoTransactions: false\n}\n\n// Define metadata storage using WeakMaps\nconst serviceMetadata = new WeakMap<any, {_serviceType: string; options: MigrationServiceOptions}>()\n\nexport function MigrationService(options: MigrationServiceOptions) {\n return (target: any, context: ClassDecoratorContext<any>) => {\n Service()(target, context)\n\n context.addInitializer(function (this) {\n serviceMetadata.set(this, {_serviceType: 'migrations', options: options})\n })\n }\n}\n\nexport type MigrationExecutable = {\n runMigration(context: ExecutionContext): Promise<void>\n} & MigrationServiceOptions\n\nexport function getMigrationsFromServices(services: any[]): MigrationExecutable[] {\n return services.map(service => {\n const instance = getInstance(service)\n const options = serviceMetadata.get(instance.constructor)\n if (!options._serviceType || options._serviceType !== 'migrations') {\n throw new Error(`Service ${service.name} is not a migration service`)\n }\n\n return {\n ...options.options,\n runMigration: async (context: ExecutionContext) => {\n const instance = getInstance(service) as any\n return await instance.runMigration(context)\n },\n }\n })\n}\n","import {Inject, Service} from '@orion-js/services'\nimport type {MigrationsRepo as MigrationsRepoType} from './Repo'\nimport {MigrationsRepo} from './Repo'\nimport {logger} from '@orion-js/logger'\nimport {MigrationExecutable} from './service'\nimport {ExecutionContext} from '@orion-js/dogs'\n\n@Service()\nexport class MigrationsService {\n @Inject(() => MigrationsRepo)\n private migrationsRepo: MigrationsRepoType\n\n async getNextMigration(migrationsList: MigrationExecutable[]) {\n const completedNames = await this.migrationsRepo.getCompletedMigrationNames()\n\n for (const migrationExecutable of migrationsList) {\n if (completedNames.includes(migrationExecutable.name)) continue\n return migrationExecutable\n }\n }\n\n async runMigrations(migrationsList: MigrationExecutable[], context: ExecutionContext) {\n const next = await this.getNextMigration(migrationsList)\n if (!next) return\n\n logger.info('[orionjs/migrations] Running migration...', {name: next.name})\n\n if (next.useMongoTransactions) {\n await this.runAsTransaction(next.runMigration, context)\n } else {\n await this.runMigration(next.runMigration, context)\n }\n\n logger.info('[orionjs/migrations] Migration executed correctly', {name: next.name})\n\n await this.migrationsRepo.saveCompletedMigration(next.name)\n\n await this.runMigrations(migrationsList, context)\n }\n\n async runMigration(\n func: (context: ExecutionContext) => Promise<void>,\n context: ExecutionContext,\n ) {\n try {\n await func(context)\n } catch (error) {\n logger.error('[orionjs/migrations] Error running migration', error)\n throw error\n }\n }\n\n async runAsTransaction(\n func: (context: ExecutionContext) => Promise<void>,\n context: ExecutionContext,\n ) {\n const {client} = this.migrationsRepo.collection.client\n const session = client.startSession()\n\n await session.withTransaction(async () => {\n try {\n await func(context)\n } catch (error) {\n logger.error('[orionjs/migrations] Error running migration, will abort transaction', error)\n throw error\n }\n })\n\n session.endSession()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAiB,eAAc;AAC/B,SAAyB,sBAAqB;AAIvC,IAAM,kBAAkB,eAAe,aAAa;AAAA,EACzD,KAAK;AAAA,IACH,MAAM,QAAQ,OAAO;AAAA,EACvB;AAAA,EACA,MAAM;AAAA,IACJ,MAAM;AAAA,EACR;AAAA,EACA,aAAa;AAAA,IACX,MAAM;AAAA,EACR;AACF,CAAC;;;ACfD,SAAQ,wBAAuB;AAE/B,SAAQ,eAAc;AAFtB;AAIA,8BAAC,QAAQ;AACF,IAAM,iBAAN,MAAqB;AAAA,EACnB,aAAa,iBAAiB;AAAA,IACnC,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,SAAS,CAAC;AAAA,EACZ,CAAC;AAAA,EAED,MAAM,6BAA6B;AACjC,UAAM,aAAa,MAAM,KAAK,WAAW,KAAK,EAAE,QAAQ;AACxD,WAAO,WAAW,IAAI,OAAK,EAAE,IAAI;AAAA,EACnC;AAAA,EAEA,MAAM,uBAAuB,MAAc;AACz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,QAAM,aAAa,0BAA0B,iBAAiB;AAC9D,MAAI,mCAAS,QAAS,QAAO;AAE7B,eAAa;AAAA,IACX,gBAAgB;AAAA,IAChB,UAAU,MAAO,KAAK;AAAA;AAAA,IACtB,cAAc;AAAA,IACd,cAAc,KAAK;AAAA,IACnB,MAAM;AAAA,MACJ,sBAAsB,UAAU;AAAA,QAC9B,MAAM;AAAA,QACN,UAAU,KAAK;AAAA,QACf,MAAM,QAAQ,SAAS,SAAS;AAC9B,gBAAM,WAAWE,aAAY,iBAAiB;AAC9C,gBAAM,SAAS,cAAc,YAAY,OAAO;AAAA,QAClD;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AAED,SAAO;AACT;","names":["Service","instance","getInstance","Service","_init","Service","getInstance"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orion-js/migrations",
3
- "version": "4.0.0-next.8",
3
+ "version": "4.0.0",
4
4
  "main": "./dist/index.cjs",
5
5
  "types": "./dist/index.d.ts",
6
6
  "files": [
@@ -9,12 +9,13 @@
9
9
  "author": "nicolaslopezj",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
- "@orion-js/dogs": "4.0.0-next.8",
13
- "@orion-js/logger": "4.0.0-next.7",
14
- "@orion-js/helpers": "4.0.0-next.8",
15
- "@orion-js/mongodb": "4.0.0-next.8",
16
- "@orion-js/typed-model": "4.0.0-next.8",
17
- "@orion-js/services": "4.0.0-next.8"
12
+ "@orion-js/dogs": "4.0.0",
13
+ "@orion-js/logger": "4.0.0",
14
+ "@orion-js/mongodb": "4.0.0",
15
+ "@orion-js/helpers": "4.0.0",
16
+ "@orion-js/typed-model": "4.0.0",
17
+ "@orion-js/services": "4.0.0",
18
+ "@orion-js/schema": "4.0.0"
18
19
  },
19
20
  "devDependencies": {
20
21
  "@types/node": "^18.0.0",