speedly 1.0.0 → 1.1.1

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.
Files changed (58) hide show
  1. package/README.md +280 -0
  2. package/dist/cjs/auth/auth.js +86 -0
  3. package/dist/cjs/db/db.d.ts +181 -0
  4. package/dist/cjs/db/db.js +485 -0
  5. package/dist/cjs/index.d.ts +5 -0
  6. package/dist/cjs/index.js +44 -0
  7. package/dist/cjs/model/translation.d.ts +59 -0
  8. package/dist/cjs/model/translation.js +13 -0
  9. package/dist/{modules/auth.d.ts → cjs/uploader/uploader.d.ts} +1 -1
  10. package/dist/cjs/uploader/uploader.js +150 -0
  11. package/dist/cjs/util/getConfig.d.ts +4 -0
  12. package/dist/cjs/util/getConfig.js +21 -0
  13. package/dist/cjs/util/strToObj.d.ts +2 -0
  14. package/dist/cjs/util/strToObj.js +9 -0
  15. package/dist/cjs/util/translator.d.ts +2 -0
  16. package/dist/cjs/util/translator.js +67 -0
  17. package/dist/cjs/validator/validator.d.ts +9 -0
  18. package/dist/cjs/validator/validator.js +32 -0
  19. package/dist/esm/auth/auth.js +86 -0
  20. package/dist/esm/db/db.d.ts +181 -0
  21. package/dist/esm/db/db.js +485 -0
  22. package/dist/esm/index.d.ts +5 -0
  23. package/dist/esm/index.js +44 -0
  24. package/dist/esm/model/translation.d.ts +59 -0
  25. package/dist/esm/model/translation.js +13 -0
  26. package/dist/{modules/db.d.ts → esm/uploader/uploader.d.ts} +1 -1
  27. package/dist/esm/uploader/uploader.js +150 -0
  28. package/dist/esm/util/getConfig.d.ts +4 -0
  29. package/dist/esm/util/getConfig.js +21 -0
  30. package/dist/esm/util/strToObj.d.ts +2 -0
  31. package/dist/esm/util/strToObj.js +9 -0
  32. package/dist/esm/util/translator.d.ts +2 -0
  33. package/dist/esm/util/translator.js +67 -0
  34. package/dist/esm/validator/validator.d.ts +9 -0
  35. package/dist/esm/validator/validator.js +32 -0
  36. package/package.json +28 -15
  37. package/dist/index.d.ts +0 -0
  38. package/dist/index.js +0 -1
  39. package/dist/modules/auth.js +0 -68
  40. package/dist/modules/db/aggregation.d.ts +0 -0
  41. package/dist/modules/db/aggregation.js +0 -1
  42. package/dist/modules/db/aggregation.types.d.ts +0 -56
  43. package/dist/modules/db/aggregation.types.js +0 -2
  44. package/dist/modules/db/db.d.ts +0 -0
  45. package/dist/modules/db/db.js +0 -1
  46. package/dist/modules/db/db.type.js +0 -2
  47. package/dist/modules/db.js +0 -228
  48. package/dist/modules/types/db.d.ts +0 -38
  49. package/dist/modules/types/db.js +0 -1
  50. package/dist/modules/uploader.js +0 -57
  51. package/dist/modules/utils.d.ts +0 -0
  52. package/dist/modules/utils.js +0 -1
  53. package/dist/modules/validator.d.ts +0 -1
  54. package/dist/modules/validator.js +0 -47
  55. package/dist/utils/strToObj.d.ts +0 -0
  56. package/dist/utils/strToObj.js +0 -8
  57. /package/dist/{modules/db/db.type.d.ts → cjs/auth/auth.d.ts} +0 -0
  58. /package/dist/{modules/uploader.d.ts → esm/auth/auth.d.ts} +0 -0
@@ -0,0 +1,150 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const path_1 = __importDefault(require("path"));
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const multer_1 = __importDefault(require("multer"));
9
+ const mongoose_1 = __importDefault(require("mongoose"));
10
+ const getConfig = require("../util/getConfig");
11
+ const relativePath = '../../../public';
12
+ let configs = {
13
+ saveInDb: false,
14
+ prefix: "",
15
+ limit: 5,
16
+ format: /png|jpg|webp|jpeg/i,
17
+ ...getConfig("uploader")
18
+ };
19
+ console.log('uploader', 15, configs);
20
+ module.exports = (destination = "/image", config = configs) => {
21
+ let dest;
22
+ try {
23
+ Object.entries(config).forEach(([key, val]) => {
24
+ configs[key] = val;
25
+ });
26
+ const storage = multer_1.default.diskStorage({
27
+ destination: function (req, file, cb) {
28
+ try {
29
+ dest = typeof destination === "function"
30
+ ? destination(req, file)
31
+ : destination;
32
+ const splitPath = dest.split("/");
33
+ let currentPath = path_1.default.join(__dirname, relativePath);
34
+ splitPath.forEach(folder => {
35
+ currentPath = path_1.default.join(currentPath, folder);
36
+ console.log('uploader', 39, currentPath, !fs_1.default.existsSync(currentPath));
37
+ if (!fs_1.default.existsSync(currentPath)) {
38
+ fs_1.default.mkdirSync(currentPath);
39
+ }
40
+ });
41
+ cb(null, path_1.default.join(__dirname, relativePath, dest));
42
+ }
43
+ catch (err) {
44
+ cb(err, "");
45
+ }
46
+ },
47
+ filename: function (req, file, cb) {
48
+ try {
49
+ const ext = path_1.default.extname(file.originalname);
50
+ if (!ext.slice(1).match(configs.format)) {
51
+ return cb(new Error("File format not acceptable"), '');
52
+ }
53
+ const originalName = Buffer.from(file.originalname, "latin1").toString("utf8");
54
+ const fileName = (configs.prefix ? configs.prefix + "-" : "") +
55
+ originalName.replace(/\.\w+$/, "") + ext;
56
+ const filePath = path_1.default.join(__dirname, relativePath, dest, fileName);
57
+ console.log('uploader', 65, filePath);
58
+ try {
59
+ fs_1.default.existsSync(filePath);
60
+ }
61
+ catch (error) {
62
+ console.log('uploader', 70, error);
63
+ }
64
+ if (fs_1.default.existsSync(filePath)) {
65
+ return cb(new Error("File already exists in the destination folder"), '');
66
+ }
67
+ cb(null, fileName);
68
+ }
69
+ catch (err) {
70
+ cb(err, '');
71
+ }
72
+ },
73
+ });
74
+ const uploader = (0, multer_1.default)({
75
+ storage,
76
+ limits: { fileSize: (configs.limit || 5) * 1024 * 1024 }, // MB
77
+ });
78
+ return {
79
+ single: (fieldName) => (req, res, next) => {
80
+ uploader.single(fieldName)(req, res, async (err) => {
81
+ if (err) {
82
+ console.log('uploader', 85, err);
83
+ return next({ status: 405, json: { message: err.message } });
84
+ }
85
+ if (req.file) {
86
+ if (configs.saveInDb) {
87
+ const db = mongoose_1.default.connection;
88
+ const collection = db.collection("media");
89
+ const duplicate = await collection.findOne({ alt: req.body.alt });
90
+ if (duplicate) {
91
+ fs_1.default.rmSync(req.file.path);
92
+ return res.status(405).json({ message: "alt is repetitive" });
93
+ }
94
+ const mediaDoc = await collection.insertOne({
95
+ type: req.file.mimetype.split("/")[0],
96
+ name: req.file.filename,
97
+ dirPath: dest + "/",
98
+ alt: req.body.alt,
99
+ desc: req.body.desc,
100
+ url: "/static/" + dest + "/" + req.file.filename,
101
+ });
102
+ console.log('uploader', 101, mediaDoc);
103
+ req.mediaId = mediaDoc.insertedId;
104
+ }
105
+ req.body[fieldName] = path_1.default
106
+ .join("/static", path_1.default.relative(path_1.default.join(__dirname, relativePath), req.file.path))
107
+ .replaceAll(/\\/g, "/");
108
+ }
109
+ next();
110
+ });
111
+ },
112
+ array: (fieldName, maxCount = Infinity) => (req, res, next) => {
113
+ uploader.array(fieldName, maxCount)(req, res, (err) => {
114
+ if (err)
115
+ return res.status(405).json({ message: err.message });
116
+ if (req.files && Array.isArray(req.files) && req.files.length) {
117
+ req.body[fieldName] = req.files.map(file => path_1.default
118
+ .join("/static", path_1.default.relative(path_1.default.join(__dirname, relativePath), file.path))
119
+ .replaceAll(/\\/g, "/"));
120
+ }
121
+ next();
122
+ });
123
+ },
124
+ fields: (fields) => (req, res, next) => {
125
+ uploader.fields(fields)(req, res, (err) => {
126
+ if (err)
127
+ return res.status(405).json({ message: err.message });
128
+ next();
129
+ });
130
+ },
131
+ any: () => (req, res, next) => {
132
+ uploader.any()(req, res, (err) => {
133
+ if (err)
134
+ return res.status(405).json({ message: err.message });
135
+ next();
136
+ });
137
+ },
138
+ none: () => (req, res, next) => {
139
+ uploader.none()(req, res, (err) => {
140
+ if (err)
141
+ return res.status(405).json({ message: err.message });
142
+ next();
143
+ });
144
+ },
145
+ };
146
+ }
147
+ catch (error) {
148
+ console.log("uploader init error", error);
149
+ }
150
+ };
@@ -0,0 +1,4 @@
1
+ declare const _default: (configField: string) => {
2
+ [key: string]: unknown;
3
+ };
4
+ export default _default;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const fs_1 = __importDefault(require("fs"));
7
+ // const { path } = require('../../app');
8
+ exports.default = (configField) => {
9
+ const stackPath = new Error().stack?.split('\n')[2].trim().match(/\(.+\)/)?.[0].replace(/([\(\)]|\:\d+\:\d+)/g, '');
10
+ for (let i = 1; i < 4; i++) {
11
+ const filePath = stackPath?.replace(/\\/g, '/').split('/').slice(0, -i).join('/') + '/speedly.config.js';
12
+ if (fs_1.default.existsSync(filePath)) {
13
+ const config = require(filePath);
14
+ if (config && config[configField]) {
15
+ return config[configField];
16
+ }
17
+ return {};
18
+ }
19
+ }
20
+ return {};
21
+ };
@@ -0,0 +1,2 @@
1
+ declare const _default: (value: string, falseValue?: number, splitValue?: string) => {};
2
+ export default _default;
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = (value, falseValue = -1, splitValue = ' ') => {
4
+ return value.split(splitValue).reduce((prev, curr) => {
5
+ if (curr[0] == '-')
6
+ return { ...prev, [curr.slice(1)]: falseValue };
7
+ return { ...prev, [curr]: 1 };
8
+ }, {});
9
+ };
@@ -0,0 +1,2 @@
1
+ declare const _default: (text?: string, lang?: string) => Promise<unknown>;
2
+ export default _default;
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const axios_1 = __importDefault(require("axios"));
7
+ const translation_1 = __importDefault(require("./../model/translation"));
8
+ const getConfig_1 = __importDefault(require("./getConfig"));
9
+ const configs = { ...(0, getConfig_1.default)('translate') };
10
+ async function firstSuccessful(promises) {
11
+ return new Promise((resolve, reject) => {
12
+ let rejections = 0;
13
+ const total = promises.length;
14
+ promises.forEach((p) => {
15
+ Promise.resolve(p)
16
+ .then(resolve)
17
+ .catch(() => {
18
+ rejections++;
19
+ if (rejections === total) {
20
+ reject(new Error("همه ترجمه‌ها شکست خوردند"));
21
+ }
22
+ });
23
+ });
24
+ });
25
+ }
26
+ exports.default = async (text = "unspecified text", lang = "fa") => {
27
+ const formattedText = text
28
+ .replaceAll(/[\-\_]/g, " ")
29
+ .replaceAll(/[A-Z]/g, " $&");
30
+ const translationDoc = await translation_1.default.findOne({ text: formattedText, lang });
31
+ if (translationDoc)
32
+ return translationDoc.translatedText;
33
+ const translationPromises = [];
34
+ translationPromises.push((async () => {
35
+ const res = await axios_1.default.get(`https://655.mtis.workers.dev/translate?text=${encodeURIComponent(formattedText)}&source_lang=en&target_lang=${lang}`, { timeout: 2000 });
36
+ if (!res.data?.response?.translated_text)
37
+ throw new Error("Translation failed");
38
+ return res.data.response.translated_text;
39
+ })());
40
+ if (configs.one_api_token)
41
+ translationPromises.push((async () => {
42
+ const res = await axios_1.default.post("https://api.one-api.ir/translate/v1/microsoft", {
43
+ text: formattedText,
44
+ target: lang,
45
+ }, {
46
+ timeout: 2000,
47
+ headers: {
48
+ "one-api-token": configs.one_api_token
49
+ },
50
+ });
51
+ if (res.data.status === 200) {
52
+ return res.data.result;
53
+ }
54
+ else {
55
+ throw new Error(res.data.message);
56
+ }
57
+ })());
58
+ try {
59
+ const result = await firstSuccessful(translationPromises);
60
+ await translation_1.default.create({ text: formattedText, lang, translatedText: result });
61
+ return result;
62
+ }
63
+ catch (err) {
64
+ console.error("translator error:", err);
65
+ return formattedText;
66
+ }
67
+ };
@@ -0,0 +1,9 @@
1
+ import { RequestHandler } from "express";
2
+ import * as yup from "yup";
3
+ type ValidationSchema = {
4
+ body?: yup.AnyObjectSchema;
5
+ params?: yup.AnyObjectSchema;
6
+ query?: yup.AnyObjectSchema;
7
+ };
8
+ export declare const validator: <T extends ValidationSchema>(schemas: T) => RequestHandler;
9
+ export {};
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validator = void 0;
4
+ // این تابع validator generic هست
5
+ const validator = (schemas) => async (req, res, next) => {
6
+ try {
7
+ if (schemas.body) {
8
+ req.body = (await schemas.body.validate(req.body, {
9
+ stripUnknown: true,
10
+ }));
11
+ }
12
+ if (schemas.params) {
13
+ req.params = (await schemas.params.validate(req.params, {
14
+ stripUnknown: true,
15
+ }));
16
+ }
17
+ if (schemas.query) {
18
+ req.query = (await schemas.query.validate(req.query, {
19
+ stripUnknown: true,
20
+ }));
21
+ }
22
+ next();
23
+ }
24
+ catch (err) {
25
+ return next({
26
+ status: 405,
27
+ json: { message: err.message },
28
+ section: "validation",
29
+ });
30
+ }
31
+ };
32
+ exports.validator = validator;
package/package.json CHANGED
@@ -1,25 +1,38 @@
1
1
  {
2
2
  "name": "speedly",
3
- "version": "1.0.0",
4
- "main": "dist/index.js",
5
- "types": "dist/index.d.ts",
3
+ "version": "1.1.1",
4
+ "main": "dist/cjs/index.js",
5
+ "module": "dist/esm/index.js",
6
+ "types": "dist/esm/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "import": "./dist/esm/index.js",
10
+ "require": "./dist/cjs/index.js"
11
+ }
12
+ },
6
13
  "scripts": {
7
- "test": "echo \"Error: no test specified\" && exit 1",
8
- "build": "tsc"
14
+ "build": "npm run build:cjs && npm run build:esm",
15
+ "build:cjs": "tsc -p tsconfig.cjs.json",
16
+ "build:esm": "tsc -p tsconfig.esm.json",
17
+ "dev": "ts-node src/index.ts"
9
18
  },
10
- "keywords": ["mongodb", "aggregation", "builder", "fluent", "typescript"],
11
- "author": "Mahserin",
19
+ "author": "MAHSERIN",
12
20
  "license": "MIT",
13
- "description": "A powerful backend module that lets you build and run advanced MongoDB aggregation queries with blazing speed and ultimate simplicity.",
21
+ "description": "",
22
+ "devDependencies": {
23
+ "@types/express": "^5.0.3",
24
+ "@types/multer": "^2.0.0",
25
+ "@types/node": "^24.5.2",
26
+ "ts-node": "^10.9.2",
27
+ "typescript": "^5.9.2"
28
+ },
14
29
  "dependencies": {
15
- "@types/express": "^5.0.1",
16
- "@types/node": "^22.15.17",
30
+ "axios": "^1.11.0",
17
31
  "express": "^5.1.0",
18
32
  "jsonwebtoken": "^9.0.2",
19
- "typescript": "^5.8.3",
20
- "yup": "^1.6.1"
21
- },
22
- "devDependencies": {
23
- "@types/multer": "^1.4.12"
33
+ "mongoose": "^8.18.2",
34
+ "multer": "^2.0.2",
35
+ "translate": "^3.0.1",
36
+ "yup": "^1.7.1"
24
37
  }
25
38
  }
package/dist/index.d.ts DELETED
File without changes
package/dist/index.js DELETED
@@ -1 +0,0 @@
1
- "use strict";
@@ -1,68 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- const jwt = require('jsonwebtoken');
13
- const adminModel = require('./../models/admin');
14
- const auth = (config = { admin: { role: 'ADMIN' } }) => {
15
- let handlerState = {};
16
- const useAuth = (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
17
- var _a, _b, _c, _d, _e, _f, _g;
18
- console.log('auth 6 ', req.cookies);
19
- try {
20
- const nextFunc = (handlers, index = 0) => (errorMessage = '') => {
21
- if (!handlers.length || !handlers[index + 1])
22
- return next();
23
- if (errorMessage)
24
- return next(errorMessage);
25
- handlers[index + 1](req, res, nextFunc(handlers, index + 1));
26
- };
27
- if (!req.cookies.AT_SECRET) {
28
- if (!handlerState.user || !((_b = (_a = handlerState.user) === null || _a === void 0 ? void 0 : _a.handlers) === null || _b === void 0 ? void 0 : _b.length))
29
- return res.status(403).json({ message: 'you dont have access for this section' });
30
- handlerState.user.handlers[0](req, res, nextFunc(handlerState.user.handlers));
31
- }
32
- else {
33
- if (!handlerState.admin || !((_d = (_c = handlerState.admin) === null || _c === void 0 ? void 0 : _c.handlers) === null || _d === void 0 ? void 0 : _d.length)) {
34
- if (!handlerState.user || !((_f = (_e = handlerState.user) === null || _e === void 0 ? void 0 : _e.handlers) === null || _f === void 0 ? void 0 : _f.length))
35
- return res.status(404).json({ message: 'route not found :(' });
36
- handlerState.user.handlers[0](req, res, nextFunc(handlerState.user.handlers));
37
- }
38
- else {
39
- const tokenPayload = jwt.verify(req.cookies.AT_SECRET, process.env.ACCESS_TOKEN_SECRET);
40
- const adminDoc = yield adminModel.findById(tokenPayload.id);
41
- if (!adminDoc)
42
- return res.status(403).json({ message: 'you dont have access for this section' });
43
- if (adminDoc.role != 'OWNER' && adminDoc.role != ((_g = config === null || config === void 0 ? void 0 : config.admin) === null || _g === void 0 ? void 0 : _g.role))
44
- return res.status(403).json({ message: 'you dont have access for this section' });
45
- req.admin = adminDoc;
46
- handlerState.admin.handlers[0](req, res, nextFunc(handlerState.admin.handlers));
47
- }
48
- }
49
- }
50
- catch (error) {
51
- }
52
- });
53
- useAuth.admin = (...handlers) => {
54
- var _a;
55
- if (!Array.isArray(handlers))
56
- throw new Error('handlers must be an array');
57
- handlerState.admin = { role: ((_a = config === null || config === void 0 ? void 0 : config.admin) === null || _a === void 0 ? void 0 : _a.role) || 'admin', handlers };
58
- return useAuth;
59
- };
60
- useAuth.user = (...handlers) => {
61
- if (!Array.isArray(handlers))
62
- throw new Error('handlers must be an array');
63
- handlerState.user = { handlers };
64
- return useAuth;
65
- };
66
- return useAuth;
67
- };
68
- module.exports = auth;
File without changes
@@ -1 +0,0 @@
1
- "use strict";
@@ -1,56 +0,0 @@
1
- export interface IAggregationBuilder {
2
- match(filter: object): this;
3
- group(id: any, fn: (op: IAggregationOperators) => object): this;
4
- project(fields: object): this;
5
- addFields(fields: object): this;
6
- sort(sort: object): this;
7
- limit(n: number): this;
8
- skip(n: number): this;
9
- unwind(field: string | object): this;
10
- lookup(config: ILookupConfig): this;
11
- count(field: string): this;
12
- sortByCount(field: string): this;
13
- facet(facets: {
14
- [key: string]: any[];
15
- }): this;
16
- bucket(params: IBucketConfig): this;
17
- bucketAuto(params: IBucketAutoConfig): this;
18
- replaceRoot(newRoot: object): this;
19
- redact(expression: any): this;
20
- sample(size: number): this;
21
- merge(output: string | object): this;
22
- out(collection: string): this;
23
- raw(stage: object): this;
24
- toArray(): Promise<any[]>;
25
- first(): Promise<any | null>;
26
- }
27
- export interface IAggregationOperators {
28
- sum(field: string | number): object;
29
- avg(field: string | number): object;
30
- min(field: string | number): object;
31
- max(field: string | number): object;
32
- first(field: string): object;
33
- last(field: string): object;
34
- push(field: string): object;
35
- addToSet(field: string): object;
36
- count(): object;
37
- }
38
- export interface ILookupConfig {
39
- from: string;
40
- localField?: string;
41
- foreignField?: string;
42
- as: string;
43
- let?: object;
44
- pipeline?: any[];
45
- }
46
- export interface IBucketConfig {
47
- groupBy: any;
48
- boundaries: any[];
49
- default?: any;
50
- output?: object;
51
- }
52
- export interface IBucketAutoConfig {
53
- groupBy: any;
54
- buckets: number;
55
- output?: object;
56
- }
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
File without changes
@@ -1 +0,0 @@
1
- "use strict";
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });