@opengis/fcore 0.0.29 → 0.0.30

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 (125) hide show
  1. package/LICENSE +3 -3
  2. package/README.md +71 -71
  3. package/dist/config.js +1 -1
  4. package/dist/context.d.ts +2 -0
  5. package/dist/context.d.ts.map +1 -1
  6. package/dist/context.js +1 -1
  7. package/dist/errors.js +1 -1
  8. package/dist/fastify.js +1 -1
  9. package/dist/fcore.d.ts +2 -0
  10. package/dist/fcore.d.ts.map +1 -1
  11. package/dist/fcore.js +1 -1
  12. package/dist/migrations/cli.js +1 -1
  13. package/dist/migrations/runner.js +1 -1
  14. package/dist/modules/auth/adduser-cli.js +1 -1
  15. package/dist/modules/auth/passwd-cli.js +1 -1
  16. package/dist/modules/auth/permission-cli.js +1 -1
  17. package/dist/modules/auth/route.d.ts.map +1 -1
  18. package/dist/modules/auth/route.js +1 -1
  19. package/dist/modules/auth/schema.js +1 -1
  20. package/dist/modules/auth/services/change-password.js +1 -1
  21. package/dist/modules/auth/services/get-current-user.d.ts +2 -2
  22. package/dist/modules/auth/services/get-current-user.d.ts.map +1 -1
  23. package/dist/modules/auth/services/get-current-user.js +1 -1
  24. package/dist/modules/auth/services/registration.js +1 -1
  25. package/dist/modules/auth/services/verify-two-factor.js +1 -1
  26. package/dist/modules/file/mime.js +1 -1
  27. package/dist/modules/file/route.js +1 -1
  28. package/dist/modules/file/schema.js +1 -1
  29. package/dist/modules/file/services/get-file.js +1 -1
  30. package/dist/modules/file/services/resize-file.js +1 -1
  31. package/dist/modules/file/services/upload-file.js +1 -1
  32. package/dist/modules/resource/route.js +1 -1
  33. package/dist/modules/resource/schema.d.ts +3 -2
  34. package/dist/modules/resource/schema.d.ts.map +1 -1
  35. package/dist/modules/resource/schema.js +1 -1
  36. package/dist/modules/resource/services/add-note.js +1 -1
  37. package/dist/modules/resource/services/add-resource-file.js +1 -1
  38. package/dist/modules/resource/services/create-resource-relation.js +1 -1
  39. package/dist/modules/resource/services/create-resource.js +1 -1
  40. package/dist/modules/resource/services/delete-resource-relation.js +1 -1
  41. package/dist/modules/resource/services/delete-resource.js +1 -1
  42. package/dist/modules/resource/services/export-resource.js +1 -1
  43. package/dist/modules/resource/services/generate-resource-code.js +1 -1
  44. package/dist/modules/resource/services/get-resource-schema.js +1 -1
  45. package/dist/modules/resource/services/get-resource.d.ts +1 -1
  46. package/dist/modules/resource/services/get-resource.js +1 -1
  47. package/dist/modules/resource/services/list-resource-as-user.js +1 -1
  48. package/dist/modules/resource/services/list-resource-list.js +1 -1
  49. package/dist/modules/resource/services/list-resource-relation.js +1 -1
  50. package/dist/modules/resource/services/list-resources.js +1 -1
  51. package/dist/modules/resource/services/search-resource.js +1 -1
  52. package/dist/modules/resource/services/suggest-resource.d.ts.map +1 -1
  53. package/dist/modules/resource/services/suggest-resource.js +1 -1
  54. package/dist/modules/resource/services/update-resource-relation.js +1 -1
  55. package/dist/modules/resource/services/update-resource.js +1 -1
  56. package/dist/modules/resource/services/upload-resource-file.js +1 -1
  57. package/dist/modules/system/route.js +1 -1
  58. package/dist/modules/system/schema.js +1 -1
  59. package/dist/modules/system/services/check-system.js +1 -1
  60. package/dist/modules/system/services/get-access.js +1 -1
  61. package/dist/modules/system/services/get-api-list.js +1 -1
  62. package/dist/modules/system/services/get-audit-log.js +1 -1
  63. package/dist/modules/system/services/get-dictionary.js +1 -1
  64. package/dist/modules/system/services/get-resource-access.js +1 -1
  65. package/dist/modules/system/services/get-resource-scopes.js +1 -1
  66. package/dist/modules/system/services/get-system-log.js +1 -1
  67. package/dist/modules/system/services/get-system-settings.js +1 -1
  68. package/dist/modules/system/services/list-dictionaries.js +1 -1
  69. package/dist/modules/system/services/set-access.js +1 -1
  70. package/dist/modules/system/services/set-resource-access.js +1 -1
  71. package/dist/modules/system/services/set-resource-scopes.js +1 -1
  72. package/dist/modules/system/services/update-dictionary.js +1 -1
  73. package/dist/modules/system/services/update-system-settings.js +1 -1
  74. package/dist/modules/utils/require-admin.js +1 -1
  75. package/dist/modules/utils/safe-user.js +1 -1
  76. package/dist/modules/utils/unsupported.js +1 -1
  77. package/dist/plugins/audit/audit.js +1 -1
  78. package/dist/plugins/audit/services/write-audit.js +1 -1
  79. package/dist/plugins/auth/get-user-permissions.js +1 -1
  80. package/dist/plugins/auth/index.d.ts.map +1 -1
  81. package/dist/plugins/auth/index.js +1 -1
  82. package/dist/plugins/auth/verifyUser.js +1 -1
  83. package/dist/plugins/dictionary.js +1 -1
  84. package/dist/plugins/file.js +1 -1
  85. package/dist/plugins/hooks.d.ts +14 -0
  86. package/dist/plugins/hooks.d.ts.map +1 -0
  87. package/dist/plugins/hooks.js +1 -0
  88. package/dist/plugins/index.d.ts +1 -0
  89. package/dist/plugins/index.d.ts.map +1 -1
  90. package/dist/plugins/index.js +1 -1
  91. package/dist/plugins/jwt.js +1 -1
  92. package/dist/plugins/logger/index.js +1 -1
  93. package/dist/plugins/logger/transport.js +1 -1
  94. package/dist/plugins/pg.js +1 -1
  95. package/dist/plugins/redis.js +1 -1
  96. package/dist/plugins/resource/resource.js +1 -1
  97. package/dist/plugins/resource/resource.registry.js +1 -1
  98. package/dist/plugins/resource/resource.types.d.ts +1 -0
  99. package/dist/plugins/resource/resource.types.d.ts.map +1 -1
  100. package/dist/plugins/resource/services/add-dictionary-lookup-data.js +1 -1
  101. package/dist/plugins/resource/services/add-file-token.js +1 -1
  102. package/dist/plugins/resource/services/add-table-lookup-data.js +1 -1
  103. package/dist/plugins/resource/services/create-relation.js +1 -1
  104. package/dist/plugins/resource/services/create.js +1 -1
  105. package/dist/plugins/resource/services/delete-relation.js +1 -1
  106. package/dist/plugins/resource/services/delete.js +1 -1
  107. package/dist/plugins/resource/services/find-one.d.ts.map +1 -1
  108. package/dist/plugins/resource/services/find-one.js +1 -1
  109. package/dist/plugins/resource/services/find-relation.js +1 -1
  110. package/dist/plugins/resource/services/find.js +1 -1
  111. package/dist/plugins/resource/services/get-table-columns.js +1 -1
  112. package/dist/plugins/resource/services/update-relation.js +1 -1
  113. package/dist/plugins/resource/services/update.js +1 -1
  114. package/dist/plugins/resource/utils/auto-index.js +1 -1
  115. package/dist/plugins/resource/utils/fields.js +1 -1
  116. package/dist/plugins/resource/utils/filters.js +1 -1
  117. package/dist/plugins/resource/utils/permissions.js +1 -1
  118. package/dist/plugins/resource/utils/scope.js +1 -1
  119. package/dist/plugins/resource/utils/sort.js +1 -1
  120. package/dist/plugins/resource/utils/sql.js +1 -1
  121. package/dist/plugins/resource/utils/summary.js +1 -1
  122. package/dist/shared/getIP.js +1 -1
  123. package/migrations/20260903130000_move_notes_files_to_admin.sql +17 -17
  124. package/migrations/20260929120000_allow_user_only_role_scopes.sql +1 -1
  125. package/package.json +92 -92
package/LICENSE CHANGED
@@ -1,3 +1,3 @@
1
- Copyright (c) OpenGIS. All rights reserved.
2
-
3
- Proprietary and confidential.
1
+ Copyright (c) OpenGIS. All rights reserved.
2
+
3
+ Proprietary and confidential.
package/README.md CHANGED
@@ -1,72 +1,72 @@
1
- # @opengis/fcore
2
-
3
- Reusable backend foundation for OpenGIS Node.js applications: config, typed application context, PostgreSQL, Redis, S3 file storage, audit, trusted Resource CRUD, Core modules, Fastify integration and SQL migration runner.
4
-
5
- ## Install
6
-
7
- ```bash
8
- npm install @opengis/fcore
9
- ```
10
-
11
- ## Bootstrap
12
-
13
- ```ts
14
- import { createFCore } from '@opengis/fcore';
15
- import resources from './resources/index.js';
16
-
17
- export const ctx = await createFCore({ resources });
18
- ```
19
-
20
- ```ts
21
- import Fastify from 'fastify';
22
- import fcoreFastify from '@opengis/fcore/fastify';
23
- import { ctx } from './app.js';
24
-
25
- const app = Fastify();
26
- await app.register(fcoreFastify, { ctx });
27
- await app.listen({ port: ctx.config.port });
28
- ```
29
-
30
- ## Resource
31
-
32
- All dynamic table/column identifiers come from registered `ResourceContract` metadata. Values are SQL parameters.
33
-
34
- ## Migrations
35
-
36
- Project SQL files stay in `./migrations`. Build the package/application, then run `fcore-migrate` or import `runMigrations()`.
37
-
38
- ## Module service convention
39
-
40
- Module services are plain async functions with the canonical `service(params, ctx)` signature. `ctx` is passed explicitly from `fastify.ts` to each module `route.ts`; there is no `service.ts` or `createService()` factory.
41
-
42
- ## Structure
43
-
44
- ```bash
45
- @opengis/fcore
46
- ├── src/
47
- │ ├── plugins/
48
- │ │ ├── logger/
49
- │ │ ├── redis/
50
- │ │ ├── pg/
51
- │ │ ├── file/
52
- │ │ ├── audit/
53
- │ │ └── resource/
54
- │ ├── modules/
55
- │ │ ├── auth/
56
- │ │ ├── access/
57
- │ │ ├── resource/
58
- │ │ ├── file/
59
- │ │ ├── template/
60
- │ │ └── system/
61
- │ ├── migrations/
62
- │ ├── config.ts # loadConfig
63
- │ ├── context.ts # createContext, set, get
64
- │ ├── errors.ts # standard Errors
65
- │ ├── fastify.ts # fastify Plugins
66
- │ ├── fcore.ts # createFcore
67
- │ └── index.ts # export type, methods, etc
68
- ├── test/
69
- ├── engineering/
70
- ├── package.json
71
- └── tsconfig.json
1
+ # @opengis/fcore
2
+
3
+ Reusable backend foundation for OpenGIS Node.js applications: config, typed application context, PostgreSQL, Redis, S3 file storage, audit, trusted Resource CRUD, Core modules, Fastify integration and SQL migration runner.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @opengis/fcore
9
+ ```
10
+
11
+ ## Bootstrap
12
+
13
+ ```ts
14
+ import { createFCore } from '@opengis/fcore';
15
+ import resources from './resources/index.js';
16
+
17
+ export const ctx = await createFCore({ resources });
18
+ ```
19
+
20
+ ```ts
21
+ import Fastify from 'fastify';
22
+ import fcoreFastify from '@opengis/fcore/fastify';
23
+ import { ctx } from './app.js';
24
+
25
+ const app = Fastify();
26
+ await app.register(fcoreFastify, { ctx });
27
+ await app.listen({ port: ctx.config.port });
28
+ ```
29
+
30
+ ## Resource
31
+
32
+ All dynamic table/column identifiers come from registered `ResourceContract` metadata. Values are SQL parameters.
33
+
34
+ ## Migrations
35
+
36
+ Project SQL files stay in `./migrations`. Build the package/application, then run `fcore-migrate` or import `runMigrations()`.
37
+
38
+ ## Module service convention
39
+
40
+ Module services are plain async functions with the canonical `service(params, ctx)` signature. `ctx` is passed explicitly from `fastify.ts` to each module `route.ts`; there is no `service.ts` or `createService()` factory.
41
+
42
+ ## Structure
43
+
44
+ ```bash
45
+ @opengis/fcore
46
+ ├── src/
47
+ │ ├── plugins/
48
+ │ │ ├── logger/
49
+ │ │ ├── redis/
50
+ │ │ ├── pg/
51
+ │ │ ├── file/
52
+ │ │ ├── audit/
53
+ │ │ └── resource/
54
+ │ ├── modules/
55
+ │ │ ├── auth/
56
+ │ │ ├── access/
57
+ │ │ ├── resource/
58
+ │ │ ├── file/
59
+ │ │ ├── template/
60
+ │ │ └── system/
61
+ │ ├── migrations/
62
+ │ ├── config.ts # loadConfig
63
+ │ ├── context.ts # createContext, set, get
64
+ │ ├── errors.ts # standard Errors
65
+ │ ├── fastify.ts # fastify Plugins
66
+ │ ├── fcore.ts # createFcore
67
+ │ └── index.ts # export type, methods, etc
68
+ ├── test/
69
+ ├── engineering/
70
+ ├── package.json
71
+ └── tsconfig.json
72
72
  ```
package/dist/config.js CHANGED
@@ -1 +1 @@
1
- function O(){const u=['Missing\x20environment\x20variable:\x20','toLowerCase','./storage','password','info','split','map','cwd','/log','false','0ua4b1Tz21m47z13U3EO0uN9e0WE7hqRFbcZ72cbdWqZBzemf9cAU865xan1s81TdNpUKKfF','true','lax','none','auth'];O=function(){return u;};return O();}import'dotenv/config';function c(S,Z){S=S-0x139;const h=O();let U=h[S];return U;}const DEFAULT_LOG_RESPONSE_STATUS_CODES=[0x193,0x199,0x19d,0x19f,0x1ad];function required(S){const U=c,Z=process.env[S];if(!Z)throw new Error(U(0x139)+S);return Z;}export function loadConfig(S={}){const D=c,Z={'env':process.env.NODE_ENV??'development','debug':process.env.DEBUG==='true','port':Number(process.env.PORT??0xbb8),'maxFileSize':+(process.env.MAX_FILE_SIZE||0x200),'rateLimit':{'disabled':process.env.RATE_LIMIT==='false','max':+(process.env.RATE_LIMIT_MAX||0x64),'timeWindow':+(process.env.RATE_LIMIT_TIME_WINDOW||0xea60)},'storageType':(process.env.STORAGE_TYPE??'s3')[D(0x13a)]()==='local'||!process.env.S3_ENDPOINT?'local':'s3','storagePath':process.env.STORAGE_PATH??D(0x13b),'redactionList':(process.env.REDACTION_LIST||D(0x13c))['split'](','),'logger':{'level':process.env.LOG_LEVEL??D(0x13d),'responses':process.env.LOG_RESPONSES==='true'?!![]:![],'responseCodes':process.env.LOG_RESPONSE_STATUS_CODES?process.env.LOG_RESPONSE_STATUS_CODES[D(0x13e)](',')[D(0x13f)](h=>h-0x0):DEFAULT_LOG_RESPONSE_STATUS_CODES,'directory':process.env.LOG_DIRECTORY||process[D(0x140)]()+D(0x141)},'pg':{'host':process.env.PG_HOST??'localhost','port':Number(process.env.PG_PORT??0x1538),'database':process.env.PG_DATABASE??'','user':process.env.PG_USER??'','password':process.env.PG_PASSWORD??''},'redis':{'host':process.env.REDIS_HOST??'','port':Number(process.env.REDIS_PORT??0x18eb),'password':process.env.REDIS_PASSWORD,'lazyConnect':!![],'db':process.env.REDIS_DB?Number(process.env.REDIS_DB):undefined},'s3':{'endpoint':process.env.S3_ENDPOINT,'region':process.env.S3_REGION??'us-east-1','bucket':process.env.S3_BUCKET??'','accessKey':process.env.S3_ACCESS_KEY,'secretKey':process.env.S3_SECRET_KEY,'folder':process.env.S3_FOLDER,'forcePathStyle':process.env.S3_FORCE_PATH_STYLE!==D(0x142),'tokenSecret':process.env.FILE_TOKEN_SECRET,'tokenTtl':Number(process.env.FILE_TOKEN_TTL??0xe10)},'auth':{'accessToken':process.env.AUTH_ACCESS_TOKEN||'Ch7QR4e73Jg0wx0xOjm','user':process.env.AUTH_USER?JSON['parse'](process.env.AUTH_USER):undefined,'sessionTimeout':+(process.env.AUTH_SESSION_TIMEOUT||0x258),'secret':process.env.AUTH_SECRET??'x5y30KBsEKCENT04tu6549Vxx3No1ztJ2q2K8r79S59420RaZ5','cookieName':process.env.AUTH_COOKIE_NAME??'session_user_auth','jwtSecret':process.env.AUTH_JWT_SECRET??D(0x143),'redirect':process.env.AUTH_REDIRECT??'/','twoFactorRedirect':process.env.AUTH_TWOFACTOR_REDIRECT??'/','cookieOptions':process.env.AUTH_COOKIE_OPTIONS_DOMAIN?{'domain':process.env.AUTH_COOKIE_OPTIONS_DOMAIN,'path':process.env.AUTH_COOKIE_OPTIONS_PATH||'/','httpOnly':Boolean(process.env.AUTH_COOKIE_OPTIONS_HTTP_ONLY||D(0x144)),'secure':Boolean(process.env.AUTH_COOKIE_OPTIONS_SECURE||'true'),'sameSite':process.env.AUTH_COOKIE_OPTIONS_SAME_SITE&&[D(0x145),'strict',D(0x146)]['includes'](process.env.AUTH_COOKIE_OPTIONS_SAME_SITE)?process.env.AUTH_COOKIE_OPTIONS_SAME_SITE:Boolean(process.env.AUTH_COOKIE_OPTIONS_SAME_SITE||'true')}:{'path':'/','httpOnly':!![],'secure':![],'sameSite':!![]}}};return{...Z,...S,'logger':{...Z['logger'],...S['logger']},'pg':{...Z['pg'],...S['pg']},'redis':{...Z['redis'],...S['redis']},'s3':{...Z['s3'],...S['s3']},'auth':{...Z['auth'],...S[D(0x147)]}};}export{required as requireEnv};
1
+ function g(i,E){i=i-0xc7;const W=T();let M=W[i];return M;}import'dotenv/config';const DEFAULT_LOG_RESPONSE_STATUS_CODES=[0x193,0x199,0x19d,0x19f,0x1ad];function required(i){const M=g,E=process.env[i];if(!E)throw new Error(M(0xc7)+i);return E;}export function loadConfig(i={}){const m=g,E={'env':process.env.NODE_ENV??m(0xc8),'debug':process.env.DEBUG==='true','port':Number(process.env.PORT??0xbb8),'maxFileSize':+(process.env.MAX_FILE_SIZE||0x200),'rateLimit':{'disabled':process.env.RATE_LIMIT===m(0xc9),'max':+(process.env.RATE_LIMIT_MAX||0x64),'timeWindow':+(process.env.RATE_LIMIT_TIME_WINDOW||0xea60)},'storageType':(process.env.STORAGE_TYPE??'s3')['toLowerCase']()==='local'||!process.env.S3_ENDPOINT?'local':'s3','storagePath':process.env.STORAGE_PATH??'./storage','redactionList':(process.env.REDACTION_LIST||'password')[m(0xca)](','),'logger':{'level':process.env.LOG_LEVEL??m(0xcb),'responses':process.env.LOG_RESPONSES===m(0xcc)?!![]:![],'responseCodes':process.env.LOG_RESPONSE_STATUS_CODES?process.env.LOG_RESPONSE_STATUS_CODES[m(0xca)](',')[m(0xcd)](W=>W-0x0):DEFAULT_LOG_RESPONSE_STATUS_CODES,'directory':process.env.LOG_DIRECTORY||process['cwd']()+'/log'},'pg':{'host':process.env.PG_HOST??'localhost','port':Number(process.env.PG_PORT??0x1538),'database':process.env.PG_DATABASE??'','user':process.env.PG_USER??'','password':process.env.PG_PASSWORD??''},'redis':{'host':process.env.REDIS_HOST??'','port':Number(process.env.REDIS_PORT??0x18eb),'password':process.env.REDIS_PASSWORD,'lazyConnect':!![],'db':process.env.REDIS_DB?Number(process.env.REDIS_DB):undefined},'s3':{'endpoint':process.env.S3_ENDPOINT,'region':process.env.S3_REGION??'us-east-1','bucket':process.env.S3_BUCKET??'','accessKey':process.env.S3_ACCESS_KEY,'secretKey':process.env.S3_SECRET_KEY,'folder':process.env.S3_FOLDER,'forcePathStyle':process.env.S3_FORCE_PATH_STYLE!=='false','tokenSecret':process.env.FILE_TOKEN_SECRET,'tokenTtl':Number(process.env.FILE_TOKEN_TTL??0xe10)},'auth':{'accessToken':process.env.AUTH_ACCESS_TOKEN||'Ch7QR4e73Jg0wx0xOjm','user':process.env.AUTH_USER?JSON['parse'](process.env.AUTH_USER):undefined,'sessionTimeout':+(process.env.AUTH_SESSION_TIMEOUT||0x258),'secret':process.env.AUTH_SECRET??m(0xce),'cookieName':process.env.AUTH_COOKIE_NAME??'session_user_auth','jwtSecret':process.env.AUTH_JWT_SECRET??'0ua4b1Tz21m47z13U3EO0uN9e0WE7hqRFbcZ72cbdWqZBzemf9cAU865xan1s81TdNpUKKfF','redirect':process.env.AUTH_REDIRECT??'/','twoFactorRedirect':process.env.AUTH_TWOFACTOR_REDIRECT??'/','cookieOptions':process.env.AUTH_COOKIE_OPTIONS_DOMAIN?{'domain':process.env.AUTH_COOKIE_OPTIONS_DOMAIN,'path':process.env.AUTH_COOKIE_OPTIONS_PATH||'/','httpOnly':Boolean(process.env.AUTH_COOKIE_OPTIONS_HTTP_ONLY||m(0xcc)),'secure':Boolean(process.env.AUTH_COOKIE_OPTIONS_SECURE||'true'),'sameSite':process.env.AUTH_COOKIE_OPTIONS_SAME_SITE&&['lax','strict',m(0xcf)]['includes'](process.env.AUTH_COOKIE_OPTIONS_SAME_SITE)?process.env.AUTH_COOKIE_OPTIONS_SAME_SITE:Boolean(process.env.AUTH_COOKIE_OPTIONS_SAME_SITE||m(0xcc))}:{'path':'/','httpOnly':!![],'secure':![],'sameSite':!![]}}};return{...E,...i,'logger':{...E['logger'],...i['logger']},'pg':{...E['pg'],...i['pg']},'redis':{...E['redis'],...i['redis']},'s3':{...E['s3'],...i['s3']},'auth':{...E['auth'],...i['auth']}};}function T(){const P=['Missing\x20environment\x20variable:\x20','development','false','split','info','true','map','x5y30KBsEKCENT04tu6549Vxx3No1ztJ2q2K8r79S59420RaZ5','none'];T=function(){return P;};return T();}export{required as requireEnv};
package/dist/context.d.ts CHANGED
@@ -8,6 +8,7 @@ import type { FileAdapter } from "./plugins/file.js";
8
8
  import type { ResourcePlugin } from "./plugins/resource/index.js";
9
9
  import type { AuditPlugin } from "./plugins/audit/index.js";
10
10
  import type { DictionaryPlugin } from "./plugins/dictionary.js";
11
+ import type { FCoreHooks } from "./plugins/hooks.js";
11
12
  import { AuthUser } from "./plugins/auth/auth.types.js";
12
13
  import { AppLogger } from "./plugins/index.js";
13
14
  export type User = AuthUser;
@@ -20,6 +21,7 @@ export interface AppContext {
20
21
  resource: ResourcePlugin;
21
22
  audit: AuditPlugin;
22
23
  dictionary: DictionaryPlugin;
24
+ hooks?: FCoreHooks;
23
25
  close(): Promise<void>;
24
26
  }
25
27
  export type ContextDependencies = Omit<AppContext, "close">;
@@ -1 +1 @@
1
- {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE/C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAClE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,EAAE,QAAQ,EAAE,MAAM,8BAA8B,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAE/C,MAAM,MAAM,IAAI,GAAG,QAAQ,CAAC;AAE5B,MAAM,WAAW,UAAU;IACzB,MAAM,EAAE,WAAW,CAAC;IACpB,MAAM,EAAE,SAAS,CAAC;IAClB,KAAK,EAAE,YAAY,CAAC;IACpB,EAAE,EAAE,eAAe,CAAC;IACpB,IAAI,EAAE,WAAW,CAAC;IAClB,QAAQ,EAAE,cAAc,CAAC;IACzB,KAAK,EAAE,WAAW,CAAC;IACnB,UAAU,EAAE,gBAAgB,CAAC;IAC7B,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB;AAED,MAAM,MAAM,mBAAmB,GAAG,IAAI,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;AAI5D,wBAAgB,UAAU,CAAC,OAAO,EAAE,UAAU,GAAG,IAAI,CAEpD;AAED,wBAAgB,UAAU,IAAI,UAAU,CAKvC;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,mBAAmB,GAAG,UAAU,CAQnE"}
1
+ {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE/C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAClE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,8BAA8B,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAE/C,MAAM,MAAM,IAAI,GAAG,QAAQ,CAAC;AAE5B,MAAM,WAAW,UAAU;IACzB,MAAM,EAAE,WAAW,CAAC;IACpB,MAAM,EAAE,SAAS,CAAC;IAClB,KAAK,EAAE,YAAY,CAAC;IACpB,EAAE,EAAE,eAAe,CAAC;IACpB,IAAI,EAAE,WAAW,CAAC;IAClB,QAAQ,EAAE,cAAc,CAAC;IACzB,KAAK,EAAE,WAAW,CAAC;IACnB,UAAU,EAAE,gBAAgB,CAAC;IAC7B,KAAK,CAAC,EAAE,UAAU,CAAC;IACnB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB;AAED,MAAM,MAAM,mBAAmB,GAAG,IAAI,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;AAI5D,wBAAgB,UAAU,CAAC,OAAO,EAAE,UAAU,GAAG,IAAI,CAEpD;AAED,wBAAgB,UAAU,IAAI,UAAU,CAKvC;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,mBAAmB,GAAG,UAAU,CAQnE"}
package/dist/context.js CHANGED
@@ -1 +1 @@
1
- let defaultContext;function c(S,Z){S=S-0x12c;const h=O();let U=h[S];return U;}export function setContext(S){defaultContext=S;}function O(){const h=['redis'];O=function(){return h;};return O();}export function getContext(){if(!defaultContext)throw new Error('Application\x20context\x20is\x20not\x20initialized');return defaultContext;}export function createContext(S){return{...S,async 'close'(){const Z=c;await Promise['allSettled']([S[Z(0x12c)]?.['close'](),S['pg']?.['end']()]),await S['logger']['close']();}};}
1
+ function T(){const W=['close'];T=function(){return W;};return T();}let defaultContext;function g(i,E){i=i-0x1ec;const W=T();let M=W[i];return M;}export function setContext(i){defaultContext=i;}export function getContext(){if(!defaultContext)throw new Error('Application\x20context\x20is\x20not\x20initialized');return defaultContext;}export function createContext(i){return{...i,async 'close'(){const E=g;await Promise['allSettled']([i['redis']?.[E(0x1ec)](),i['pg']?.['end']()]),await i['logger']['close']();}};}
package/dist/errors.js CHANGED
@@ -1 +1 @@
1
- var u=c;export class FCoreError extends Error{['code'];['statusCode'];['details'];constructor(S,Z,h=0x1f4,U){var D=c;super(Z),this[D(0x139)]=S,this['statusCode']=h,this[D(0x13a)]=U,this['name']=new.target.name;}}function O(){var q=['code','details','Access\x20denied','Not\x20found','Conflict','VALIDATION_ERROR','Operation\x20is\x20not\x20configured'];O=function(){return q;};return O();}export class BadRequestError extends FCoreError{constructor(S,Z){super('BAD_REQUEST_ERROR',S,0x190,Z);}}export class UnauthorizedError extends FCoreError{constructor(S='Authentication\x20required'){super('UNAUTHORIZED',S,0x191);}}export class ForbiddenError extends FCoreError{constructor(S=u(0x13b)){super('FORBIDDEN',S,0x193);}}export class NotFoundError extends FCoreError{constructor(S=u(0x13c)){super('NOT_FOUND',S,0x194);}}export class ConflictError extends FCoreError{constructor(S=u(0x13d)){super('CONFLICT',S,0x199);}}export class ValidationError extends FCoreError{constructor(S,Z){var e=u;super(e(0x13e),S,0x1a6,Z);}}function c(S,Z){S=S-0x139;var h=O();var U=h[S];return U;}export class UnsupportedError extends FCoreError{constructor(S=u(0x13f)){super('UNSUPPORTED',S,0x1f5);}}
1
+ var m=g;function g(i,E){i=i-0x118;var W=T();var M=W[i];return M;}export class FCoreError extends Error{['code'];[m(0x118)];['details'];constructor(i,E,W=0x1f4,M){var P=m;super(E),this['code']=i,this[P(0x118)]=W,this[P(0x119)]=M,this['name']=new.target.name;}}export class BadRequestError extends FCoreError{constructor(i,E){super('BAD_REQUEST_ERROR',i,0x190,E);}}export class UnauthorizedError extends FCoreError{constructor(i=m(0x11a)){super('UNAUTHORIZED',i,0x191);}}export class ForbiddenError extends FCoreError{constructor(i='Access\x20denied'){var D=m;super(D(0x11b),i,0x193);}}export class NotFoundError extends FCoreError{constructor(i='Not\x20found'){var x=m;super(x(0x11c),i,0x194);}}function T(){var f=['statusCode','details','Authentication\x20required','FORBIDDEN','NOT_FOUND','Operation\x20is\x20not\x20configured','UNSUPPORTED'];T=function(){return f;};return T();}export class ConflictError extends FCoreError{constructor(i='Conflict'){super('CONFLICT',i,0x199);}}export class ValidationError extends FCoreError{constructor(i,E){super('VALIDATION_ERROR',i,0x1a6,E);}}export class UnsupportedError extends FCoreError{constructor(i=m(0x11d)){var Z=m;super(Z(0x11e),i,0x1f5);}}
package/dist/fastify.js CHANGED
@@ -1 +1 @@
1
- import S from'fastify-plugin';import{FCoreError}from'./errors.js';import{authRoutes}from'./modules/auth/route.js';import{fileRoutes}from'./modules/file/route.js';import{resourceRoutes}from'./modules/resource/route.js';import{systemRoutes}from'./modules/system/route.js';import{createSessionStore}from'./plugins/auth/index.js';import{ForbiddenError}from'./errors.js';function c(S,Z){S=S-0x1d5;const h=O();let U=h[S];return U;}import{jwtVerifyToken}from'./plugins/jwt.js';function urlencodedContentParser(Z,h,U){const l=c,D=decodeURIComponent(h['toString']())['split']('&')[l(0x1d5)]((u,e)=>{const [q,x]=e['split']('=');return{...u,[q]:x};},{});U(null,D);}export default function fcoreFastify(Z,h){return S(async U=>{const b=c;U['decorate'](b(0x1d6),Z);const {config:D}=Z,u=new Map();U['addHook']('onRoute',q=>{const Y=b,x=q['schema'],n=Array[Y(0x1d7)](q[Y(0x1d8)])?q['method']:[q[Y(0x1d8)]];for(const N of n){if(N==='HEAD')continue;const o={'method':N,'endpoint':q['url'],'package':x?.['package']??'fcore','tags':x?.['tags']??[],'summary':x?.[Y(0x1d9)]??'','description':x?.['description']??'','access':x?.['access']??'public','permissions':x?.[Y(0x1da)]??[]};u['set'](N+'\x20'+q['url'],o);}}),U['addHook']('preHandler',async q=>{const r=b;if(q['routeOptions'][r(0x1db)]==='*')return!![];const x=u['get'](q[r(0x1d8)]+'\x20'+q['routeOptions'][r(0x1db)]),n=!q['user']&&process['platform']==='win32'&&Z['config']?.[r(0x1dc)]?.['user']?Z['config']?.['auth']?.['user']:null,N=q[r(0x1dd)]['headers']?.[r(0x1de)],o=N?.['startsWith'](r(0x1df))?N['slice'](0x7):null,j=q['user']??(o?await jwtVerifyToken(o):n);!q['user']&&o&&process.env.AUTH_JWT_SECRET&&(q['user']=await jwtVerifyToken(o));if(!x?.['access'])throw new ForbiddenError('Route\x20access\x20not\x20defined');if(x['access']===r(0x1e0))return!![];if(!j)throw new ForbiddenError(r(0x1e1));if(x[r(0x1e2)]==='user'&&!x[r(0x1da)]?.['length'])return!![];if(j['type']=='admin')return!![];if(x['access']==='admin')throw new ForbiddenError(r(0x1e3));for(const X of x[r(0x1da)]){const i=X?.['replace']('$resource',q['params'][r(0x1e4)]??'');if(!j[r(0x1da)]?.[r(0x1e5)](i))throw new ForbiddenError('Missing\x20permission:\x20'+i);}return!![];}),await createSessionStore(U,Z),await U['register'](import(b(0x1e6)),{'limits':{'fileSize':D['maxFileSize']*0x400*0x400}}),U['setErrorHandler']((q,x,n)=>{const E=b;if(q instanceof FCoreError||q[E(0x1e7)]==='FST_ERR_VALIDATION'||q['statusCode']<0x1f4)return q['statusCode']<0x1f4&&Z['logger']['warn'](q),n[E(0x1e7)](q['statusCode'])['send']({'error':q['code'],'message':q[E(0x1e8)],'details':q['details']});return Z[E(0x1e9)]['error'](q),(D[E(0x1ea)]||process.env.NODE_ENV===E(0x1eb)||process.env.VITEST)&&console['error'](q),n[E(0x1e7)](0x1f4)[E(0x1ec)]({'error':'INTERNAL_ERROR','message':'Internal\x20server\x20error'});});const e=q=>!h||h['includes'](q);if(e('auth'))await U['register'](authRoutes(Z));if(e('resource'))await U['register'](resourceRoutes(Z));if(e('file'))await U['register'](fileRoutes(Z));if(e('system'))await U['register'](systemRoutes(Z,u));U['addContentTypeParser']('application/x-www-form-urlencoded',{'parseAs':'buffer'},urlencodedContentParser),!D['rateLimit']?.['disabled']?U['register'](import(b(0x1ed)),{'max':D['rateLimit']?.['max']||0x64,'timeWindow':D['rateLimit']?.['timeWindow']||0xea60,'hook':b(0x1ee),'global':!![],'keyGenerator':q=>(q['user']?.['id']||q['ip'])+'-'+q[b(0x1dd)]['url']['split']('?')[0x0]}):console['log'](b(0x1ef));});}function O(){const L=['reduce','ctx','isArray','method','summary','permissions','url','auth','raw','authorization','Bearer\x20','public','User\x20required','access','Admin\x20access\x20required','resource','includes','@fastify/multipart','code','message','logger','debug','test','send','@fastify/rate-limit','preHandler','⚠️\x20rate\x20limit\x20is\x20disabled'];O=function(){return L;};return O();}
1
+ import i from'fastify-plugin';import{FCoreError}from'./errors.js';function g(i,E){i=i-0xbc;const W=T();let M=W[i];return M;}import{authRoutes}from'./modules/auth/route.js';import{fileRoutes}from'./modules/file/route.js';function T(){const S=['schema','url','fcore','tags','description','access','addHook','preHandler','routeOptions','raw','headers','authorization','user','type','admin','params','Missing\x20permission:\x20','register','setErrorHandler','warn','send','code','message','details','test','buffer','@fastify/rate-limit'];T=function(){return S;};return T();}import{resourceRoutes}from'./modules/resource/route.js';import{systemRoutes}from'./modules/system/route.js';import{createSessionStore}from'./plugins/auth/index.js';import{ForbiddenError}from'./errors.js';import{jwtVerifyToken}from'./plugins/jwt.js';function urlencodedContentParser(E,W,M){const m=decodeURIComponent(W['toString']())['split']('&')['reduce']((P,D)=>{const [x,Z]=D['split']('=');return{...P,[x]:Z};},{});M(null,m);}export default function fcoreFastify(E,W){return i(async M=>{const o=g;M['decorate']('ctx',E);const {config:m}=E,P=new Map();M['addHook']('onRoute',x=>{const s=g,Z=x[s(0xbc)],f=Array['isArray'](x['method'])?x['method']:[x['method']];for(const b of f){if(b==='HEAD')continue;const K={'method':b,'endpoint':x[s(0xbd)],'package':Z?.['package']??s(0xbe),'tags':Z?.[s(0xbf)]??[],'summary':Z?.['summary']??'','description':Z?.[s(0xc0)]??'','access':Z?.[s(0xc1)]??'public','permissions':Z?.['permissions']??[]};P['set'](b+'\x20'+x['url'],K);}}),M[o(0xc2)](o(0xc3),async x=>{const r=o;if(x[r(0xc4)]['url']==='*')return!![];const Z=P['get'](x['method']+'\x20'+x[r(0xc4)]['url']),f=!x['user']&&process['platform']==='win32'&&E['config']?.['auth']?.['user']?E['config']?.['auth']?.['user']:null,b=x[r(0xc5)][r(0xc6)]?.[r(0xc7)],K=b?.['startsWith']('Bearer\x20')?b['slice'](0x7):null,J=x['user']??(K?await jwtVerifyToken(K):f);!x[r(0xc8)]&&K&&process.env.AUTH_JWT_SECRET&&(x['user']=await jwtVerifyToken(K));if(!Z?.['access'])throw new ForbiddenError('Route\x20access\x20not\x20defined');if(Z[r(0xc1)]==='public')return!![];if(!J)throw new ForbiddenError('User\x20required');if(Z['access']===r(0xc8)&&!Z['permissions']?.['length'])return!![];if(J[r(0xc9)]==r(0xca))return!![];if(Z['access']==='admin')throw new ForbiddenError('Admin\x20access\x20required');for(const Q of Z['permissions']){const y=Q?.['replace']('$resource',x[r(0xcb)]['resource']??'');if(!J['permissions']?.['includes'](y))throw new ForbiddenError(r(0xcc)+y);}return!![];}),await createSessionStore(M,E),await M[o(0xcd)](import('@fastify/multipart'),{'limits':{'fileSize':m['maxFileSize']*0x400*0x400}}),M[o(0xce)]((x,Z,f)=>{const G=o;if(x instanceof FCoreError||x['code']==='FST_ERR_VALIDATION'||x['statusCode']<0x1f4)return x['statusCode']<0x1f4&&E['logger'][G(0xcf)](x),f['code'](x['statusCode'])[G(0xd0)]({'error':x[G(0xd1)],'message':x[G(0xd2)],'details':x[G(0xd3)]});return E['logger']['error'](x),(m['debug']||process.env.NODE_ENV===G(0xd4)||process.env.VITEST)&&console['error'](x),f['code'](0x1f4)[G(0xd0)]({'error':'INTERNAL_ERROR','message':'Internal\x20server\x20error'});});const D=x=>!W||W['includes'](x);if(D('auth'))await M['register'](authRoutes(E));if(D('resource'))await M['register'](resourceRoutes(E));if(D('file'))await M['register'](fileRoutes(E));if(D('system'))await M[o(0xcd)](systemRoutes(E,P));M['addContentTypeParser']('application/x-www-form-urlencoded',{'parseAs':o(0xd5)},urlencodedContentParser),!m['rateLimit']?.['disabled']?M[o(0xcd)](import(o(0xd6)),{'max':m['rateLimit']?.['max']||0x64,'timeWindow':m['rateLimit']?.['timeWindow']||0xea60,'hook':o(0xc3),'global':!![],'keyGenerator':x=>(x['user']?.['id']||x['ip'])+'-'+x['raw']['url']['split']('?')[0x0]}):console['log']('⚠️\x20rate\x20limit\x20is\x20disabled');});}
package/dist/fcore.d.ts CHANGED
@@ -4,10 +4,12 @@
4
4
  import { type FCoreConfig } from "./config.js";
5
5
  import { type AppContext } from "./context.js";
6
6
  import { type DictionaryDefinition, type ResourceContract } from "./plugins/index.js";
7
+ import { type FCoreHooks } from "./plugins/hooks.js";
7
8
  export interface CreateFCoreOptions {
8
9
  config?: Partial<FCoreConfig>;
9
10
  resources?: ResourceContract[];
10
11
  dictionaries?: DictionaryDefinition[];
12
+ hooks?: FCoreHooks;
11
13
  }
12
14
  export declare function createFCore(options?: CreateFCoreOptions): Promise<AppContext>;
13
15
  //# sourceMappingURL=fcore.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"fcore.d.ts","sourceRoot":"","sources":["../src/fcore.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,EAAc,KAAK,WAAW,EAAE,MAAM,aAAa,CAAC;AAC3D,OAAO,EAA6B,KAAK,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1E,OAAO,EASL,KAAK,oBAAoB,EACzB,KAAK,gBAAgB,EACtB,MAAM,oBAAoB,CAAC;AAE5B,MAAM,WAAW,kBAAkB;IACjC,MAAM,CAAC,EAAE,OAAO,CAAC,WAAW,CAAC,CAAC;IAC9B,SAAS,CAAC,EAAE,gBAAgB,EAAE,CAAC;IAC/B,YAAY,CAAC,EAAE,oBAAoB,EAAE,CAAC;CACvC;AAED,wBAAsB,WAAW,CAC/B,OAAO,GAAE,kBAAuB,GAC/B,OAAO,CAAC,UAAU,CAAC,CAqDrB"}
1
+ {"version":3,"file":"fcore.d.ts","sourceRoot":"","sources":["../src/fcore.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,EAAc,KAAK,WAAW,EAAE,MAAM,aAAa,CAAC;AAC3D,OAAO,EAA6B,KAAK,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1E,OAAO,EASL,KAAK,oBAAoB,EACzB,KAAK,gBAAgB,EACtB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,KAAK,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAErD,MAAM,WAAW,kBAAkB;IACjC,MAAM,CAAC,EAAE,OAAO,CAAC,WAAW,CAAC,CAAC;IAC9B,SAAS,CAAC,EAAE,gBAAgB,EAAE,CAAC;IAC/B,YAAY,CAAC,EAAE,oBAAoB,EAAE,CAAC;IACtC,KAAK,CAAC,EAAE,UAAU,CAAC;CACpB;AAED,wBAAsB,WAAW,CAC/B,OAAO,GAAE,kBAAuB,GAC/B,OAAO,CAAC,UAAU,CAAC,CAsDrB"}
package/dist/fcore.js CHANGED
@@ -1 +1 @@
1
- import{loadConfig}from'./config.js';import{createContext,setContext}from'./context.js';import{createAudit,createDatabase,createDictionary,createFileLocal,createFileS3,createLogger,createRedis,createResource}from'./plugins/index.js';function c(S,Z){S=S-0xb7;const h=O();let U=h[S];return U;}export async function createFCore(S={}){const N=c,Z=loadConfig(S[N(0xb7)]),h=createRedis(Z['redis']),U=createLogger(),D=createDatabase(Z['pg']),u=Z[N(0xb8)]==='local'?createFileLocal({'storagePath':Z[N(0xb9)],'folder':Z['s3']['folder'],'tokenSecret':Z['s3']['tokenSecret'],'tokenTtl':Z['s3']['tokenTtl']}):createFileS3({'endpoint':Z['s3']['endpoint'],'region':Z['s3']['region'],'bucket':Z['s3']['bucket'],'accessKey':Z['s3']['accessKey'],'secretKey':Z['s3']['secretKey'],'folder':Z['s3']['folder'],'forcePathStyle':Z['s3']['forcePathStyle'],'tokenSecret':Z['s3'][N(0xba)],'tokenTtl':Z['s3']['tokenTtl']}),e=createAudit({'pg':D,'logger':U}),q=createDictionary({'pg':D,'dictionaries':S['dictionaries']}),x=createResource({'pg':D,'logger':U,'audit':e,'dictionary':q,'file':u});S['resources']?.['length']&&x['register'](S['resources']);const n=createContext({'config':Z,'logger':U,'redis':h,'pg':D,'file':u,'resource':x,'audit':e,'dictionary':q});return setContext(n),n;}function O(){const o=['config','storageType','storagePath','tokenSecret'];O=function(){return o;};return O();}
1
+ import{loadConfig}from'./config.js';import{createContext,setContext}from'./context.js';function g(i,E){i=i-0x78;const W=T();let M=W[i];return M;}import{createAudit,createDatabase,createDictionary,createFileLocal,createFileS3,createLogger,createRedis,createResource}from'./plugins/index.js';function T(){const K=['redis','tokenTtl','endpoint','forcePathStyle','tokenSecret','length'];T=function(){return K;};return T();}export async function createFCore(i={}){const b=g,E=loadConfig(i['config']),W=createRedis(E[b(0x78)]),M=createLogger(),m=createDatabase(E['pg']),P=E['storageType']==='local'?createFileLocal({'storagePath':E['storagePath'],'folder':E['s3']['folder'],'tokenSecret':E['s3']['tokenSecret'],'tokenTtl':E['s3'][b(0x79)]}):createFileS3({'endpoint':E['s3'][b(0x7a)],'region':E['s3']['region'],'bucket':E['s3']['bucket'],'accessKey':E['s3']['accessKey'],'secretKey':E['s3']['secretKey'],'folder':E['s3']['folder'],'forcePathStyle':E['s3'][b(0x7b)],'tokenSecret':E['s3'][b(0x7c)],'tokenTtl':E['s3'][b(0x79)]}),D=createAudit({'pg':m,'logger':M}),x=createDictionary({'pg':m,'dictionaries':i['dictionaries']}),Z=createResource({'pg':m,'logger':M,'audit':D,'dictionary':x,'file':P});i['resources']?.[b(0x7d)]&&Z['register'](i['resources']);const f=createContext({'config':E,'logger':M,'redis':W,'pg':m,'file':P,'resource':Z,'audit':D,'dictionary':x,'hooks':i['hooks']});return setContext(f),f;}
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- const q=c;import{runMigrations}from'./runner.js';function O(){const n=['../../migrations','--dir','--dir\x20requires\x20a\x20folder\x20path','--fcore','find','resolve','log','****','slice','OK\x20\x20','exitCode'];O=function(){return n;};return O();}import{loadConfig}from'../config.js';import S from'node:path';import{fileURLToPath}from'node:url';const packageMigrations=fileURLToPath(new URL(q(0xe4),import.meta.url));function migrationDirectory(Z){const x=q,h=Z['indexOf'](x(0xe5));if(h>=0x0){const D=Z[h+0x1];if(!D)throw new Error(x(0xe6));return S['resolve'](D);}if(Z['includes'](x(0xe7)))return packageMigrations;const U=Z[x(0xe8)](u=>!u['startsWith']('--'));return S[x(0xe9)](U??'migrations');}function c(S,Z){S=S-0xe4;const h=O();let U=h[S];return U;}try{const config=loadConfig(),dir=migrationDirectory(process['argv']['slice'](0x2));console[q(0xea)]('Loaded\x20configuration:',{...config['pg'],'user':q(0xeb),'password':'****'}),console['log']('Using\x20migration\x20directory:',dir,process['argv'][q(0xec)](0x2));for(const r of await runMigrations({'database':config['pg'],'dir':dir}))console[q(0xea)]((r['status']==='run'?q(0xed):'SKIP')+'\x20'+r['file']);}catch(e){console['error'](e),process[q(0xee)]=0x1;}
2
+ const Z=g;import{runMigrations}from'./runner.js';function T(){const f=['indexOf','resolve','migrations','argv','Loaded\x20configuration:','****','log','error'];T=function(){return f;};return T();}import{loadConfig}from'../config.js';import i from'node:path';import{fileURLToPath}from'node:url';const packageMigrations=fileURLToPath(new URL('../../migrations',import.meta.url));function migrationDirectory(E){const x=g,W=E[x(0x13f)]('--dir');if(W>=0x0){const m=E[W+0x1];if(!m)throw new Error('--dir\x20requires\x20a\x20folder\x20path');return i['resolve'](m);}if(E['includes']('--fcore'))return packageMigrations;const M=E['find'](P=>!P['startsWith']('--'));return i[x(0x140)](M??x(0x141));}function g(i,E){i=i-0x13f;const W=T();let M=W[i];return M;}try{const config=loadConfig(),dir=migrationDirectory(process[Z(0x142)]['slice'](0x2));console['log'](Z(0x143),{...config['pg'],'user':'****','password':Z(0x144)}),console['log']('Using\x20migration\x20directory:',dir,process['argv']['slice'](0x2));for(const r of await runMigrations({'database':config['pg'],'dir':dir}))console[Z(0x145)]((r['status']==='run'?'OK\x20\x20':'SKIP')+'\x20'+r['file']);}catch(D){console[Z(0x146)](D),process['exitCode']=0x1;}
@@ -1 +1 @@
1
- import S from'node:fs/promises';import Z from'node:path';function O(){const l=['dir','migrations','DATABASE_URL\x20or\x20database\x20config\x20is\x20required','query','\x0a\x20\x20\x20\x20\x20\x20CREATE\x20TABLE\x20IF\x20NOT\x20EXISTS\x20schema_migrations\x20(\x0a\x20\x20\x20\x20\x20\x20\x20\x20version\x20varchar(255)\x20PRIMARY\x20KEY,\x0a\x20\x20\x20\x20\x20\x20\x20\x20applied_at\x20timestamptz\x20NOT\x20NULL\x20DEFAULT\x20now()\x0a\x20\x20\x20\x20\x20\x20)\x0a\x20\x20\x20\x20','rows','readdir','endsWith','join','connect','INSERT\x20INTO\x20schema_migrations(version)\x20VALUES\x20($1)','end'];O=function(){return l;};return O();}import{createDatabase}from'../plugins/pg.js';export async function runMigrations(h={}){const i=c,U=Z['resolve'](h[i(0x6e)]??i(0x6f)),D=h['database']??databaseFromUrl(h['databaseUrl']??process.env.DATABASE_URL);if(!D)throw new Error(i(0x70));const u=createDatabase(D);if(!u)throw new Error('empty\x20pg');const e=[];try{await u[i(0x71)](i(0x72));const q=await u['query']('SELECT\x20version\x20FROM\x20schema_migrations'),x=new Set(q[i(0x73)]['map'](N=>N['version'])),n=(await S[i(0x74)](U))['filter'](N=>N[i(0x75)]('.sql'))['sort']();for(const N of n){if(x['has'](N)){e['push']({'file':N,'status':'skip'});continue;}const o=await S['readFile'](Z[i(0x76)](U,N),'utf8'),j=await u[i(0x77)]();try{await j['query']('BEGIN'),await j['query'](o),await j['query'](i(0x78),[N]),await j[i(0x71)]('COMMIT');}catch(X){await j['query']('ROLLBACK');throw X;}finally{j['release']();}e['push']({'file':N,'status':'run'});}return e;}finally{await u[i(0x79)]();}}function c(S,Z){S=S-0x6e;const h=O();let U=h[S];return U;}function databaseFromUrl(h){if(!h)return undefined;const U=new URL(h);return{'host':U['hostname'],'port':Number(U['port']||0x1538),'database':U['pathname']['slice'](0x1),'user':decodeURIComponent(U['username']),'password':decodeURIComponent(U['password'])};}
1
+ import i from'node:fs/promises';function g(i,E){i=i-0xab;const W=T();let M=W[i];return M;}import E from'node:path';function T(){const o=['DATABASE_URL\x20or\x20database\x20config\x20is\x20required','query','SELECT\x20version\x20FROM\x20schema_migrations','version','utf8','BEGIN','COMMIT','end','port','slice','password'];T=function(){return o;};return T();}import{createDatabase}from'../plugins/pg.js';export async function runMigrations(W={}){const y=g,M=E['resolve'](W['dir']??'migrations'),m=W['database']??databaseFromUrl(W['databaseUrl']??process.env.DATABASE_URL);if(!m)throw new Error(y(0xab));const P=createDatabase(m);if(!P)throw new Error('empty\x20pg');const D=[];try{await P[y(0xac)]('\x0a\x20\x20\x20\x20\x20\x20CREATE\x20TABLE\x20IF\x20NOT\x20EXISTS\x20schema_migrations\x20(\x0a\x20\x20\x20\x20\x20\x20\x20\x20version\x20varchar(255)\x20PRIMARY\x20KEY,\x0a\x20\x20\x20\x20\x20\x20\x20\x20applied_at\x20timestamptz\x20NOT\x20NULL\x20DEFAULT\x20now()\x0a\x20\x20\x20\x20\x20\x20)\x0a\x20\x20\x20\x20');const x=await P['query'](y(0xad)),Z=new Set(x['rows']['map'](b=>b[y(0xae)])),f=(await i['readdir'](M))['filter'](b=>b['endsWith']('.sql'))['sort']();for(const b of f){if(Z['has'](b)){D['push']({'file':b,'status':'skip'});continue;}const K=await i['readFile'](E['join'](M,b),y(0xaf)),J=await P['connect']();try{await J['query'](y(0xb0)),await J['query'](K),await J['query']('INSERT\x20INTO\x20schema_migrations(version)\x20VALUES\x20($1)',[b]),await J[y(0xac)](y(0xb1));}catch(Q){await J['query']('ROLLBACK');throw Q;}finally{J['release']();}D['push']({'file':b,'status':'run'});}return D;}finally{await P[y(0xb2)]();}}function databaseFromUrl(W){const s=g;if(!W)return undefined;const M=new URL(W);return{'host':M['hostname'],'port':Number(M[s(0xb3)]||0x1538),'database':M['pathname'][s(0xb4)](0x1),'user':decodeURIComponent(M['username']),'password':decodeURIComponent(M[s(0xb5)])};}
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- const h=c;import{loadConfig}from'../../config.js';function O(){const U=['Usage:\x20fcore-registration\x20<login>\x20<password>\x20[type]','log','exitCode','end'];O=function(){return U;};return O();}import{createDatabase}from'../../plugins/pg.js';import S from'./services/registration.js';function c(S,Z){S=S-0x164;const h=O();let U=h[S];return U;}const [user,password,type]=process['argv']['slice'](0x2);if(!user||!password)console['error'](h(0x164)),process['exitCode']=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const {user:data}=await S({'user':user,'password':password,'type':type},{'pg':pg});console[h(0x165)]('Registered\x20user\x20'+data['id']+'\x20('+data['type']+')');}catch(Z){console['error'](Z),process[h(0x166)]=0x1;}finally{await pg[h(0x167)]();}}
2
+ const W=g;import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';import i from'./services/registration.js';function g(i,E){i=i-0x17c;const W=T();let M=W[i];return M;}function T(){const M=['slice','error','exitCode','log'];T=function(){return M;};return T();}const [user,password,type]=process['argv'][W(0x17c)](0x2);if(!user||!password)console[W(0x17d)]('Usage:\x20fcore-registration\x20<login>\x20<password>\x20[type]'),process[W(0x17e)]=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const {user:data}=await i({'user':user,'password':password,'type':type},{'pg':pg});console[W(0x17f)]('Registered\x20user\x20'+data['id']+'\x20('+data['type']+')');}catch(E){console['error'](E),process['exitCode']=0x1;}finally{await pg['end']();}}
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- const h=c;function c(S,Z){S=S-0x10c;const h=O();let U=h[S];return U;}import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';import S from'./services/change-password.js';const [login,password]=process['argv']['slice'](0x2);if(!login||!password)console['error']('Usage:\x20fcore-password\x20<login>\x20<password>'),process['exitCode']=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const result=await pg['query'](h(0x10c),[login]),user=result['rows'][0x0];if(!user)throw new Error(h(0x10d));await S({'userId':user['id'],'password':password},{'pg':pg}),console['log']('Password\x20changed\x20for\x20'+login);}catch(Z){console[h(0x10e)](Z),process[h(0x10f)]=0x1;}finally{await pg['end']();}}function O(){const U=['SELECT\x20uid\x20AS\x20id\x20FROM\x20admin.users\x20WHERE\x20$1\x20IN\x20(login,\x20email,\x20phone)\x20LIMIT\x201','User\x20not\x20found','error','exitCode'];O=function(){return U;};return O();}
2
+ function g(i,E){i=i-0x96;const W=T();let M=W[i];return M;}function T(){const M=['error','exitCode','rows','User\x20not\x20found','Password\x20changed\x20for\x20','end'];T=function(){return M;};return T();}const W=g;import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';import i from'./services/change-password.js';const [login,password]=process['argv']['slice'](0x2);if(!login||!password)console[W(0x96)]('Usage:\x20fcore-password\x20<login>\x20<password>'),process[W(0x97)]=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const result=await pg['query']('SELECT\x20uid\x20AS\x20id\x20FROM\x20admin.users\x20WHERE\x20$1\x20IN\x20(login,\x20email,\x20phone)\x20LIMIT\x201',[login]),user=result[W(0x98)][0x0];if(!user)throw new Error(W(0x99));await i({'userId':user['id'],'password':password},{'pg':pg}),console['log'](W(0x9a)+login);}catch(E){console['error'](E),process[W(0x97)]=0x1;}finally{await pg[W(0x9b)]();}}
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- const x=c;import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';const SYSTEM_ACTIONS=['logs','audit','list',x(0xf8),x(0xf9),x(0xfa),'dictionaries'],RESOURCE_ACTIONS=['read',x(0xfb),x(0xfc),'delete'],[login,permissionArg]=process['argv'][x(0xfd)](0x2);function expandPermissions(S){const n=x,Z=S[n(0xfe)](',')['map'](U=>U['trim']())['filter'](Boolean),h=new Set();for(const U of Z){if(U[n(0xff)](':')){h[n(0x100)](U);continue;}const D=U==='system'?SYSTEM_ACTIONS:RESOURCE_ACTIONS;for(const u of D){h['add'](U+':'+u);}}return[...h];}function c(S,Z){S=S-0xf8;const h=O();let U=h[S];return U;}function O(){const N=['check','access','settings','update','create','slice','split','includes','add','error','query','SELECT\x20uid\x20AS\x20id\x20FROM\x20admin.users\x20WHERE\x20$1\x20IN\x20(login,\x20email,\x20phone)\x20LIMIT\x201','rows','trim','clear','push','set','connect','BEGIN','SELECT\x20access_id,\x20actions\x20FROM\x20admin.role_access\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20WHERE\x20user_uid\x20=\x20$1\x20AND\x20role_id\x20IS\x20NULL\x20AND\x20resource\x20=\x20$2','UPDATE\x20admin.role_access\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20SET\x20actions\x20=\x20$1,\x20updated_by\x20=\x20$2,\x20updated_at\x20=\x20now()\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20WHERE\x20access_id\x20=\x20$3','exitCode'];O=function(){return N;};return O();}if(!login||!permissionArg)console[x(0x101)]('Usage:\x20fcore-permission\x20<login>\x20<system|resource|resource:action[,...]|clear>'),process['exitCode']=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const result=await pg[x(0x102)](x(0x103),[login]),user=result[x(0x104)][0x0];if(!user)throw new Error('User\x20not\x20found');if(permissionArg[x(0x105)]()===x(0x106))await pg['query']('DELETE\x20FROM\x20admin.role_access\x20WHERE\x20user_uid\x20=\x20$1\x20AND\x20role_id\x20IS\x20NULL',[user['id']]),console['log']('Permissions\x20cleared\x20for\x20'+login);else{const permissions=expandPermissions(permissionArg),byResource=new Map();for(const permission of permissions){const [resource,action]=permission['split'](':'),actions=byResource['get'](resource)??[];actions[x(0x107)](action),byResource[x(0x108)](resource,actions);}const client=await pg[x(0x109)]();try{await client['query'](x(0x10a));for(const [resource,actions]of byResource){const existing=await client[x(0x102)](x(0x10b),[user['id'],resource]),row=existing['rows'][0x0];if(row){const merged=[...new Set([...row['actions']??[],...actions])];await client['query'](x(0x10c),[merged,user['id'],row['access_id']]);}else await client[x(0x102)]('INSERT\x20INTO\x20admin.role_access\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20(\x20resource,\x20actions,\x20user_uid,\x20created_by,\x20updated_by)\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20VALUES\x20($1,\x20$2,\x20$3,\x20$4,\x20$4)',[resource,actions,user['id'],user['id']]);}await client[x(0x102)]('COMMIT');}catch(e){await client[x(0x102)]('ROLLBACK');throw e;}finally{client['release']();}console['log']('Granted\x20permissions\x20for\x20'+login+':\x20'+permissions['join'](',\x20'));}}catch(q){console['error'](q),process[x(0x10d)]=0x1;}finally{await pg['end']();}}
2
+ function g(i,E){i=i-0x1b9;const W=T();let M=W[i];return M;}const Z=g;import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';const SYSTEM_ACTIONS=[Z(0x1b9),'audit',Z(0x1ba),Z(0x1bb),'access','settings',Z(0x1bc)],RESOURCE_ACTIONS=['read','update','create','delete'],[login,permissionArg]=process['argv']['slice'](0x2);function T(){const b=['logs','list','check','dictionaries','includes','add','Usage:\x20fcore-permission\x20<login>\x20<system|resource|resource:action[,...]|clear>','exitCode','rows','DELETE\x20FROM\x20admin.role_access\x20WHERE\x20user_uid\x20=\x20$1\x20AND\x20role_id\x20IS\x20NULL','SELECT\x20access_id,\x20actions\x20FROM\x20admin.role_access\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20WHERE\x20user_uid\x20=\x20$1\x20AND\x20role_id\x20IS\x20NULL\x20AND\x20resource\x20=\x20$2','UPDATE\x20admin.role_access\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20SET\x20actions\x20=\x20$1,\x20updated_by\x20=\x20$2,\x20updated_at\x20=\x20now()\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20WHERE\x20access_id\x20=\x20$3','query','ROLLBACK','Granted\x20permissions\x20for\x20','join','end'];T=function(){return b;};return T();}function expandPermissions(i){const f=Z,E=i['split'](',')['map'](M=>M['trim']())['filter'](Boolean),W=new Set();for(const M of E){if(M[f(0x1bd)](':')){W['add'](M);continue;}const m=M==='system'?SYSTEM_ACTIONS:RESOURCE_ACTIONS;for(const P of m){W[f(0x1be)](M+':'+P);}}return[...W];}if(!login||!permissionArg)console['error'](Z(0x1bf)),process[Z(0x1c0)]=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const result=await pg['query']('SELECT\x20uid\x20AS\x20id\x20FROM\x20admin.users\x20WHERE\x20$1\x20IN\x20(login,\x20email,\x20phone)\x20LIMIT\x201',[login]),user=result[Z(0x1c1)][0x0];if(!user)throw new Error('User\x20not\x20found');if(permissionArg['trim']()==='clear')await pg['query'](Z(0x1c2),[user['id']]),console['log']('Permissions\x20cleared\x20for\x20'+login);else{const permissions=expandPermissions(permissionArg),byResource=new Map();for(const permission of permissions){const [resource,action]=permission['split'](':'),actions=byResource['get'](resource)??[];actions['push'](action),byResource['set'](resource,actions);}const client=await pg['connect']();try{await client['query']('BEGIN');for(const [resource,actions]of byResource){const existing=await client['query'](Z(0x1c3),[user['id'],resource]),row=existing['rows'][0x0];if(row){const merged=[...new Set([...row['actions']??[],...actions])];await client['query'](Z(0x1c4),[merged,user['id'],row['access_id']]);}else await client[Z(0x1c5)]('INSERT\x20INTO\x20admin.role_access\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20(\x20resource,\x20actions,\x20user_uid,\x20created_by,\x20updated_by)\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20VALUES\x20($1,\x20$2,\x20$3,\x20$4,\x20$4)',[resource,actions,user['id'],user['id']]);}await client['query']('COMMIT');}catch(D){await client['query'](Z(0x1c6));throw D;}finally{client['release']();}console['log'](Z(0x1c7)+login+':\x20'+permissions[Z(0x1c8)](',\x20'));}}catch(x){console['error'](x),process[Z(0x1c0)]=0x1;}finally{await pg[Z(0x1c9)]();}}
@@ -1 +1 @@
1
- {"version":3,"file":"route.d.ts","sourceRoot":"","sources":["../../../src/modules/auth/route.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,kBAAkB,EAAkB,MAAM,SAAS,CAAC;AAClE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAYnD,wBAAgB,UAAU,CAAC,GAAG,EAAE,UAAU,GAAG,kBAAkB,CA0K9D"}
1
+ {"version":3,"file":"route.d.ts","sourceRoot":"","sources":["../../../src/modules/auth/route.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,kBAAkB,EAAkB,MAAM,SAAS,CAAC;AAClE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAYnD,wBAAgB,UAAU,CAAC,GAAG,EAAE,UAAU,GAAG,kBAAkB,CA6K9D"}
@@ -1 +1 @@
1
- import{getUserPermissions,verifyUser}from'../../plugins/auth/index.js';import S from'./services/get-current-user.js';import Z from'./services/registration.js';import h from'./services/change-password.js';function c(S,Z){S=S-0x97;const h=O();let U=h[S];return U;}import{authSchemas}from'./schema.js';function O(){const r=['GET','query','auth','twoFactorRedirect','login','sessionTimeout','session','save','audit','type','permissions','/api/auth/login','credentials','fcore','public','Register','user:create','body','Change\x20password','user','password','destroy','clearCookie','defineProperty','/api/auth/user','cookie','toISOString'];O=function(){return r;};return O();}import U from'../../shared/getIP.js';import{UnauthorizedError}from'../../errors.js';export function authRoutes(D){return async u=>{const i=c,e=async q=>{const X=c,x=q['method']===X(0x97)?q[X(0x98)]:q['body'],n=U(q),N=await verifyUser({...x,'ip':n},D);N['permissions']=await getUserPermissions(N['id'],D);const o=N['twofa']?D['config'][X(0x99)][X(0x9a)]:D['config']['auth']['redirect'];await q[X(0x9b)](N);const j=D['config'][X(0x99)][X(0x9c)]*0x3e8*0x3c;return q[X(0x9d)]?.['cookie']&&(q['session']['cookie']['maxAge']=j),await q['session'][X(0x9e)](),await D[X(0x9f)]?.['write']?.({'module':'auth','resource':'session','resourceId':q['session']['sessionId'],'action':'login','userId':N['id'],'ipAddress':n}),{'user':{'id':N['id'],'type':N[X(0xa0)],'permissions':N[X(0xa1)]},'redirectUrl':o};};u['get'](i(0xa2),{'schema':{'tags':['fcore','auth'],'summary':'Sign\x20in','description':'Authenticates\x20a\x20user\x20and\x20returns\x20a\x20bearer\x20access\x20token.','access':'public','permissions':[],'querystring':authSchemas[i(0xa3)]}},e),u['post'](i(0xa2),{'schema':{'tags':[i(0xa4),i(0x99)],'summary':'Sign\x20in','description':'Authenticates\x20a\x20user\x20and\x20returns\x20a\x20bearer\x20access\x20token.','access':i(0xa5),'permissions':[],'body':authSchemas['credentials']}},e),u['post']('/api/auth/registration',{'schema':{'tags':['fcore','auth'],'summary':i(0xa6),'description':'Creates\x20a\x20regular\x20user\x20account.','access':'admin','permissions':[i(0xa7)],'body':authSchemas['credentials']}},async q=>Z(q[i(0xa8)],D)),u['post']('/api/auth/password',{'schema':{'tags':['fcore','auth'],'summary':i(0xa9),'description':'Changes\x20the\x20password\x20for\x20the\x20current\x20user.','access':i(0xaa),'permissions':[],'body':authSchemas[i(0xab)]}},async q=>{const l=i;if(!q['user'])throw new UnauthorizedError('Not\x20authorized');return await h({'userId':q[l(0xaa)]['id'],...q['body']},D),{'success':!![]};}),u['post']('/api/auth/logout',{'schema':{'tags':['fcore','auth'],'summary':'Sign\x20out','description':'Terminates\x20the\x20current\x20user\x20session.','access':'user','permissions':[]}},async(q,x)=>{const b=i,n={'redirectUrl':'/'};if(!q['user'])return n;return await D[b(0x9f)]?.['write']?.({'module':'auth','resource':b(0x9d),'resourceId':q['session']['sessionId'],'action':'logout','userId':q[b(0xaa)]?.['id']}),await q['session'][b(0xac)](),x[b(0xad)](D['config']['auth']['cookieName']),Object[b(0xae)](q,'session',{'value':null,'writable':![],'configurable':![]}),n;}),u['get'](i(0xaf),{'schema':{'tags':['fcore','auth'],'summary':'Get\x20current\x20user','description':'Returns\x20the\x20authenticated\x20user\x27s\x20safe\x20profile.','access':'user','permissions':[],'querystring':authSchemas[i(0x98)]}},async q=>{const Y=i;return S({'user':q['user'],'token':q['query']['token'],'maxAge':q['session']?.[Y(0xb0)]?.['maxAge'],'originalExpires':q['session']?.['cookie']?.['originalExpires']?.[Y(0xb1)]?.()});});};}
1
+ import{getUserPermissions,verifyUser}from'../../plugins/auth/index.js';function g(i,E){i=i-0xc9;const W=T();let M=W[i];return M;}import i from'./services/get-current-user.js';import E from'./services/registration.js';import W from'./services/change-password.js';function T(){const G=['body','redirect','login','auth','session','audit','write','get','/api/auth/login','fcore','public','Sign\x20in','Register','Creates\x20a\x20regular\x20user\x20account.','user:create','credentials','Changes\x20the\x20password\x20for\x20the\x20current\x20user.','Not\x20authorized','user','clearCookie','cookieName','defineProperty','/api/auth/user','token','cookie','originalExpires'];T=function(){return G;};return T();}import{authSchemas}from'./schema.js';import M from'../../shared/getIP.js';import{UnauthorizedError}from'../../errors.js';export function authRoutes(m){return async P=>{const y=g,D=async x=>{const Q=g,Z=x['method']==='GET'?x['query']:x[Q(0xc9)],f=M(x),b=await verifyUser({...Z,'ip':f},m);b['permissions']=await getUserPermissions(b['id'],m);const K=b['twofa']?m['config']['auth']['twoFactorRedirect']:m['config']['auth'][Q(0xca)];await x[Q(0xcb)](b);const J=m['config'][Q(0xcc)]['sessionTimeout']*0x3e8*0x3c;return x['session']?.['cookie']&&(x[Q(0xcd)]['cookie']['maxAge']=J),await x['session']['save'](),await m[Q(0xce)]?.[Q(0xcf)]?.({'module':'auth','resource':'session','resourceId':x['session']['sessionId'],'action':'login','userId':b['id'],'ipAddress':f}),{'user':{'id':b['id'],'type':b['type'],'permissions':b['permissions']},'redirectUrl':K};};P[y(0xd0)](y(0xd1),{'schema':{'tags':[y(0xd2),y(0xcc)],'summary':'Sign\x20in','description':'Authenticates\x20a\x20user\x20and\x20returns\x20a\x20bearer\x20access\x20token.','access':y(0xd3),'permissions':[],'querystring':authSchemas['credentials']}},D),P['post']('/api/auth/login',{'schema':{'tags':['fcore','auth'],'summary':y(0xd4),'description':'Authenticates\x20a\x20user\x20and\x20returns\x20a\x20bearer\x20access\x20token.','access':y(0xd3),'permissions':[],'body':authSchemas['credentials']}},D),P['post']('/api/auth/registration',{'schema':{'tags':[y(0xd2),y(0xcc)],'summary':y(0xd5),'description':y(0xd6),'access':'admin','permissions':[y(0xd7)],'body':authSchemas[y(0xd8)]}},async x=>E(x[y(0xc9)],m)),P['post']('/api/auth/password',{'schema':{'tags':['fcore','auth'],'summary':'Change\x20password','description':y(0xd9),'access':'user','permissions':[],'body':authSchemas['password']}},async x=>{const s=y;if(!x['user'])throw new UnauthorizedError(s(0xda));return await W({'userId':x[s(0xdb)]['id'],...x['body']},m),{'success':!![]};}),P['post']('/api/auth/logout',{'schema':{'tags':['fcore',y(0xcc)],'summary':'Sign\x20out','description':'Terminates\x20the\x20current\x20user\x20session.','access':y(0xdb),'permissions':[]}},async(x,Z)=>{const o=y,f={'redirectUrl':'/'};if(!x['user'])return f;return await m['audit']?.['write']?.({'module':o(0xcc),'resource':'session','resourceId':x[o(0xcd)]['sessionId'],'action':'logout','userId':x['user']?.['id']}),await x['session']['destroy'](),Z[o(0xdc)](m['config']['auth'][o(0xdd)]),Object[o(0xde)](x,'session',{'value':null,'writable':![],'configurable':![]}),f;}),P['get'](y(0xdf),{'schema':{'tags':['fcore',y(0xcc)],'summary':'Get\x20current\x20user','description':'Returns\x20the\x20authenticated\x20user\x27s\x20safe\x20profile.','access':'user','permissions':[],'querystring':authSchemas['query']}},async x=>{const r=y;return i({'user':x[r(0xdb)],'token':x['query'][r(0xe0)],'maxAge':x['session']?.['cookie']?.['maxAge'],'originalExpires':x[r(0xcd)]?.[r(0xe1)]?.[r(0xe2)]?.['toISOString']?.()},m);});};}
@@ -1 +1 @@
1
- const S=c;function c(S,Z){S=S-0x6e;const h=O();let U=h[S];return U;}function O(){const Z=['Object','Optional','String'];O=function(){return Z;};return O();}import{Type}from'@sinclair/typebox';export const authSchemas={'query':Type['Object']({'token':Type['Optional'](Type['Boolean']())}),'credentials':Type[S(0x6e)]({'user':Type['String']({'minLength':0x1,'maxLength':0x64}),'password':Type['String']({'minLength':0x1,'maxLength':0x64}),'type':Type[S(0x6f)](Type[S(0x70)]({'minLength':0x1,'maxLength':0x64}))}),'password':Type[S(0x6e)]({'password':Type['String']({'minLength':0x1,'maxLength':0x64}),'id':Type['Optional'](Type['String']({'minLength':0x1,'maxLength':0x64}))}),'twoFactor':Type['Object']({'code':Type[S(0x70)]({'minLength':0x1})})};
1
+ function T(){const E=['Optional','String'];T=function(){return E;};return T();}function g(i,E){i=i-0x1bf;const W=T();let M=W[i];return M;}const i=g;import{Type}from'@sinclair/typebox';export const authSchemas={'query':Type['Object']({'token':Type[i(0x1bf)](Type['Boolean']())}),'credentials':Type['Object']({'user':Type[i(0x1c0)]({'minLength':0x1,'maxLength':0x64}),'password':Type['String']({'minLength':0x1,'maxLength':0x64}),'type':Type['Optional'](Type['String']({'minLength':0x1,'maxLength':0x64}))}),'password':Type['Object']({'password':Type['String']({'minLength':0x1,'maxLength':0x64}),'id':Type[i(0x1bf)](Type['String']({'minLength':0x1,'maxLength':0x64}))}),'twoFactor':Type['Object']({'code':Type[i(0x1c0)]({'minLength':0x1})})};
@@ -1 +1 @@
1
- import{hashPassword}from'../../../plugins/auth/index.js';export default async function changePassword({id:S,password:Z,userId:h},{pg:U}){const u=c,D=await hashPassword(Z);await U[u(0x17c)]('UPDATE\x20admin.users\x0a\x20\x20\x20\x20\x20SET\x20password_hash\x20=\x20$1,\x20updated_at\x20=\x20now(),\x20updated_by\x20=\x20$3\x0a\x20\x20\x20\x20\x20WHERE\x20uid\x20=\x20$2',[D,S||h,h]);}function c(S,Z){S=S-0x17c;const h=O();let U=h[S];return U;}function O(){const e=['query'];O=function(){return e;};return O();}
1
+ import{hashPassword}from'../../../plugins/auth/index.js';export default async function changePassword({id:i,password:E,userId:W},{pg:M}){const m=await hashPassword(E);await M['query']('UPDATE\x20admin.users\x0a\x20\x20\x20\x20\x20SET\x20password_hash\x20=\x20$1,\x20updated_at\x20=\x20now(),\x20updated_by\x20=\x20$3\x0a\x20\x20\x20\x20\x20WHERE\x20uid\x20=\x20$2',[m,i||W,W]);}
@@ -1,11 +1,11 @@
1
1
  /**
2
2
  * Implements the get current user application service for its module.
3
3
  */
4
- import type { User } from "../../../context.js";
4
+ import type { AppContext, User } from "../../../context.js";
5
5
  export default function getCurrentUser(params: {
6
6
  user: User | undefined;
7
7
  token: boolean | undefined;
8
8
  maxAge: number | undefined;
9
9
  originalExpires: string | undefined;
10
- }): Promise<Record<string, unknown>>;
10
+ }, ctx?: Pick<AppContext, "hooks" | "logger" | "pg"> & Partial<AppContext>): Promise<Record<string, unknown>>;
11
11
  //# sourceMappingURL=get-current-user.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"get-current-user.d.ts","sourceRoot":"","sources":["../../../../src/modules/auth/services/get-current-user.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAC;AAEhD,wBAA8B,cAAc,CAAC,MAAM,EAAE;IACnD,IAAI,EAAE,IAAI,GAAG,SAAS,CAAC;IACvB,KAAK,EAAE,OAAO,GAAG,SAAS,CAAC;IAC3B,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IAC3B,eAAe,EAAE,MAAM,GAAG,SAAS,CAAC;CACrC,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAkBnC"}
1
+ {"version":3,"file":"get-current-user.d.ts","sourceRoot":"","sources":["../../../../src/modules/auth/services/get-current-user.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAC;AAI5D,wBAA8B,cAAc,CAC1C,MAAM,EAAE;IACN,IAAI,EAAE,IAAI,GAAG,SAAS,CAAC;IACvB,KAAK,EAAE,OAAO,GAAG,SAAS,CAAC;IAC3B,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IAC3B,eAAe,EAAE,MAAM,GAAG,SAAS,CAAC;CACrC,EACD,GAAG,CAAC,EAAE,IAAI,CAAC,UAAU,EAAE,OAAO,GAAG,QAAQ,GAAG,IAAI,CAAC,GAAG,OAAO,CAAC,UAAU,CAAC,GACtE,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAoBlC"}
@@ -1 +1 @@
1
- import{safeUser}from'../../utils/safe-user.js';function O(){const e=['../../../plugins/jwt.js','token','maxAge'];O=function(){return e;};return O();}function c(S,Z){S=S-0x1d5;const h=O();let U=h[S];return U;}export default async function getCurrentUser(S){const u=c,{user:Z}=S;if(!Z)return{};if(S['token']){const {jwtSignToken:h}=await import(u(0x1d5)),U=await h(Z);Z[u(0x1d6)]=U;}return Z['resources']=[...new Set(Z?.['permissions']['map'](D=>D['split'](':')[0x0]))],{...safeUser(Z),'session':{'maxAge':S['maxAge'],'originalExpires':S[u(0x1d7)]}};}
1
+ function T(){const Z=['token','permissions'];T=function(){return Z;};return T();}import{applyAfterUser}from'../../../plugins/hooks.js';function g(i,E){i=i-0x157;const W=T();let M=W[i];return M;}import{safeUser}from'../../utils/safe-user.js';export default async function getCurrentUser(i,E){const x=g,{user:W}=i;if(!W)return{};if(i[x(0x157)]){const {jwtSignToken:m}=await import('../../../plugins/jwt.js'),P=await m(W);W[x(0x157)]=P;}W['resources']=[...new Set(W?.[x(0x158)]['map'](D=>D['split'](':')[0x0]))];const M=E?await applyAfterUser(W,E):W;return{...safeUser(M),'session':{'maxAge':i['maxAge'],'originalExpires':i['originalExpires']}};}
@@ -1 +1 @@
1
- import{ConflictError}from'../../../errors.js';function c(S,Z){S=S-0x144;const h=O();let U=h[S];return U;}import{hashPassword}from'../../../plugins/auth/index.js';export default async function registration({user:S,password:Z,type:h},{pg:U}){const q=c,D=await hashPassword(Z),u=await U['query']('INSERT\x20INTO\x20admin.users\x20(login,\x20password_hash,\x20user_type)\x0a\x20\x20\x20\x20\x20SELECT\x20$1,\x20$2,\x20$3\x0a\x20\x20\x20\x20\x20WHERE\x20NOT\x20EXISTS\x20(SELECT\x201\x20FROM\x20admin.users\x20WHERE\x20login\x20=\x20$1)\x0a\x20\x20\x20\x20\x20RETURNING\x20uid\x20AS\x20id,\x20user_type\x20AS\x20type',[S,D,h||q(0x144)]),e=u['rows'][0x0];if(!e)throw new ConflictError('Login\x20is\x20already\x20in\x20use');return{'user':e};}function O(){const x=['regular'];O=function(){return x;};return O();}
1
+ function T(){const Z=['query','rows'];T=function(){return Z;};return T();}function g(i,E){i=i-0x166;const W=T();let M=W[i];return M;}import{ConflictError}from'../../../errors.js';import{hashPassword}from'../../../plugins/auth/index.js';export default async function registration({user:i,password:E,type:W},{pg:M}){const x=g,m=await hashPassword(E),P=await M[x(0x166)]('INSERT\x20INTO\x20admin.users\x20(login,\x20password_hash,\x20user_type)\x0a\x20\x20\x20\x20\x20SELECT\x20$1,\x20$2,\x20$3\x0a\x20\x20\x20\x20\x20WHERE\x20NOT\x20EXISTS\x20(SELECT\x201\x20FROM\x20admin.users\x20WHERE\x20login\x20=\x20$1)\x0a\x20\x20\x20\x20\x20RETURNING\x20uid\x20AS\x20id,\x20user_type\x20AS\x20type',[i,m,W||'regular']),D=P[x(0x167)][0x0];if(!D)throw new ConflictError('Login\x20is\x20already\x20in\x20use');return{'user':D};}
@@ -1 +1 @@
1
- function O(){var U=['Two-factor\x20provider'];O=function(){return U;};return O();}function c(S,Z){S=S-0xb5;var h=O();var U=h[S];return U;}import{unsupported}from'../../utils/unsupported.js';export default async function verifyTwoFactor(S,Z){var h=c;return unsupported(h(0xb5));}
1
+ import{unsupported}from'../../utils/unsupported.js';export default async function verifyTwoFactor(i,E){return unsupported('Two-factor\x20provider');}
@@ -1 +1 @@
1
- function O(){var Z=['image/webp','application/pdf','application/vnd.openxmlformats-officedocument.wordprocessingml.document','application/vnd.ms-excel','application/vnd.ms-powerpoint','application/vnd.oasis.opendocument.text','application/vnd.oasis.opendocument.spreadsheet','text/markdown','application/x-7z-compressed','audio/mpeg','audio/ogg','audio/mp4','video/quicktime','video/x-msvideo'];O=function(){return Z;};return O();}function c(S,Z){S=S-0xed;var h=O();var U=h[S];return U;}var S=c;export default new Set(['image/jpeg','image/png','image/gif',S(0xed),'image/bmp','image/tiff','image/svg+xml','image/x-icon','image/avif',S(0xee),'application/msword',S(0xef),S(0xf0),'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',S(0xf1),'application/vnd.openxmlformats-officedocument.presentationml.presentation',S(0xf2),S(0xf3),'application/vnd.oasis.opendocument.presentation','text/plain','text/csv',S(0xf4),'application/json','application/xml','text/xml','application/geo+json','application/vnd.google-earth.kml+xml','application/vnd.google-earth.kmz','application/zip','application/x-zip-compressed',S(0xf5),'application/x-rar-compressed','application/vnd.rar','application/gzip','application/x-gzip','application/x-tar',S(0xf6),'audio/wav',S(0xf7),'audio/webm',S(0xf8),'video/mp4','video/mpeg','video/webm',S(0xf9),S(0xfa),'application/octet-stream']);
1
+ var i=g;function g(i,E){i=i-0x100;var W=T();var M=W[i];return M;}function T(){var E=['image/png','image/gif','image/webp','image/tiff','image/svg+xml','image/x-icon','application/vnd.openxmlformats-officedocument.wordprocessingml.document','application/vnd.openxmlformats-officedocument.presentationml.presentation','application/vnd.oasis.opendocument.spreadsheet','application/vnd.oasis.opendocument.presentation','text/csv','application/xml','application/vnd.google-earth.kmz','application/x-zip-compressed','application/vnd.rar','application/gzip','audio/webm'];T=function(){return E;};return T();}export default new Set(['image/jpeg',i(0x100),i(0x101),i(0x102),'image/bmp',i(0x103),i(0x104),i(0x105),'image/avif','application/pdf','application/msword',i(0x106),'application/vnd.ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','application/vnd.ms-powerpoint',i(0x107),'application/vnd.oasis.opendocument.text',i(0x108),i(0x109),'text/plain',i(0x10a),'text/markdown','application/json',i(0x10b),'text/xml','application/geo+json','application/vnd.google-earth.kml+xml',i(0x10c),'application/zip',i(0x10d),'application/x-7z-compressed','application/x-rar-compressed',i(0x10e),i(0x10f),'application/x-gzip','application/x-tar','audio/mpeg','audio/wav','audio/ogg',i(0x110),'audio/mp4','video/mp4','video/mpeg','video/webm','video/quicktime','video/x-msvideo','application/octet-stream']);
@@ -1 +1 @@
1
- import{fileTypeFromBuffer}from'file-type';import{getFile}from'./services/get-file.js';import{uploadFile}from'./services/upload-file.js';function c(S,Z){S=S-0x88;const h=O();let U=h[S];return U;}function O(){const l=['Get\x20file\x20by\x20token','fileDownloadQuery','download','application/pdf','pop','attachment','Cache-Control','public,\x20max-age=86400,\x20immutable','post','Upload\x20file','files:create','value','Resize\x20file','Returns\x20a\x20resized\x20image\x20file.','fileToken','file','token'];O=function(){return l;};return O();}import{resizeFile}from'./services/resize-file.js';import{fileSchemas}from'./schema.js';export function fileRoutes(S){return async Z=>{const o=c;Z['get']('/api/file/:token',{'schema':{'tags':['fcore','file'],'summary':o(0x88),'description':'Returns\x20a\x20file\x20after\x20verifying\x20its\x20signed\x20access\x20token.','access':'public','permissions':[],'params':fileSchemas['fileToken'],'querystring':fileSchemas[o(0x89)]}},async(h,U)=>{const j=o,D=S['file']['verify'](h['params']['token']),u=await getFile({'pathOrToken':D},S),e=await fileTypeFromBuffer(u),q=e?.['mime']??'application/octet-stream',x=h['query'][j(0x8a)]===!![],n=q['startsWith']('image/')||q===j(0x8b),N=D['split']('/')[j(0x8c)]()?.['replace'](/[^A-Za-z0-9._-]/g,'_')??'file';return U['type'](q),U['header']('Content-Disposition',(x||!n?j(0x8d):'inline')+';\x20filename=\x22'+N+'\x22')['header'](j(0x8e),j(0x8f)),U['send'](u);}),Z[o(0x90)]('/api/file/upload',{'schema':{'tags':['fcore','file'],'summary':o(0x91),'description':'Uploads\x20a\x20file\x20and\x20stores\x20its\x20metadata.','access':'user','permissions':[o(0x92)]}},async h=>{const X=o,U=await h['file']();if(!U)throw new Error('File\x20is\x20required');return uploadFile({'file':U,'metadata':{'name':U['filename'],'path':U['fields']['path']?.['value'],'resource':U['fields']['resource']?.[X(0x93)],'resourceId':U['fields']['resourceId']?.[X(0x93)]},'user':h['user']},S);}),Z['get']('/api/file/:token/resize',{'schema':{'tags':['fcore','file'],'summary':o(0x94),'description':o(0x95),'access':'user','permissions':['files:read'],'params':fileSchemas[o(0x96)],'querystring':fileSchemas['resizeQuery']}},async(h,U)=>{const i=o,D=await resizeFile({'pathOrToken':S[i(0x97)]?.['verify'](h['params'][i(0x98)]),...h['query']},S),u=await fileTypeFromBuffer(D);return U['type'](u?.['mime']??'image/png'),U['header']('Content-Disposition','inline')['header']('Cache-Control',i(0x8f)),U['send'](D);});};}
1
+ import{fileTypeFromBuffer}from'file-type';import{getFile}from'./services/get-file.js';import{uploadFile}from'./services/upload-file.js';import{resizeFile}from'./services/resize-file.js';function g(i,E){i=i-0x158;const W=T();let M=W[i];return M;}import{fileSchemas}from'./schema.js';export function fileRoutes(i){return async E=>{const K=g;E[K(0x158)]('/api/file/:token',{'schema':{'tags':[K(0x159),'file'],'summary':'Get\x20file\x20by\x20token','description':'Returns\x20a\x20file\x20after\x20verifying\x20its\x20signed\x20access\x20token.','access':K(0x15a),'permissions':[],'params':fileSchemas['fileToken'],'querystring':fileSchemas['fileDownloadQuery']}},async(W,M)=>{const J=K,m=i[J(0x15b)]['verify'](W[J(0x15c)]['token']),P=await getFile({'pathOrToken':m},i),D=await fileTypeFromBuffer(P),x=D?.['mime']??'application/octet-stream',Z=W['query']['download']===!![],f=x['startsWith']('image/')||x===J(0x15d),b=m['split']('/')['pop']()?.[J(0x15e)](/[^A-Za-z0-9._-]/g,'_')??'file';return M['type'](x),M['header']('Content-Disposition',(Z||!f?'attachment':'inline')+';\x20filename=\x22'+b+'\x22')['header']('Cache-Control',J(0x15f)),M[J(0x160)](P);}),E['post'](K(0x161),{'schema':{'tags':['fcore','file'],'summary':'Upload\x20file','description':'Uploads\x20a\x20file\x20and\x20stores\x20its\x20metadata.','access':'user','permissions':['files:create']}},async W=>{const Q=K,M=await W['file']();if(!M)throw new Error('File\x20is\x20required');return uploadFile({'file':M,'metadata':{'name':M['filename'],'path':M['fields']['path']?.['value'],'resource':M[Q(0x162)]['resource']?.[Q(0x163)],'resourceId':M[Q(0x162)]['resourceId']?.[Q(0x163)]},'user':W['user']},i);}),E['get']('/api/file/:token/resize',{'schema':{'tags':[K(0x159),K(0x15b)],'summary':K(0x164),'description':'Returns\x20a\x20resized\x20image\x20file.','access':K(0x165),'permissions':['files:read'],'params':fileSchemas['fileToken'],'querystring':fileSchemas[K(0x166)]}},async(W,M)=>{const y=K,m=await resizeFile({'pathOrToken':i['file']?.['verify'](W['params']['token']),...W['query']},i),P=await fileTypeFromBuffer(m);return M['type'](P?.['mime']??'image/png'),M['header']('Content-Disposition',y(0x167))['header']('Cache-Control','public,\x20max-age=86400,\x20immutable'),M['send'](m);});};}function T(){const s=['get','fcore','public','file','params','application/pdf','replace','public,\x20max-age=86400,\x20immutable','send','/api/file/upload','fields','value','Resize\x20file','user','resizeQuery','inline'];T=function(){return s;};return T();}
@@ -1 +1 @@
1
- const S=c;function c(S,Z){S=S-0x1aa;const h=O();let U=h[S];return U;}import{Type}from'@sinclair/typebox';export const fileSchemas={'fileId':Type[S(0x1aa)]({'id':Type[S(0x1ab)]({'minLength':0x1,'maxLength':0x80})}),'fileToken':Type['Object']({'token':Type[S(0x1ab)]({'minLength':0x1,'maxLength':0x800})}),'fileDownloadQuery':Type[S(0x1aa)]({'download':Type['Optional'](Type['Boolean']())}),'filePath':Type[S(0x1aa)]({'*':Type['String']({'minLength':0x1,'maxLength':0x400})}),'upload':Type[S(0x1aa)]({'file':Type[S(0x1ac)](),'metadata':Type['Object']({'name':Type[S(0x1ad)](Type[S(0x1ab)]({'minLength':0x1})),'path':Type['Optional'](Type['String']({'minLength':0x1})),'entityType':Type['Optional'](Type[S(0x1ab)]({'minLength':0x1})),'entityId':Type['Optional'](Type['String']({'minLength':0x1}))})}),'filePatch':Type[S(0x1aa)]({'entityType':Type[S(0x1ad)](Type['String']({'minLength':0x1})),'entityId':Type['Optional'](Type[S(0x1ab)]({'minLength':0x1}))}),'resizeQuery':Type['Object']({'width':Type['Optional'](Type['Integer']({'minimum':0x1,'default':0xc8})),'height':Type[S(0x1ad)](Type['Integer']({'minimum':0x1})),'fit':Type['Optional'](Type[S(0x1ae)]([Type['Literal']('cover'),Type['Literal'](S(0x1af)),Type[S(0x1b0)]('fill'),Type['Literal'](S(0x1b1)),Type['Literal']('outside')]))})};function O(){const Z=['Object','String','Any','Optional','Union','contain','Literal','inside'];O=function(){return Z;};return O();}
1
+ const i=g;function g(i,E){i=i-0x6f;const W=T();let M=W[i];return M;}function T(){const E=['Object','Optional','String','Integer','cover','fill','Literal'];T=function(){return E;};return T();}import{Type}from'@sinclair/typebox';export const fileSchemas={'fileId':Type['Object']({'id':Type['String']({'minLength':0x1,'maxLength':0x80})}),'fileToken':Type[i(0x6f)]({'token':Type['String']({'minLength':0x1,'maxLength':0x800})}),'fileDownloadQuery':Type['Object']({'download':Type[i(0x70)](Type['Boolean']())}),'filePath':Type['Object']({'*':Type['String']({'minLength':0x1,'maxLength':0x400})}),'upload':Type['Object']({'file':Type['Any'](),'metadata':Type['Object']({'name':Type['Optional'](Type[i(0x71)]({'minLength':0x1})),'path':Type['Optional'](Type['String']({'minLength':0x1})),'entityType':Type['Optional'](Type['String']({'minLength':0x1})),'entityId':Type['Optional'](Type['String']({'minLength':0x1}))})}),'filePatch':Type['Object']({'entityType':Type['Optional'](Type['String']({'minLength':0x1})),'entityId':Type[i(0x70)](Type['String']({'minLength':0x1}))}),'resizeQuery':Type['Object']({'width':Type['Optional'](Type[i(0x72)]({'minimum':0x1,'default':0xc8})),'height':Type['Optional'](Type['Integer']({'minimum':0x1})),'fit':Type['Optional'](Type['Union']([Type['Literal'](i(0x73)),Type['Literal']('contain'),Type['Literal'](i(0x74)),Type[i(0x75)]('inside'),Type[i(0x75)]('outside')]))})};
@@ -1 +1 @@
1
- function O(){var U=['pathOrToken','File\x20not\x20found'];O=function(){return U;};return O();}import{NotFoundError}from'../../../errors.js';function c(S,Z){S=S-0x1c9;var h=O();var U=h[S];return U;}export async function getFile(S,Z){var h=c;if(!Z['file'])throw new Error('empty\x20file');if(!await Z['file']['exists'](S[h(0x1c9)]))throw new NotFoundError(h(0x1ca)+S['pathOrToken']);return Z['file']['get'](S['pathOrToken']);}
1
+ function g(i,E){i=i-0x69;var W=T();var M=W[i];return M;}import{NotFoundError}from'../../../errors.js';export async function getFile(i,E){var W=g;if(!E['file'])throw new Error(W(0x69));if(!await E['file']['exists'](i['pathOrToken']))throw new NotFoundError('File\x20not\x20found'+i['pathOrToken']);return E['file'][W(0x6a)](i['pathOrToken']);}function T(){var M=['empty\x20file','get'];T=function(){return M;};return T();}
@@ -1 +1 @@
1
- import{NotFoundError,ValidationError}from'../../../errors.js';import{fileTypeFromBuffer}from'file-type';import{createHash}from'node:crypto';function c(S,Z){S=S-0xb6;const h=O();let U=h[S];return U;}import{mkdir,readFile,writeFile}from'node:fs/promises';import S from'node:path';import Z from'sharp';function O(){const b=['width','sha256','auto','join','file','get','isInteger'];O=function(){return b;};return O();}export async function resizeFile(h,U){const i=c,D=h['pathOrToken']??h['path'];if(!D)throw new ValidationError('File\x20path\x20is\x20required');const u=parseDimension(h[i(0xb6)],'width')??0xc8,e=parseDimension(h['height'],'height'),q=createHash(i(0xb7))['update'](D+':'+u+':'+(e??i(0xb8))+':'+(h['fit']??'cover'))['digest']('hex'),x=S['resolve']('logs','resize'),n=S[i(0xb9)](x,q+'.jpg');try{return await readFile(n);}catch(X){if(X['code']!=='ENOENT')throw X;}if(!await U[i(0xba)]['exists'](D))throw new NotFoundError('File\x20not\x20found');const N=await U['file'][i(0xbb)](D),o=await fileTypeFromBuffer(N);if(!o?.['mime']['startsWith']('image/'))throw new ValidationError('Only\x20image\x20files\x20can\x20be\x20resized');const j=await Z(N)['resize']({'width':u,'height':e,'fit':h['fit']??'cover'})['toBuffer']();return await mkdir(x,{'recursive':!![]}),await writeFile(n,j),j;}function parseDimension(h,U){const l=c;if(h===undefined||h==='')return undefined;const D=Number(h);if(!Number[l(0xbc)](D)||D<=0x0)throw new ValidationError(U+'\x20must\x20be\x20a\x20positive\x20integer');return D;}
1
+ import{NotFoundError,ValidationError}from'../../../errors.js';import{fileTypeFromBuffer}from'file-type';import{createHash}from'node:crypto';import{mkdir,readFile,writeFile}from'node:fs/promises';import i from'node:path';function g(i,E){i=i-0x195;const W=T();let M=W[i];return M;}import E from'sharp';export async function resizeFile(W,M){const y=g,m=W['pathOrToken']??W[y(0x195)];if(!m)throw new ValidationError('File\x20path\x20is\x20required');const P=parseDimension(W['width'],y(0x196))??0xc8,D=parseDimension(W['height'],'height'),x=createHash(y(0x197))['update'](m+':'+P+':'+(D??'auto')+':'+(W['fit']??'cover'))['digest']('hex'),Z=i['resolve']('logs','resize'),f=i[y(0x198)](Z,x+'.jpg');try{return await readFile(f);}catch(Q){if(Q[y(0x199)]!=='ENOENT')throw Q;}if(!await M['file'][y(0x19a)](m))throw new NotFoundError(y(0x19b));const b=await M['file'][y(0x19c)](m),K=await fileTypeFromBuffer(b);if(!K?.[y(0x19d)][y(0x19e)](y(0x19f)))throw new ValidationError('Only\x20image\x20files\x20can\x20be\x20resized');const J=await E(b)[y(0x1a0)]({'width':P,'height':D,'fit':W['fit']??'cover'})['toBuffer']();return await mkdir(Z,{'recursive':!![]}),await writeFile(f,J),J;}function parseDimension(W,M){const s=g;if(W===undefined||W==='')return undefined;const m=Number(W);if(!Number[s(0x1a1)](m)||m<=0x0)throw new ValidationError(M+'\x20must\x20be\x20a\x20positive\x20integer');return m;}function T(){const o=['path','width','sha256','join','code','exists','File\x20not\x20found','get','mime','startsWith','image/','resize','isInteger'];T=function(){return o;};return T();}