@medusajs/user 0.0.4-snapshot-20240531102054 → 0.0.4-snapshot-20240701122250

Sign up to get free protection for your applications and to get access to all the features.
package/dist/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
- import { moduleDefinition } from "./module-definition";
1
+ import { ModuleExports } from "@medusajs/types";
2
+ declare const moduleDefinition: ModuleExports;
2
3
  export default moduleDefinition;
package/dist/index.js CHANGED
@@ -1,4 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const module_definition_1 = require("./module-definition");
4
- exports.default = module_definition_1.moduleDefinition;
3
+ const _services_1 = require("./services");
4
+ const moduleDefinition = {
5
+ service: _services_1.UserModuleService,
6
+ };
7
+ exports.default = moduleDefinition;
@@ -1,8 +1,3 @@
1
1
  import { MapToConfig } from "@medusajs/utils";
2
- import { ModuleJoinerConfig } from "@medusajs/types";
3
- export declare const LinkableKeys: {
4
- user_id: string;
5
- invite_id: string;
6
- };
2
+ export declare const joinerConfig: Omit<import("@medusajs/types").ModuleJoinerConfig, "serviceName" | "primaryKeys" | "alias" | "linkableKeys"> & Required<Pick<import("@medusajs/types").ModuleJoinerConfig, "serviceName" | "primaryKeys" | "alias" | "linkableKeys">>;
7
3
  export declare const entityNameToLinkableKeysMap: MapToConfig;
8
- export declare const joinerConfig: ModuleJoinerConfig;
@@ -1,38 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.joinerConfig = exports.entityNameToLinkableKeysMap = exports.LinkableKeys = void 0;
4
- const _models_1 = require("./models");
5
- const modules_sdk_1 = require("@medusajs/modules-sdk");
6
- exports.LinkableKeys = {
7
- user_id: _models_1.User.name,
8
- invite_id: _models_1.Invite.name,
9
- };
10
- const entityLinkableKeysMap = {};
11
- Object.entries(exports.LinkableKeys).forEach(([key, value]) => {
12
- entityLinkableKeysMap[value] ??= [];
13
- entityLinkableKeysMap[value].push({
14
- mapTo: key,
15
- valueFrom: key.split("_").pop(),
16
- });
17
- });
18
- exports.entityNameToLinkableKeysMap = entityLinkableKeysMap;
19
- exports.joinerConfig = {
20
- serviceName: modules_sdk_1.Modules.USER,
21
- primaryKeys: ["id"],
22
- linkableKeys: exports.LinkableKeys,
23
- alias: [
24
- {
25
- name: ["user", "users"],
26
- args: {
27
- entity: _models_1.User.name,
28
- },
29
- },
30
- {
31
- name: ["invite", "invites"],
32
- args: {
33
- entity: _models_1.Invite.name,
34
- methodSuffix: "Invites",
35
- },
36
- },
37
- ],
38
- };
3
+ exports.entityNameToLinkableKeysMap = exports.joinerConfig = void 0;
4
+ const utils_1 = require("@medusajs/utils");
5
+ exports.joinerConfig = (0, utils_1.defineJoinerConfig)(utils_1.Modules.USER);
6
+ exports.entityNameToLinkableKeysMap = (0, utils_1.buildEntitiesNameToLinkableKeysMap)(exports.joinerConfig.linkableKeys);
@@ -1,2 +1 @@
1
1
  export { default as UserModuleService } from "./user-module";
2
- export { default as InviteService } from "./invite";
@@ -3,8 +3,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.InviteService = exports.UserModuleService = void 0;
6
+ exports.UserModuleService = void 0;
7
7
  var user_module_1 = require("./user-module");
8
8
  Object.defineProperty(exports, "UserModuleService", { enumerable: true, get: function () { return __importDefault(user_module_1).default; } });
9
- var invite_1 = require("./invite");
10
- Object.defineProperty(exports, "InviteService", { enumerable: true, get: function () { return __importDefault(invite_1).default; } });
@@ -1,36 +1,42 @@
1
- import { Context, DAL, InternalModuleDeclaration, ModuleJoinerConfig, UserTypes, ModulesSdkTypes, IEventBusModuleService } from "@medusajs/types";
2
- import { ModulesSdkUtils } from "@medusajs/utils";
1
+ import { Context, DAL, IEventBusModuleService, InternalModuleDeclaration, ModuleJoinerConfig, ModulesSdkTypes, UserTypes } from "@medusajs/types";
3
2
  import { Invite, User } from "../models";
4
- import InviteService from "./invite";
5
3
  type InjectedDependencies = {
6
4
  baseRepository: DAL.RepositoryService;
7
- userService: ModulesSdkTypes.InternalModuleService<any>;
8
- inviteService: InviteService<any>;
5
+ userService: ModulesSdkTypes.IMedusaInternalService<any>;
6
+ inviteService: ModulesSdkTypes.IMedusaInternalService<any>;
9
7
  eventBusModuleService: IEventBusModuleService;
10
8
  };
11
- declare const UserModuleService_base: new (container: InjectedDependencies) => ModulesSdkUtils.AbstractModuleService<InjectedDependencies, UserTypes.UserDTO, {
9
+ declare const UserModuleService_base: new (...args: any[]) => import("@medusajs/utils").AbstractModuleService<{
10
+ User: {
11
+ dto: UserTypes.UserDTO;
12
+ };
12
13
  Invite: {
13
14
  dto: UserTypes.InviteDTO;
14
15
  };
15
16
  }>;
16
- export default class UserModuleService<TUser extends User = User, TInvite extends Invite = Invite> extends UserModuleService_base implements UserTypes.IUserModuleService {
17
+ export default class UserModuleService extends UserModuleService_base implements UserTypes.IUserModuleService {
17
18
  protected readonly moduleDeclaration: InternalModuleDeclaration;
18
19
  __joinerConfig(): ModuleJoinerConfig;
19
20
  protected baseRepository_: DAL.RepositoryService;
20
- protected readonly userService_: ModulesSdkTypes.InternalModuleService<TUser>;
21
- protected readonly inviteService_: InviteService<TInvite>;
21
+ protected readonly userService_: ModulesSdkTypes.IMedusaInternalService<User>;
22
+ protected readonly inviteService_: ModulesSdkTypes.IMedusaInternalService<Invite>;
23
+ protected readonly config: {
24
+ jwtSecret: string;
25
+ expiresIn: number;
26
+ };
22
27
  constructor({ userService, inviteService, baseRepository }: InjectedDependencies, moduleDeclaration: InternalModuleDeclaration);
23
28
  validateInviteToken(token: string, sharedContext?: Context): Promise<UserTypes.InviteDTO>;
24
29
  refreshInviteTokens(inviteIds: string[], sharedContext?: Context): Promise<UserTypes.InviteDTO[]>;
25
- refreshInviteTokens_(inviteIds: string[], sharedContext?: Context): Promise<TInvite[]>;
26
- create(data: UserTypes.CreateUserDTO[], sharedContext?: Context): Promise<UserTypes.UserDTO[]>;
27
- create(data: UserTypes.CreateUserDTO, sharedContext?: Context): Promise<UserTypes.UserDTO>;
28
- update(data: UserTypes.UpdateUserDTO[], sharedContext?: Context): Promise<UserTypes.UserDTO[]>;
29
- update(data: UserTypes.UpdateUserDTO, sharedContext?: Context): Promise<UserTypes.UserDTO>;
30
+ refreshInviteTokens_(inviteIds: string[], sharedContext?: Context): Promise<Invite[]>;
31
+ createUsers(data: UserTypes.CreateUserDTO[], sharedContext?: Context): Promise<UserTypes.UserDTO[]>;
32
+ createUsers(data: UserTypes.CreateUserDTO, sharedContext?: Context): Promise<UserTypes.UserDTO>;
33
+ updateUsers(data: UserTypes.UpdateUserDTO[], sharedContext?: Context): Promise<UserTypes.UserDTO[]>;
34
+ updateUsers(data: UserTypes.UpdateUserDTO, sharedContext?: Context): Promise<UserTypes.UserDTO>;
30
35
  createInvites(data: UserTypes.CreateInviteDTO[], sharedContext?: Context): Promise<UserTypes.InviteDTO[]>;
31
36
  createInvites(data: UserTypes.CreateInviteDTO, sharedContext?: Context): Promise<UserTypes.InviteDTO>;
32
37
  private createInvites_;
33
38
  updateInvites(data: UserTypes.UpdateInviteDTO[], sharedContext?: Context): Promise<UserTypes.InviteDTO[]>;
34
39
  updateInvites(data: UserTypes.UpdateInviteDTO, sharedContext?: Context): Promise<UserTypes.InviteDTO>;
40
+ private generateToken;
35
41
  }
36
42
  export {};
@@ -11,12 +11,18 @@ var __metadata = (this && this.__metadata) || function (k, v) {
11
11
  var __param = (this && this.__param) || function (paramIndex, decorator) {
12
12
  return function (target, key) { decorator(target, key, paramIndex); }
13
13
  };
14
+ var __importDefault = (this && this.__importDefault) || function (mod) {
15
+ return (mod && mod.__esModule) ? mod : { "default": mod };
16
+ };
14
17
  Object.defineProperty(exports, "__esModule", { value: true });
15
18
  const utils_1 = require("@medusajs/utils");
19
+ const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
16
20
  const joiner_config_1 = require("../joiner-config");
21
+ const node_crypto_1 = __importDefault(require("node:crypto"));
17
22
  const _models_1 = require("../models");
18
- const generateMethodForModels = [_models_1.Invite];
19
- class UserModuleService extends utils_1.ModulesSdkUtils.abstractModuleServiceFactory(_models_1.User, generateMethodForModels, joiner_config_1.entityNameToLinkableKeysMap) {
23
+ // 1 day
24
+ const DEFAULT_VALID_INVITE_DURATION = 60 * 60 * 24 * 1000;
25
+ class UserModuleService extends (0, utils_1.MedusaService)({ User: _models_1.User, Invite: _models_1.Invite }, joiner_config_1.entityNameToLinkableKeysMap) {
20
26
  __joinerConfig() {
21
27
  return joiner_config_1.joinerConfig;
22
28
  }
@@ -26,10 +32,23 @@ class UserModuleService extends utils_1.ModulesSdkUtils.abstractModuleServiceFac
26
32
  this.moduleDeclaration = moduleDeclaration;
27
33
  this.baseRepository_ = baseRepository;
28
34
  this.userService_ = userService;
29
- this.inviteService_ = inviteService.withModuleOptions(this.moduleDeclaration);
35
+ this.inviteService_ = inviteService;
36
+ this.config = {
37
+ jwtSecret: moduleDeclaration["jwt_secret"],
38
+ expiresIn: parseInt(moduleDeclaration["valid_duration"]) ||
39
+ DEFAULT_VALID_INVITE_DURATION,
40
+ };
41
+ if (!this.config.jwtSecret) {
42
+ throw new utils_1.MedusaError(utils_1.MedusaError.Types.INVALID_DATA, "No jwt_secret was provided in the UserModule's options. Please add one.");
43
+ }
30
44
  }
31
45
  async validateInviteToken(token, sharedContext = {}) {
32
- const invite = await this.inviteService_.validateInviteToken(token, sharedContext);
46
+ const jwtSecret = this.moduleDeclaration["jwt_secret"];
47
+ const decoded = jsonwebtoken_1.default.verify(token, jwtSecret, { complete: true });
48
+ const invite = await this.inviteService_.retrieve(decoded.payload.id, {}, sharedContext);
49
+ if (invite.expires_at < new Date()) {
50
+ throw new utils_1.MedusaError(utils_1.MedusaError.Types.INVALID_DATA, "The invite has expired");
51
+ }
33
52
  return await this.baseRepository_.serialize(invite, {
34
53
  populate: true,
35
54
  });
@@ -37,12 +56,11 @@ class UserModuleService extends utils_1.ModulesSdkUtils.abstractModuleServiceFac
37
56
  async refreshInviteTokens(inviteIds, sharedContext = {}) {
38
57
  const invites = await this.refreshInviteTokens_(inviteIds, sharedContext);
39
58
  sharedContext.messageAggregator?.saveRawMessageData(invites.map((invite) => ({
40
- eventName: utils_1.UserEvents.invite_token_generated,
41
- metadata: {
42
- service: this.constructor.name,
43
- action: "token_generated",
44
- object: "invite",
45
- },
59
+ eventName: utils_1.UserEvents.INVITE_TOKEN_GENERATED,
60
+ source: this.constructor.name,
61
+ action: "token_generated",
62
+ object: "invite",
63
+ context: sharedContext,
46
64
  data: { id: invite.id },
47
65
  })));
48
66
  return await this.baseRepository_.serialize(invites, {
@@ -50,38 +68,50 @@ class UserModuleService extends utils_1.ModulesSdkUtils.abstractModuleServiceFac
50
68
  });
51
69
  }
52
70
  async refreshInviteTokens_(inviteIds, sharedContext = {}) {
53
- return await this.inviteService_.refreshInviteTokens(inviteIds, sharedContext);
71
+ const [invites, count] = await this.inviteService_.listAndCount({ id: inviteIds }, {}, sharedContext);
72
+ if (count !== inviteIds.length) {
73
+ const missing = (0, utils_1.arrayDifference)(inviteIds, invites.map((invite) => invite.id));
74
+ if (missing.length > 0) {
75
+ throw new utils_1.MedusaError(utils_1.MedusaError.Types.INVALID_DATA, `The following invites do not exist: ${missing.join(", ")}`);
76
+ }
77
+ }
78
+ const updates = invites.map((invite) => {
79
+ return {
80
+ id: invite.id,
81
+ expires_at: new Date().setMilliseconds(new Date().getMilliseconds() + this.config.expiresIn),
82
+ token: this.generateToken({ id: invite.id }),
83
+ };
84
+ });
85
+ return await this.inviteService_.update(updates, sharedContext);
54
86
  }
55
- async create(data, sharedContext = {}) {
87
+ async createUsers(data, sharedContext = {}) {
56
88
  const input = Array.isArray(data) ? data : [data];
57
89
  const users = await this.userService_.create(input, sharedContext);
58
90
  const serializedUsers = await this.baseRepository_.serialize(users, {
59
91
  populate: true,
60
92
  });
61
93
  sharedContext.messageAggregator?.saveRawMessageData(users.map((user) => ({
62
- eventName: utils_1.UserEvents.created,
63
- metadata: {
64
- service: this.constructor.name,
65
- action: utils_1.CommonEvents.CREATED,
66
- object: "user",
67
- },
94
+ eventName: utils_1.UserEvents.USER_CREATED,
95
+ source: this.constructor.name,
96
+ action: utils_1.CommonEvents.CREATED,
97
+ object: "user",
98
+ context: sharedContext,
68
99
  data: { id: user.id },
69
100
  })));
70
101
  return Array.isArray(data) ? serializedUsers : serializedUsers[0];
71
102
  }
72
- async update(data, sharedContext = {}) {
103
+ async updateUsers(data, sharedContext = {}) {
73
104
  const input = Array.isArray(data) ? data : [data];
74
105
  const updatedUsers = await this.userService_.update(input, sharedContext);
75
106
  const serializedUsers = await this.baseRepository_.serialize(updatedUsers, {
76
107
  populate: true,
77
108
  });
78
109
  sharedContext.messageAggregator?.saveRawMessageData(updatedUsers.map((user) => ({
79
- eventName: utils_1.UserEvents.updated,
80
- metadata: {
81
- service: this.constructor.name,
82
- action: utils_1.CommonEvents.UPDATED,
83
- object: "user",
84
- },
110
+ eventName: utils_1.UserEvents.USER_UPDATED,
111
+ source: this.constructor.name,
112
+ action: utils_1.CommonEvents.UPDATED,
113
+ object: "user",
114
+ context: sharedContext,
85
115
  data: { id: user.id },
86
116
  })));
87
117
  return Array.isArray(data) ? serializedUsers : serializedUsers[0];
@@ -93,21 +123,19 @@ class UserModuleService extends utils_1.ModulesSdkUtils.abstractModuleServiceFac
93
123
  populate: true,
94
124
  });
95
125
  sharedContext.messageAggregator?.saveRawMessageData(invites.map((invite) => ({
96
- eventName: utils_1.UserEvents.invite_created,
97
- metadata: {
98
- service: this.constructor.name,
99
- action: utils_1.CommonEvents.CREATED,
100
- object: "invite",
101
- },
126
+ eventName: utils_1.UserEvents.INVITE_CREATED,
127
+ source: this.constructor.name,
128
+ action: utils_1.CommonEvents.CREATED,
129
+ object: "invite",
130
+ context: sharedContext,
102
131
  data: { id: invite.id },
103
132
  })));
104
133
  sharedContext.messageAggregator?.saveRawMessageData(invites.map((invite) => ({
105
- eventName: utils_1.UserEvents.invite_token_generated,
106
- metadata: {
107
- service: this.constructor.name,
108
- action: "token_generated",
109
- object: "invite",
110
- },
134
+ eventName: utils_1.UserEvents.INVITE_TOKEN_GENERATED,
135
+ source: this.constructor.name,
136
+ action: "token_generated",
137
+ object: "invite",
138
+ context: sharedContext,
111
139
  data: { id: invite.id },
112
140
  })));
113
141
  return Array.isArray(data) ? serializedInvites : serializedInvites[0];
@@ -120,7 +148,15 @@ class UserModuleService extends utils_1.ModulesSdkUtils.abstractModuleServiceFac
120
148
  token: "placeholder",
121
149
  };
122
150
  });
123
- return await this.inviteService_.create(toCreate, sharedContext);
151
+ const created = await this.inviteService_.create(toCreate, sharedContext);
152
+ const updates = created.map((invite) => {
153
+ return {
154
+ id: invite.id,
155
+ expires_at: new Date().setMilliseconds(new Date().getMilliseconds() + this.config.expiresIn),
156
+ token: this.generateToken({ id: invite.id }),
157
+ };
158
+ });
159
+ return await this.inviteService_.update(updates, sharedContext);
124
160
  }
125
161
  async updateInvites(data, sharedContext = {}) {
126
162
  const input = Array.isArray(data) ? data : [data];
@@ -129,16 +165,22 @@ class UserModuleService extends utils_1.ModulesSdkUtils.abstractModuleServiceFac
129
165
  populate: true,
130
166
  });
131
167
  sharedContext.messageAggregator?.saveRawMessageData(serializedInvites.map((invite) => ({
132
- eventName: utils_1.UserEvents.invite_updated,
133
- metadata: {
134
- service: this.constructor.name,
135
- action: utils_1.CommonEvents.UPDATED,
136
- object: "invite",
137
- },
168
+ eventName: utils_1.UserEvents.INVITE_UPDATED,
169
+ source: this.constructor.name,
170
+ action: utils_1.CommonEvents.UPDATED,
171
+ object: "invite",
172
+ context: sharedContext,
138
173
  data: { id: invite.id },
139
174
  })));
140
175
  return Array.isArray(data) ? serializedInvites : serializedInvites[0];
141
176
  }
177
+ generateToken(data) {
178
+ const jwtSecret = this.moduleDeclaration["jwt_secret"];
179
+ return jsonwebtoken_1.default.sign(data, jwtSecret, {
180
+ jwtid: node_crypto_1.default.randomUUID(),
181
+ expiresIn: this.config.expiresIn,
182
+ });
183
+ }
142
184
  }
143
185
  exports.default = UserModuleService;
144
186
  __decorate([
@@ -170,7 +212,7 @@ __decorate([
170
212
  __metadata("design:type", Function),
171
213
  __metadata("design:paramtypes", [Object, Object]),
172
214
  __metadata("design:returntype", Promise)
173
- ], UserModuleService.prototype, "create", null);
215
+ ], UserModuleService.prototype, "createUsers", null);
174
216
  __decorate([
175
217
  (0, utils_1.InjectManager)("baseRepository_"),
176
218
  (0, utils_1.EmitEvents)(),
@@ -178,7 +220,7 @@ __decorate([
178
220
  __metadata("design:type", Function),
179
221
  __metadata("design:paramtypes", [Object, Object]),
180
222
  __metadata("design:returntype", Promise)
181
- ], UserModuleService.prototype, "update", null);
223
+ ], UserModuleService.prototype, "updateUsers", null);
182
224
  __decorate([
183
225
  (0, utils_1.InjectManager)("baseRepository_"),
184
226
  (0, utils_1.EmitEvents)(),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@medusajs/user",
3
- "version": "0.0.4-snapshot-20240531102054",
3
+ "version": "0.0.4-snapshot-20240701122250",
4
4
  "description": "Medusa Users module",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -8,10 +8,7 @@
8
8
  "dist"
9
9
  ],
10
10
  "engines": {
11
- "node": ">=16"
12
- },
13
- "bin": {
14
- "medusa-user-seed": "dist/scripts/bin/run-seed.js"
11
+ "node": ">=20"
15
12
  },
16
13
  "repository": {
17
14
  "type": "git",
@@ -37,20 +34,21 @@
37
34
  "orm:cache:clear": " MIKRO_ORM_CLI=./mikro-orm.config.dev.ts mikro-orm cache:clear"
38
35
  },
39
36
  "devDependencies": {
40
- "@medusajs/types": "1.12.0-snapshot-20240531102054",
37
+ "@medusajs/types": "1.12.0-snapshot-20240701122250",
41
38
  "@mikro-orm/cli": "5.9.7",
39
+ "@swc/core": "^1.5.29",
40
+ "@swc/jest": "^0.2.36",
42
41
  "cross-env": "^5.2.1",
43
- "jest": "^29.6.3",
44
- "medusa-test-utils": "1.1.45-snapshot-20240531102054",
42
+ "jest": "^29.7.0",
43
+ "medusa-test-utils": "1.1.45-snapshot-20240701122250",
45
44
  "rimraf": "^3.0.2",
46
- "ts-jest": "^29.1.1",
47
45
  "ts-node": "^10.9.1",
48
46
  "tsc-alias": "^1.8.6",
49
47
  "typescript": "^5.1.6"
50
48
  },
51
49
  "dependencies": {
52
- "@medusajs/modules-sdk": "1.13.0-snapshot-20240531102054",
53
- "@medusajs/utils": "1.12.0-snapshot-20240531102054",
50
+ "@medusajs/modules-sdk": "1.13.0-snapshot-20240701122250",
51
+ "@medusajs/utils": "1.12.0-snapshot-20240701122250",
54
52
  "@mikro-orm/core": "5.9.7",
55
53
  "@mikro-orm/migrations": "5.9.7",
56
54
  "@mikro-orm/postgresql": "5.9.7",
@@ -1,2 +0,0 @@
1
- import { ModuleExports } from "@medusajs/types";
2
- export declare const moduleDefinition: ModuleExports;
@@ -1,8 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.moduleDefinition = void 0;
4
- const _services_1 = require("./services");
5
- const service = _services_1.UserModuleService;
6
- exports.moduleDefinition = {
7
- service,
8
- };
@@ -1 +0,0 @@
1
- export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils";
@@ -1,5 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.BaseRepository = void 0;
4
- var utils_1 = require("@medusajs/utils");
5
- Object.defineProperty(exports, "BaseRepository", { enumerable: true, get: function () { return utils_1.MikroOrmBaseRepository; } });
@@ -1,3 +0,0 @@
1
- #!/usr/bin/env node
2
- declare const _default: Promise<void>;
3
- export default _default;
@@ -1,38 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
- if (k2 === undefined) k2 = k;
5
- var desc = Object.getOwnPropertyDescriptor(m, k);
6
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
- desc = { enumerable: true, get: function() { return m[k]; } };
8
- }
9
- Object.defineProperty(o, k2, desc);
10
- }) : (function(o, m, k, k2) {
11
- if (k2 === undefined) k2 = k;
12
- o[k2] = m[k];
13
- }));
14
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
- Object.defineProperty(o, "default", { enumerable: true, value: v });
16
- }) : function(o, v) {
17
- o["default"] = v;
18
- });
19
- var __importStar = (this && this.__importStar) || function (mod) {
20
- if (mod && mod.__esModule) return mod;
21
- var result = {};
22
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
23
- __setModuleDefault(result, mod);
24
- return result;
25
- };
26
- Object.defineProperty(exports, "__esModule", { value: true });
27
- const os_1 = require("os");
28
- const seed_1 = require("../seed");
29
- const args = process.argv;
30
- const path = args.pop();
31
- exports.default = (async () => {
32
- const { config } = await Promise.resolve().then(() => __importStar(require("dotenv")));
33
- config();
34
- if (!path) {
35
- throw new Error(`filePath is required.${os_1.EOL}Example: medusa-user-seed <filePath>`);
36
- }
37
- await (0, seed_1.run)({ path });
38
- })();
@@ -1,4 +0,0 @@
1
- import { LoaderOptions, ModulesSdkTypes } from "@medusajs/types";
2
- export declare function run({ options, logger, path, }: Partial<Pick<LoaderOptions<ModulesSdkTypes.ModuleServiceInitializeOptions>, "options" | "logger">> & {
3
- path: string;
4
- }): Promise<void>;
@@ -1,54 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.run = void 0;
27
- const UserModels = __importStar(require("../models"));
28
- const utils_1 = require("@medusajs/utils");
29
- const os_1 = require("os");
30
- const modules_sdk_1 = require("@medusajs/modules-sdk");
31
- const path_1 = require("path");
32
- async function run({ options, logger, path, }) {
33
- logger ??= console;
34
- logger.info(`Loading seed data from ${path}...`);
35
- const { userData } = await Promise.resolve(`${(0, path_1.resolve)(process.cwd(), path)}`).then(s => __importStar(require(s))).catch((e) => {
36
- logger?.error(`Failed to load seed data from ${path}. Please, provide a relative path and check that you export the following: userData.${os_1.EOL}${e}`);
37
- throw e;
38
- });
39
- const dbData = utils_1.ModulesSdkUtils.loadDatabaseConfig(modules_sdk_1.Modules.USER, options);
40
- const entities = Object.values(UserModels);
41
- const pathToMigrations = __dirname + "/../migrations";
42
- const orm = await utils_1.DALUtils.mikroOrmCreateConnection(dbData, entities, pathToMigrations);
43
- const manager = orm.em.fork();
44
- try {
45
- logger.info("Seeding user data..");
46
- // TODO: implement user seed data
47
- // await createUsers(manager, usersData)
48
- }
49
- catch (e) {
50
- logger.error(`Failed to insert the seed data in the PostgreSQL database ${dbData.clientUrl}.${os_1.EOL}${e}`);
51
- }
52
- await orm.close(true);
53
- }
54
- exports.run = run;
@@ -1,25 +0,0 @@
1
- import { Context, DAL } from "@medusajs/types";
2
- import { Invite } from "../models";
3
- import { InviteServiceTypes } from "../types";
4
- type InjectedDependencies = {
5
- inviteRepository: DAL.RepositoryService;
6
- };
7
- declare const InviteService_base: new <TEntity_1 extends object = any>(container: InjectedDependencies) => import("@medusajs/types").InternalModuleService<TEntity_1, InjectedDependencies>;
8
- export default class InviteService<TEntity extends Invite = Invite> extends InviteService_base<TEntity> {
9
- protected readonly inviteRepository_: DAL.RepositoryService<TEntity>;
10
- protected options_: {
11
- jwt_secret: string;
12
- valid_duration: number;
13
- } | undefined;
14
- constructor(container: InjectedDependencies);
15
- withModuleOptions(options: any): InviteService<TEntity>;
16
- private getOption;
17
- create(data: InviteServiceTypes.CreateInviteDTO, context?: Context): Promise<TEntity>;
18
- create(data: InviteServiceTypes.CreateInviteDTO[], context?: Context): Promise<TEntity[]>;
19
- refreshInviteTokens(inviteIds: string[], context?: Context): Promise<TEntity[]>;
20
- validateInviteToken(token: string, context?: Context): Promise<TEntity>;
21
- private generateToken;
22
- private getValidDuration;
23
- private validateToken;
24
- }
25
- export {};
@@ -1,140 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
19
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
20
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
22
- return c > 3 && r && Object.defineProperty(target, key, r), r;
23
- };
24
- var __importStar = (this && this.__importStar) || function (mod) {
25
- if (mod && mod.__esModule) return mod;
26
- var result = {};
27
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
28
- __setModuleDefault(result, mod);
29
- return result;
30
- };
31
- var __metadata = (this && this.__metadata) || function (k, v) {
32
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
33
- };
34
- var __importDefault = (this && this.__importDefault) || function (mod) {
35
- return (mod && mod.__esModule) ? mod : { "default": mod };
36
- };
37
- Object.defineProperty(exports, "__esModule", { value: true });
38
- const crypto = __importStar(require("crypto"));
39
- const utils_1 = require("@medusajs/utils");
40
- const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
41
- const _models_1 = require("../models");
42
- // 1 day
43
- const DEFAULT_VALID_INVITE_DURATION = 60 * 60 * 24 * 1000;
44
- class InviteService extends utils_1.ModulesSdkUtils.internalModuleServiceFactory(_models_1.Invite) {
45
- constructor(container) {
46
- super(container);
47
- this.inviteRepository_ = container.inviteRepository;
48
- }
49
- withModuleOptions(options) {
50
- const service = new InviteService(this.__container__);
51
- service.options_ = options;
52
- return service;
53
- }
54
- getOption(key) {
55
- if (!this.options_) {
56
- throw new utils_1.MedusaError(utils_1.MedusaError.Types.UNEXPECTED_STATE, `Options are not configured for InviteService, call "withModuleOptions" and provide options`);
57
- }
58
- return this.options_[key];
59
- }
60
- async create(data, context = {}) {
61
- const data_ = Array.isArray(data) ? data : [data];
62
- const invites = await super.create(data_, context);
63
- const expiresIn = this.getValidDuration();
64
- const updates = invites.map((invite) => {
65
- return {
66
- id: invite.id,
67
- expires_at: new Date().setMilliseconds(new Date().getMilliseconds() + expiresIn),
68
- token: this.generateToken({ id: invite.id }),
69
- };
70
- });
71
- return await super.update(updates, context);
72
- }
73
- async refreshInviteTokens(inviteIds, context = {}) {
74
- const [invites, count] = await super.listAndCount({ id: inviteIds }, {}, context);
75
- if (count !== inviteIds.length) {
76
- const missing = (0, utils_1.arrayDifference)(inviteIds, invites.map((invite) => invite.id));
77
- if (missing.length > 0) {
78
- throw new utils_1.MedusaError(utils_1.MedusaError.Types.INVALID_DATA, `The following invites do not exist: ${missing.join(", ")}`);
79
- }
80
- }
81
- const expiresIn = this.getValidDuration();
82
- const updates = invites.map((invite) => {
83
- return {
84
- id: invite.id,
85
- expires_at: new Date().setMilliseconds(new Date().getMilliseconds() + expiresIn),
86
- token: this.generateToken({ id: invite.id }),
87
- };
88
- });
89
- return await super.update(updates, context);
90
- }
91
- async validateInviteToken(token, context) {
92
- const decoded = this.validateToken(token);
93
- const invite = await super.retrieve(decoded.payload.id, {}, context);
94
- if (invite.expires_at < new Date()) {
95
- throw new utils_1.MedusaError(utils_1.MedusaError.Types.INVALID_DATA, "The invite has expired");
96
- }
97
- return invite;
98
- }
99
- generateToken(data) {
100
- const jwtSecret = this.getOption("jwt_secret");
101
- const expiresIn = this.getValidDuration() / 1000;
102
- if (!jwtSecret) {
103
- throw new utils_1.MedusaError(utils_1.MedusaError.Types.INVALID_DATA, "No jwt_secret was provided in the UserModule's options. Please add one.");
104
- }
105
- return jsonwebtoken_1.default.sign(data, jwtSecret, {
106
- jwtid: crypto.randomUUID(),
107
- expiresIn,
108
- });
109
- }
110
- getValidDuration() {
111
- return (parseInt(this.getOption("valid_duration")) ||
112
- DEFAULT_VALID_INVITE_DURATION);
113
- }
114
- validateToken(data) {
115
- const jwtSecret = this.getOption("jwt_secret");
116
- if (!jwtSecret) {
117
- throw new utils_1.MedusaError(utils_1.MedusaError.Types.INVALID_DATA, "No jwt_secret was provided in the UserModule's options. Please add one.");
118
- }
119
- return jsonwebtoken_1.default.verify(data, jwtSecret, { complete: true });
120
- }
121
- }
122
- exports.default = InviteService;
123
- __decorate([
124
- (0, utils_1.InjectTransactionManager)("inviteRepository_"),
125
- __metadata("design:type", Function),
126
- __metadata("design:paramtypes", [Object, Object]),
127
- __metadata("design:returntype", Promise)
128
- ], InviteService.prototype, "create", null);
129
- __decorate([
130
- (0, utils_1.InjectTransactionManager)("inviteRepository_"),
131
- __metadata("design:type", Function),
132
- __metadata("design:paramtypes", [Array, Object]),
133
- __metadata("design:returntype", Promise)
134
- ], InviteService.prototype, "refreshInviteTokens", null);
135
- __decorate([
136
- (0, utils_1.InjectTransactionManager)("inviteRepository_"),
137
- __metadata("design:type", Function),
138
- __metadata("design:paramtypes", [String, Object]),
139
- __metadata("design:returntype", Promise)
140
- ], InviteService.prototype, "validateInviteToken", null);