@opengis/fcore 0.0.1-beta.17 → 0.0.1-beta.19

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 (112) hide show
  1. package/LICENSE +3 -3
  2. package/README.md +71 -71
  3. package/dist/config.js +1 -1
  4. package/dist/context.js +1 -1
  5. package/dist/errors.js +1 -1
  6. package/dist/fastify.d.ts.map +1 -1
  7. package/dist/fastify.js +1 -1
  8. package/dist/fcore.js +1 -1
  9. package/dist/migrations/cli.js +1 -1
  10. package/dist/migrations/runner.js +1 -1
  11. package/dist/modules/auth/adduser-cli.js +1 -1
  12. package/dist/modules/auth/passwd-cli.js +1 -1
  13. package/dist/modules/auth/permission-cli.js +1 -1
  14. package/dist/modules/auth/route.js +1 -1
  15. package/dist/modules/auth/schema.js +1 -1
  16. package/dist/modules/auth/services/change-password.js +1 -1
  17. package/dist/modules/auth/services/get-current-user.js +1 -1
  18. package/dist/modules/auth/services/registration.js +1 -1
  19. package/dist/modules/auth/services/verify-two-factor.js +1 -1
  20. package/dist/modules/file/mime.js +1 -1
  21. package/dist/modules/file/route.js +1 -1
  22. package/dist/modules/file/schema.js +1 -1
  23. package/dist/modules/file/services/get-file.js +1 -1
  24. package/dist/modules/file/services/resize-file.js +1 -1
  25. package/dist/modules/file/services/upload-file.js +1 -1
  26. package/dist/modules/resource/route.js +1 -1
  27. package/dist/modules/resource/schema.js +1 -1
  28. package/dist/modules/resource/services/add-note.js +1 -1
  29. package/dist/modules/resource/services/add-resource-file.js +1 -1
  30. package/dist/modules/resource/services/create-resource-relation.js +1 -1
  31. package/dist/modules/resource/services/create-resource.js +1 -1
  32. package/dist/modules/resource/services/delete-resource-relation.js +1 -1
  33. package/dist/modules/resource/services/delete-resource.js +1 -1
  34. package/dist/modules/resource/services/export-resource.js +1 -1
  35. package/dist/modules/resource/services/get-resource.js +1 -1
  36. package/dist/modules/resource/services/list-resource-relation.js +1 -1
  37. package/dist/modules/resource/services/list-resources.js +1 -1
  38. package/dist/modules/resource/services/search-resource.js +1 -1
  39. package/dist/modules/resource/services/suggest-resource.js +1 -1
  40. package/dist/modules/resource/services/update-resource-relation.js +1 -1
  41. package/dist/modules/resource/services/update-resource.js +1 -1
  42. package/dist/modules/resource/services/upload-resource-file.js +1 -1
  43. package/dist/modules/system/route.js +1 -1
  44. package/dist/modules/system/schema.d.ts +3 -2
  45. package/dist/modules/system/schema.d.ts.map +1 -1
  46. package/dist/modules/system/schema.js +1 -1
  47. package/dist/modules/system/services/check-system.js +1 -1
  48. package/dist/modules/system/services/get-access.d.ts +1 -0
  49. package/dist/modules/system/services/get-access.d.ts.map +1 -1
  50. package/dist/modules/system/services/get-access.js +1 -1
  51. package/dist/modules/system/services/get-api-list.js +1 -1
  52. package/dist/modules/system/services/get-audit-log.js +1 -1
  53. package/dist/modules/system/services/get-dictionary.js +1 -1
  54. package/dist/modules/system/services/get-system-log.js +1 -1
  55. package/dist/modules/system/services/get-system-settings.js +1 -1
  56. package/dist/modules/system/services/list-dictionaries.js +1 -1
  57. package/dist/modules/system/services/set-access.d.ts +2 -1
  58. package/dist/modules/system/services/set-access.d.ts.map +1 -1
  59. package/dist/modules/system/services/set-access.js +1 -1
  60. package/dist/modules/system/services/update-dictionary.js +1 -1
  61. package/dist/modules/system/services/update-system-settings.js +1 -1
  62. package/dist/modules/utils/require-admin.js +1 -1
  63. package/dist/modules/utils/safe-user.js +1 -1
  64. package/dist/modules/utils/unsupported.js +1 -1
  65. package/dist/plugins/audit/audit.js +1 -1
  66. package/dist/plugins/audit/audit.types.d.ts +1 -1
  67. package/dist/plugins/audit/audit.types.d.ts.map +1 -1
  68. package/dist/plugins/audit/services/write-audit.js +1 -1
  69. package/dist/plugins/auth/get-user-permissions.js +1 -1
  70. package/dist/plugins/auth/index.js +1 -1
  71. package/dist/plugins/auth/verifyUser.js +1 -1
  72. package/dist/plugins/dictionary.js +1 -1
  73. package/dist/plugins/file.js +1 -1
  74. package/dist/plugins/jwt.js +1 -1
  75. package/dist/plugins/logger/index.js +1 -1
  76. package/dist/plugins/logger/transport.js +1 -1
  77. package/dist/plugins/pg.js +1 -1
  78. package/dist/plugins/redis.js +1 -1
  79. package/dist/plugins/resource/resource.js +1 -1
  80. package/dist/plugins/resource/resource.registry.js +1 -1
  81. package/dist/plugins/resource/resource.types.d.ts +3 -4
  82. package/dist/plugins/resource/resource.types.d.ts.map +1 -1
  83. package/dist/plugins/resource/services/add-dictionary-lookup-data.js +1 -1
  84. package/dist/plugins/resource/services/add-file-token.js +1 -1
  85. package/dist/plugins/resource/services/add-table-lookup-data.js +1 -1
  86. package/dist/plugins/resource/services/create-relation.js +1 -1
  87. package/dist/plugins/resource/services/create.js +1 -1
  88. package/dist/plugins/resource/services/delete-relation.js +1 -1
  89. package/dist/plugins/resource/services/delete.d.ts.map +1 -1
  90. package/dist/plugins/resource/services/delete.js +1 -1
  91. package/dist/plugins/resource/services/find-one.d.ts.map +1 -1
  92. package/dist/plugins/resource/services/find-one.js +1 -1
  93. package/dist/plugins/resource/services/find-relation.d.ts.map +1 -1
  94. package/dist/plugins/resource/services/find-relation.js +1 -1
  95. package/dist/plugins/resource/services/find.d.ts.map +1 -1
  96. package/dist/plugins/resource/services/find.js +1 -1
  97. package/dist/plugins/resource/services/update-relation.js +1 -1
  98. package/dist/plugins/resource/services/update.d.ts.map +1 -1
  99. package/dist/plugins/resource/services/update.js +1 -1
  100. package/dist/plugins/resource/utils/auto-index.js +1 -1
  101. package/dist/plugins/resource/utils/fields.js +1 -1
  102. package/dist/plugins/resource/utils/filters.js +1 -1
  103. package/dist/plugins/resource/utils/permissions.js +1 -1
  104. package/dist/plugins/resource/utils/sort.d.ts +1 -1
  105. package/dist/plugins/resource/utils/sort.d.ts.map +1 -1
  106. package/dist/plugins/resource/utils/sort.js +1 -1
  107. package/dist/plugins/resource/utils/sql.js +1 -1
  108. package/dist/shared/getIP.js +1 -1
  109. package/migrations/20260903130000_move_notes_files_to_admin.sql +17 -17
  110. package/migrations/20260903140000_settings_nulls_not_distinct.sql +18 -18
  111. package/migrations/20260905120000_add_user_foreign_keys.sql +42 -42
  112. package/package.json +1 -1
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
- import'dotenv/config';const DEFAULT_LOG_RESPONSE_STATUS_CODES=[0x193,0x199,0x19d,0x19f,0x1ad];function D(){const o=['development','true','false','./storage','info','split','cwd','us-east-1','Ch7QR4e73Jg0wx0xOjm','session_user_auth','lax','logger'];D=function(){return o;};return D();}function required(i){const n=process.env[i];if(!n)throw new Error('Missing\x20environment\x20variable:\x20'+i);return n;}export function loadConfig(i={}){const O=u,n={'env':process.env.NODE_ENV??O(0x12d),'debug':process.env.DEBUG===O(0x12e),'port':Number(process.env.PORT??0xbb8),'maxFileSize':+(process.env.MAX_FILE_SIZE||0x200),'rateLimit':{'disabled':process.env.RATE_LIMIT===O(0x12f),'max':+(process.env.RATE_LIMIT_MAX||0x64),'timeWindow':+(process.env.RATE_LIMIT_TIME_WINDOW||0xea60)},'storagePath':process.env.STORAGE_PATH??O(0x130),'redactionList':(process.env.REDACTION_LIST||'password')['split'](','),'logger':{'level':process.env.LOG_LEVEL??O(0x131),'responses':process.env.LOG_RESPONSES==='true'?!![]:![],'responseCodes':process.env.LOG_RESPONSE_STATUS_CODES?process.env.LOG_RESPONSE_STATUS_CODES[O(0x132)](',')['map'](U=>U-0x0):DEFAULT_LOG_RESPONSE_STATUS_CODES,'directory':process.env.LOG_DIRECTORY||process[O(0x133)]()+'/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??O(0x134),'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||O(0x135),'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??O(0x136),'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||'true'),'secure':Boolean(process.env.AUTH_COOKIE_OPTIONS_SECURE||'true'),'sameSite':process.env.AUTH_COOKIE_OPTIONS_SAME_SITE&&[O(0x137),'strict','none']['includes'](process.env.AUTH_COOKIE_OPTIONS_SAME_SITE)?process.env.AUTH_COOKIE_OPTIONS_SAME_SITE:Boolean(process.env.AUTH_COOKIE_OPTIONS_SAME_SITE||O(0x12e))}:{'path':'/','httpOnly':!![],'secure':![],'sameSite':!![]}}};return{...n,...i,'logger':{...n['logger'],...i[O(0x138)]},'pg':{...n['pg'],...i['pg']},'redis':{...n['redis'],...i['redis']},'s3':{...n['s3'],...i['s3']},'auth':{...n['auth'],...i['auth']}};}function u(i,n){i=i-0x12d;const U=D();let O=U[i];return O;}export{required as requireEnv};
1
+ import'dotenv/config';const DEFAULT_LOG_RESPONSE_STATUS_CODES=[0x193,0x199,0x19d,0x19f,0x1ad];function required(L){const t=O,E=process.env[L];if(!E)throw new Error(t(0x77)+L);return E;}function Z(){const B=['Missing\x20environment\x20variable:\x20','split','false','parse','strict','none','auth'];Z=function(){return B;};return Z();}function O(L,E){L=L-0x77;const c=Z();let t=c[L];return t;}export function loadConfig(L={}){const e=O,E={'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)},'storagePath':process.env.STORAGE_PATH??'./storage','redactionList':(process.env.REDACTION_LIST||'password')[e(0x78)](','),'logger':{'level':process.env.LOG_LEVEL??'info','responses':process.env.LOG_RESPONSES==='true'?!![]:![],'responseCodes':process.env.LOG_RESPONSE_STATUS_CODES?process.env.LOG_RESPONSE_STATUS_CODES['split'](',')['map'](c=>c-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!==e(0x79),'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[e(0x7a)](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??'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||'true'),'secure':Boolean(process.env.AUTH_COOKIE_OPTIONS_SECURE||'true'),'sameSite':process.env.AUTH_COOKIE_OPTIONS_SAME_SITE&&['lax',e(0x7b),e(0x7c)]['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{...E,...L,'logger':{...E['logger'],...L['logger']},'pg':{...E['pg'],...L['pg']},'redis':{...E['redis'],...L['redis']},'s3':{...E['s3'],...L['s3']},'auth':{...E[e(0x7d)],...L['auth']}};}export{required as requireEnv};
package/dist/context.js CHANGED
@@ -1 +1 @@
1
- function u(i,n){i=i-0x152;const U=D();let O=U[i];return O;}let defaultContext;export function setContext(i){defaultContext=i;}export function getContext(){const n=u;if(!defaultContext)throw new Error(n(0x152));return defaultContext;}export function createContext(i){return{...i,async 'close'(){const U=u;await Promise['allSettled']([i[U(0x153)]?.['close'](),i['pg']?.['end']()]),await i['logger'][U(0x154)]();}};}function D(){const O=['Application\x20context\x20is\x20not\x20initialized','redis','close'];D=function(){return O;};return D();}
1
+ let defaultContext;export function setContext(L){defaultContext=L;}function Z(){const t=['Application\x20context\x20is\x20not\x20initialized','redis','end'];Z=function(){return t;};return Z();}export function getContext(){const E=O;if(!defaultContext)throw new Error(E(0x145));return defaultContext;}function O(L,E){L=L-0x145;const c=Z();let t=c[L];return t;}export function createContext(L){return{...L,async 'close'(){const c=O;await Promise['allSettled']([L[c(0x146)]?.['close'](),L['pg']?.[c(0x147)]()]),await L['logger']['close']();}};}
package/dist/errors.js CHANGED
@@ -1 +1 @@
1
- var o=u;export class FCoreError extends Error{['code'];['statusCode'];[o(0x1b1)];constructor(i,n,U=0x1f4,O){super(n),this['code']=i,this['statusCode']=U,this['details']=O,this['name']=new.target.name;}}export class BadRequestError extends FCoreError{constructor(i,n){super('BAD_REQUEST_ERROR',i,0x190,n);}}export class UnauthorizedError extends FCoreError{constructor(i='Authentication\x20required'){super('UNAUTHORIZED',i,0x191);}}export class ForbiddenError extends FCoreError{constructor(i='Access\x20denied'){super('FORBIDDEN',i,0x193);}}export class NotFoundError extends FCoreError{constructor(i='Not\x20found'){super('NOT_FOUND',i,0x194);}}function u(i,n){i=i-0x1b1;var U=D();var O=U[i];return O;}function D(){var X=['details','CONFLICT'];D=function(){return X;};return D();}export class ConflictError extends FCoreError{constructor(i='Conflict'){var I=o;super(I(0x1b2),i,0x199);}}export class ValidationError extends FCoreError{constructor(i,n){super('VALIDATION_ERROR',i,0x1a6,n);}}export class UnsupportedError extends FCoreError{constructor(i='Operation\x20is\x20not\x20configured'){super('UNSUPPORTED',i,0x1f5);}}
1
+ var e=O;function Z(){var X=['details','statusCode','BAD_REQUEST_ERROR','Authentication\x20required','NOT_FOUND'];Z=function(){return X;};return Z();}export class FCoreError extends Error{['code'];['statusCode'];[e(0xdc)];constructor(L,E,c=0x1f4,t){var B=e;super(E),this['code']=L,this[B(0xdd)]=c,this['details']=t,this['name']=new.target.name;}}export class BadRequestError extends FCoreError{constructor(L,E){var g=e;super(g(0xde),L,0x190,E);}}export class UnauthorizedError extends FCoreError{constructor(L=e(0xdf)){super('UNAUTHORIZED',L,0x191);}}function O(L,E){L=L-0xdc;var c=Z();var t=c[L];return t;}export class ForbiddenError extends FCoreError{constructor(L='Access\x20denied'){super('FORBIDDEN',L,0x193);}}export class NotFoundError extends FCoreError{constructor(L='Not\x20found'){var r=e;super(r(0xe0),L,0x194);}}export class ConflictError extends FCoreError{constructor(L='Conflict'){super('CONFLICT',L,0x199);}}export class ValidationError extends FCoreError{constructor(L,E){super('VALIDATION_ERROR',L,0x1a6,E);}}export class UnsupportedError extends FCoreError{constructor(L='Operation\x20is\x20not\x20configured'){super('UNSUPPORTED',L,0x1f5);}}
@@ -1 +1 @@
1
- {"version":3,"file":"fastify.d.ts","sourceRoot":"","sources":["../src/fastify.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,KAAK,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAY/C,MAAM,MAAM,cAAc,GAAG,MAAM,GAAG,UAAU,GAAG,MAAM,GAAG,QAAQ,CAAC;AAarE,MAAM,CAAC,OAAO,UAAU,YAAY,CAClC,GAAG,EAAE,UAAU,EACf,OAAO,CAAC,EAAE,SAAS,cAAc,EAAE,GAClC,kBAAkB,CAkIpB"}
1
+ {"version":3,"file":"fastify.d.ts","sourceRoot":"","sources":["../src/fastify.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,KAAK,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAY/C,MAAM,MAAM,cAAc,GAAG,MAAM,GAAG,UAAU,GAAG,MAAM,GAAG,QAAQ,CAAC;AAYrE,MAAM,CAAC,OAAO,UAAU,YAAY,CAClC,GAAG,EAAE,UAAU,EACf,OAAO,CAAC,EAAE,SAAS,cAAc,EAAE,GAClC,kBAAkB,CAwIpB"}
package/dist/fastify.js CHANGED
@@ -1 +1 @@
1
- import i from'fastify-plugin';import{FCoreError}from'./errors.js';function u(i,n){i=i-0x176;const U=D();let O=U[i];return O;}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 D(){const b=['toString','schema','isArray','method','fcore','description','preHandler','routeOptions','startsWith','access','Missing\x20permission:\x20','code','debug','error','Internal\x20server\x20error','auth','register','system','user','raw','split','⚠️\x20rate\x20limit\x20is\x20disabled'];D=function(){return b;};return D();}import{jwtVerifyToken}from'./plugins/jwt.js';function urlencodedContentParser(n,U,O){const h=u,o=decodeURIComponent(U[h(0x176)]())['split']('&')['reduce']((I,X)=>{const [T,R]=X['split']('=');return{...I,[T]:R};},{});O(null,o);}export default function fcoreFastify(n,U){return i(async O=>{const M=u;O['decorate']('ctx',n);const {config:o}=n,I=new Map();O['addHook']('onRoute',T=>{const q=u,R=T[q(0x177)],g=Array[q(0x178)](T[q(0x179)])?T['method']:[T['method']];for(const k of g){if(k==='HEAD')continue;const d={'method':k,'endpoint':T['url'],'package':R?.['package']??q(0x17a),'tags':R?.['tags']??[],'summary':R?.['summary']??'','description':R?.[q(0x17b)]??'','access':R?.['access']??'public','permissions':R?.['permissions']??[]};I['set'](k+'\x20'+T['url'],d);}}),O['addHook'](M(0x17c),async T=>{const y=M;if(T['routeOptions']['url']==='*')return!![];const R=I['get'](T['method']+'\x20'+T[y(0x17d)]['url']),g=T['raw']['headers']?.['authorization'],k=g?.[y(0x17e)]('Bearer\x20')?g['slice'](0x7):null,d=T['user']??(k?await jwtVerifyToken(k):null);!T['user']&&k&&process.env.AUTH_JWT_SECRET&&(T['user']=await jwtVerifyToken(k));if(!R?.['access'])throw new Error('Route\x20access\x20not\x20defined');if(R['access']==='public')return!![];if(!d)throw new ForbiddenError('User\x20required');if(R['access']==='user'&&!R['permissions']?.['length'])return!![];if(d['type']=='admin')return!![];if(R[y(0x17f)]==='admin')throw new ForbiddenError('Admin\x20access\x20required');for(const L of R['permissions']){if(!d['permissions']?.['includes'](L))throw new ForbiddenError(y(0x180)+L);}return!![];}),await createSessionStore(O,n),await O['register'](import('@fastify/multipart'),{'limits':{'fileSize':o['maxFileSize']*0x400*0x400}}),O['setErrorHandler']((T,R,g)=>{const Z=M;if(T instanceof FCoreError||T[Z(0x181)]==='FST_ERR_VALIDATION'||T['statusCode']<0x1f4)return T['statusCode']<0x1f4&&n['logger']['warn'](T),g['code'](T['statusCode'])['send']({'error':T[Z(0x181)],'message':T['message'],'details':T['details']});return n['logger']['error'](T),(o[Z(0x182)]||process.env.NODE_ENV==='test'||process.env.VITEST)&&console[Z(0x183)](T),g['code'](0x1f4)['send']({'error':'INTERNAL_ERROR','message':Z(0x184)});});const X=T=>!U||U['includes'](T);if(X(M(0x185)))await O['register'](authRoutes(n));if(X('resource'))await O['register'](resourceRoutes(n));if(X('file'))await O[M(0x186)](fileRoutes(n));if(X(M(0x187)))await O[M(0x186)](systemRoutes(n,I));O['addContentTypeParser']('application/x-www-form-urlencoded',{'parseAs':'buffer'},urlencodedContentParser),!o['rateLimit']?.['disabled']?O['register'](import('@fastify/rate-limit'),{'max':o['rateLimit']?.['max']||0x64,'timeWindow':o['rateLimit']?.['timeWindow']||0xea60,'hook':'preHandler','global':!![],'keyGenerator':T=>(T[M(0x188)]?.['id']||T['ip'])+'-'+T[M(0x189)]['url'][M(0x18a)]('?')[0x0]}):console['log'](M(0x18b));});};
1
+ import L from'fastify-plugin';import{FCoreError}from'./errors.js';function Z(){const q=['reduce','ctx','method','fcore','public','set','url','addHook','routeOptions','raw','headers','authorization','Bearer\x20','user','auth','access','length','admin','permissions','includes','@fastify/multipart','FST_ERR_VALIDATION','logger','send','code','details','error','debug','test','register','resource','file','rateLimit','disabled','@fastify/rate-limit'];Z=function(){return q;};return Z();}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';function O(L,E){L=L-0x106;const c=Z();let t=c[L];return t;}import{ForbiddenError}from'./errors.js';import{jwtVerifyToken}from'./plugins/jwt.js';function urlencodedContentParser(E,c,t){const f=O,e=decodeURIComponent(c['toString']())['split']('&')[f(0x106)]((B,g)=>{const [r,X]=g['split']('=');return{...B,[r]:X};},{});t(null,e);}export default function fcoreFastify(E,c){return L(async t=>{const A=O;t['decorate'](A(0x107),E);const {config:e}=E,B=new Map();t['addHook']('onRoute',r=>{const G=A,X=r['schema'],j=Array['isArray'](r['method'])?r[G(0x108)]:[r[G(0x108)]];for(const F of j){if(F==='HEAD')continue;const I={'method':F,'endpoint':r['url'],'package':X?.['package']??G(0x109),'tags':X?.['tags']??[],'summary':X?.['summary']??'','description':X?.['description']??'','access':X?.['access']??G(0x10a),'permissions':X?.['permissions']??[]};B[G(0x10b)](F+'\x20'+r[G(0x10c)],I);}}),t[A(0x10d)]('preHandler',async r=>{const x=A;if(r['routeOptions']['url']==='*')return!![];const X=B['get'](r['method']+'\x20'+r[x(0x10e)][x(0x10c)]),j=r[x(0x10f)][x(0x110)]?.[x(0x111)],F=j?.['startsWith'](x(0x112))?j['slice'](0x7):null,I=r[x(0x113)]??(F?await jwtVerifyToken(F):null);!r[x(0x113)]&&F&&process.env.AUTH_JWT_SECRET&&(r['user']=await jwtVerifyToken(F));!r['user']&&process['platform']==='win32'&&E['config']?.[x(0x114)]?.['user']&&(r[x(0x113)]=E['config']['auth']['user']);if(!X?.['access'])throw new Error('Route\x20access\x20not\x20defined');if(X[x(0x115)]==='public')return!![];if(!I)throw new ForbiddenError('User\x20required');if(X['access']==='user'&&!X['permissions']?.[x(0x116)])return!![];if(I['type']==x(0x117))return!![];if(X['access']==='admin')throw new ForbiddenError('Admin\x20access\x20required');for(const T of X[x(0x118)]){if(!I['permissions']?.[x(0x119)](T))throw new ForbiddenError('Missing\x20permission:\x20'+T);}return!![];}),await createSessionStore(t,E),await t['register'](import(A(0x11a)),{'limits':{'fileSize':e['maxFileSize']*0x400*0x400}}),t['setErrorHandler']((r,X,j)=>{const W=A;if(r instanceof FCoreError||r['code']===W(0x11b)||r['statusCode']<0x1f4)return r['statusCode']<0x1f4&&E[W(0x11c)]['warn'](r),j['code'](r['statusCode'])[W(0x11d)]({'error':r[W(0x11e)],'message':r['message'],'details':r[W(0x11f)]});return E['logger'][W(0x120)](r),(e[W(0x121)]||process.env.NODE_ENV===W(0x122)||process.env.VITEST)&&console[W(0x120)](r),j['code'](0x1f4)['send']({'error':'INTERNAL_ERROR','message':'Internal\x20server\x20error'});});const g=r=>!c||c[A(0x119)](r);if(g('auth'))await t[A(0x123)](authRoutes(E));if(g(A(0x124)))await t['register'](resourceRoutes(E));if(g(A(0x125)))await t[A(0x123)](fileRoutes(E));if(g('system'))await t['register'](systemRoutes(E,B));t['addContentTypeParser']('application/x-www-form-urlencoded',{'parseAs':'buffer'},urlencodedContentParser),!e[A(0x126)]?.[A(0x127)]?t['register'](import(A(0x128)),{'max':e[A(0x126)]?.['max']||0x64,'timeWindow':e[A(0x126)]?.['timeWindow']||0xea60,'hook':'preHandler','global':!![],'keyGenerator':r=>(r['user']?.['id']||r['ip'])+'-'+r[A(0x10f)][A(0x10c)]['split']('?')[0x0]}):console['log']('⚠️\x20rate\x20limit\x20is\x20disabled');});}
package/dist/fcore.js CHANGED
@@ -1 +1 @@
1
- function u(i,n){i=i-0x1a9;const U=D();let O=U[i];return O;}import{loadConfig}from'./config.js';import{createContext,setContext}from'./context.js';function D(){const d=['config','forcePathStyle','dictionaries'];D=function(){return d;};return D();}import{createAudit,createDatabase,createDictionary,createFileS3,createLogger,createRedis,createResource}from'./plugins/index.js';export async function createFCore(i={}){const k=u,n=loadConfig(i[k(0x1a9)]),U=createRedis(n['redis']),O=createLogger(),o=createDatabase(n['pg']),I=createFileS3({'endpoint':n['s3']['endpoint'],'region':n['s3']['region'],'bucket':n['s3']['bucket'],'accessKey':n['s3']['accessKey'],'secretKey':n['s3']['secretKey'],'folder':n['s3']['folder'],'forcePathStyle':n['s3'][k(0x1aa)],'tokenSecret':n['s3']['tokenSecret'],'tokenTtl':n['s3']['tokenTtl']}),X=createAudit({'pg':o,'logger':O}),T=createDictionary({'pg':o,'dictionaries':i[k(0x1ab)]}),R=createResource({'pg':o,'logger':O,'audit':X,'dictionary':T,'file':I});i['resources']?.['length']&&R['register'](i['resources']);const g=createContext({'config':n,'logger':O,'redis':U,'pg':o,'file':I,'resource':R,'audit':X,'dictionary':T});return setContext(g),g;}
1
+ import{loadConfig}from'./config.js';import{createContext,setContext}from'./context.js';import{createAudit,createDatabase,createDictionary,createFileS3,createLogger,createRedis,createResource}from'./plugins/index.js';function Z(){const I=['redis','endpoint','accessKey'];Z=function(){return I;};return Z();}function O(L,E){L=L-0xfe;const c=Z();let t=c[L];return t;}export async function createFCore(L={}){const F=O,E=loadConfig(L['config']),c=createRedis(E[F(0xfe)]),t=createLogger(),e=createDatabase(E['pg']),B=createFileS3({'endpoint':E['s3'][F(0xff)],'region':E['s3']['region'],'bucket':E['s3']['bucket'],'accessKey':E['s3'][F(0x100)],'secretKey':E['s3']['secretKey'],'folder':E['s3']['folder'],'forcePathStyle':E['s3']['forcePathStyle'],'tokenSecret':E['s3']['tokenSecret'],'tokenTtl':E['s3']['tokenTtl']}),g=createAudit({'pg':e,'logger':t}),r=createDictionary({'pg':e,'dictionaries':L['dictionaries']}),X=createResource({'pg':e,'logger':t,'audit':g,'dictionary':r,'file':B});L['resources']?.['length']&&X['register'](L['resources']);const j=createContext({'config':E,'logger':t,'redis':c,'pg':e,'file':B,'resource':X,'audit':g,'dictionary':r});return setContext(j),j;}
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- const n=u;function u(i,n){i=i-0x1be;const U=D();let O=U[i];return O;}import{runMigrations}from'./runner.js';import{loadConfig}from'../config.js';function D(){const U=['log','file'];D=function(){return U;};return D();}try{const config=loadConfig();console['log']('Loaded\x20configuration:',config['pg']);for(const r of await runMigrations({'database':config['pg']}))console[n(0x1be)]((r['status']==='run'?'OK\x20\x20':'SKIP')+'\x20'+r[n(0x1bf)]);}catch(i){console['error'](i),process['exitCode']=0x1;}
2
+ function Z(){const F=['--dir','--dir\x20requires\x20a\x20folder\x20path','--fcore','slice','****'];Z=function(){return F;};return Z();}const j=O;import{runMigrations}from'./runner.js';import{loadConfig}from'../config.js';import L from'node:path';import{fileURLToPath}from'node:url';function O(L,E){L=L-0x136;const c=Z();let t=c[L];return t;}const packageMigrations=fileURLToPath(new URL('../../migrations',import.meta.url));function migrationDirectory(E){const X=O,c=E['indexOf'](X(0x136));if(c>=0x0){const e=E[c+0x1];if(!e)throw new Error(X(0x137));return L['resolve'](e);}if(E['includes'](X(0x138)))return packageMigrations;const t=E['find'](B=>!B['startsWith']('--'));return L['resolve'](t??'migrations');}try{const config=loadConfig(),dir=migrationDirectory(process['argv'][j(0x139)](0x2));console['log']('Loaded\x20configuration:',{...config['pg'],'user':'****','password':j(0x13a)}),console['log']('Using\x20migration\x20directory:',dir,process['argv']['slice'](0x2));for(const r of await runMigrations({'database':config['pg'],'dir':dir}))console['log']((r['status']==='run'?'OK\x20\x20':'SKIP')+'\x20'+r['file']);}catch(g){console['error'](g),process['exitCode']=0x1;}
@@ -1 +1 @@
1
- function D(){const y=['dir','database','databaseUrl','version','filter','sort','readFile','query','BEGIN','ROLLBACK','release','push','end','hostname','slice'];D=function(){return y;};return D();}function u(i,n){i=i-0xab;const U=D();let O=U[i];return O;}import i from'node:fs/promises';import n from'node:path';import{createDatabase}from'../plugins/pg.js';export async function runMigrations(U={}){const q=u,O=n['resolve'](U[q(0xab)]??'migrations'),o=U[q(0xac)]??databaseFromUrl(U[q(0xad)]??process.env.DATABASE_URL);if(!o)throw new Error('DATABASE_URL\x20or\x20database\x20config\x20is\x20required');const I=createDatabase(o);if(!I)throw new Error('empty\x20pg');const X=[];try{await I['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');const T=await I['query']('SELECT\x20version\x20FROM\x20schema_migrations'),R=new Set(T['rows']['map'](k=>k[q(0xae)])),g=(await i['readdir'](O))[q(0xaf)](k=>k['endsWith']('.sql'))[q(0xb0)]();for(const k of g){if(R['has'](k)){X['push']({'file':k,'status':'skip'});continue;}const d=await i[q(0xb1)](n['join'](O,k),'utf8'),L=await I['connect']();try{await L[q(0xb2)](q(0xb3)),await L[q(0xb2)](d),await L['query']('INSERT\x20INTO\x20schema_migrations(version)\x20VALUES\x20($1)',[k]),await L[q(0xb2)]('COMMIT');}catch(h){await L['query'](q(0xb4));throw h;}finally{L[q(0xb5)]();}X[q(0xb6)]({'file':k,'status':'run'});}return X;}finally{await I[q(0xb7)]();}}function databaseFromUrl(U){const M=u;if(!U)return undefined;const O=new URL(U);return{'host':O[M(0xb8)],'port':Number(O['port']||0x1538),'database':O['pathname'][M(0xb9)](0x1),'user':decodeURIComponent(O['username']),'password':decodeURIComponent(O['password'])};}
1
+ import L from'node:fs/promises';function O(L,E){L=L-0x10d;const c=Z();let t=c[L];return t;}import E from'node:path';import{createDatabase}from'../plugins/pg.js';export async function runMigrations(c={}){const A=O,t=E['resolve'](c['dir']??'migrations'),e=c['database']??databaseFromUrl(c['databaseUrl']??process.env.DATABASE_URL);if(!e)throw new Error('DATABASE_URL\x20or\x20database\x20config\x20is\x20required');const B=createDatabase(e);if(!B)throw new Error(A(0x10d));const g=[];try{await B['query'](A(0x10e));const r=await B['query'](A(0x10f)),X=new Set(r[A(0x110)]['map'](F=>F['version'])),j=(await L['readdir'](t))[A(0x111)](F=>F['endsWith']('.sql'))[A(0x112)]();for(const F of j){if(X['has'](F)){g['push']({'file':F,'status':A(0x113)});continue;}const I=await L['readFile'](E['join'](t,F),A(0x114)),T=await B[A(0x115)]();try{await T['query']('BEGIN'),await T['query'](I),await T[A(0x116)]('INSERT\x20INTO\x20schema_migrations(version)\x20VALUES\x20($1)',[F]),await T['query']('COMMIT');}catch(f){await T['query']('ROLLBACK');throw f;}finally{T[A(0x117)]();}g['push']({'file':F,'status':A(0x118)});}return g;}finally{await B['end']();}}function Z(){const x=['empty\x20pg','\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','SELECT\x20version\x20FROM\x20schema_migrations','rows','filter','sort','skip','utf8','connect','query','release','run','hostname'];Z=function(){return x;};return Z();}function databaseFromUrl(c){const G=O;if(!c)return undefined;const t=new URL(c);return{'host':t[G(0x119)],'port':Number(t['port']||0x1538),'database':t['pathname']['slice'](0x1),'user':decodeURIComponent(t['username']),'password':decodeURIComponent(t['password'])};}
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- const U=u;import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';function u(i,n){i=i-0xc7;const U=D();let O=U[i];return O;}import i from'./services/registration.js';function D(){const O=['argv','error','type','end'];D=function(){return O;};return D();}const [user,password,type]=process[U(0xc7)]['slice'](0x2);if(!user||!password)console[U(0xc8)]('Usage:\x20fcore-registration\x20<login>\x20<password>\x20[type]'),process['exitCode']=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const {user:data}=await i({'user':user,'password':password,'type':type},{'pg':pg});console['log']('Registered\x20user\x20'+data['id']+'\x20('+data[U(0xc9)]+')');}catch(n){console['error'](n),process['exitCode']=0x1;}finally{await pg[U(0xca)]();}}
2
+ const c=O;function O(L,E){L=L-0x16a;const c=Z();let t=c[L];return t;}import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';import L from'./services/registration.js';const [user,password,type]=process['argv']['slice'](0x2);function Z(){const t=['log','Registered\x20user\x20','exitCode','end'];Z=function(){return t;};return Z();}if(!user||!password)console['error']('Usage:\x20fcore-registration\x20<login>\x20<password>\x20[type]'),process['exitCode']=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const {user:data}=await L({'user':user,'password':password,'type':type},{'pg':pg});console[c(0x16a)](c(0x16b)+data['id']+'\x20('+data['type']+')');}catch(E){console['error'](E),process[c(0x16c)]=0x1;}finally{await pg[c(0x16d)]();}}
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- const U=u;import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';import i from'./services/change-password.js';function u(i,n){i=i-0x1c0;const U=D();let O=U[i];return O;}const [login,password]=process['argv'][U(0x1c0)](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[U(0x1c1)]('SELECT\x20uid\x20AS\x20id\x20FROM\x20admin.users\x20WHERE\x20$1\x20IN\x20(login,\x20email,\x20phone)\x20LIMIT\x201',[login]),user=result['rows'][0x0];if(!user)throw new Error('User\x20not\x20found');await i({'userId':user['id'],'password':password},{'pg':pg}),console['log'](U(0x1c2)+login);}catch(n){console['error'](n),process['exitCode']=0x1;}finally{await pg['end']();}}function D(){const O=['slice','query','Password\x20changed\x20for\x20'];D=function(){return O;};return D();}
2
+ const c=O;import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';function Z(){const t=['slice','query','rows'];Z=function(){return t;};return Z();}import L from'./services/change-password.js';const [login,password]=process['argv'][c(0x7d)](0x2);function O(L,E){L=L-0x7d;const c=Z();let t=c[L];return t;}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[c(0x7e)]('SELECT\x20uid\x20AS\x20id\x20FROM\x20admin.users\x20WHERE\x20$1\x20IN\x20(login,\x20email,\x20phone)\x20LIMIT\x201',[login]),user=result[c(0x7f)][0x0];if(!user)throw new Error('User\x20not\x20found');await L({'userId':user['id'],'password':password},{'pg':pg}),console['log']('Password\x20changed\x20for\x20'+login);}catch(E){console['error'](E),process['exitCode']=0x1;}finally{await pg['end']();}}
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- function u(i,n){i=i-0x6f;const U=D();let O=U[i];return O;}const R=u;import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';function D(){const k=['logs','list','check','create','split','map','filter','error','Permissions\x20cleared\x20for\x20','push','query','ROLLBACK'];D=function(){return k;};return D();}const SYSTEM_ACTIONS=[R(0x6f),'audit',R(0x70),R(0x71),'access','settings','dictionaries'],RESOURCE_ACTIONS=['read','update',R(0x72),'delete'],[login,permissionArg]=process['argv']['slice'](0x2);function expandPermissions(i){const g=R,n=i[g(0x73)](',')[g(0x74)](O=>O['trim']())[g(0x75)](Boolean),U=new Set();for(const O of n){if(O['includes'](':')){U['add'](O);continue;}const o=O==='system'?SYSTEM_ACTIONS:RESOURCE_ACTIONS;for(const I of o){U['add'](O+':'+I);}}return[...U];}if(!login||!permissionArg)console[R(0x76)]('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['query']('SELECT\x20uid\x20AS\x20id\x20FROM\x20admin.users\x20WHERE\x20$1\x20IN\x20(login,\x20email,\x20phone)\x20LIMIT\x201',[login]),user=result['rows'][0x0];if(!user)throw new Error('User\x20not\x20found');if(permissionArg['trim']()==='clear')await pg['query']('DELETE\x20FROM\x20admin.role_access\x20WHERE\x20user_uid\x20=\x20$1\x20AND\x20role_id\x20IS\x20NULL',[user['id']]),console['log'](R(0x77)+login);else{const permissions=expandPermissions(permissionArg),byResource=new Map();for(const permission of permissions){const [resource,action]=permission['split'](':'),actions=byResource['get'](resource)??[];actions[R(0x78)](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[R(0x79)]('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',[user['id'],resource]),row=existing['rows'][0x0];if(row){const merged=[...new Set([...row['actions']??[],...actions])];await client['query']('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',[merged,user['id'],row['access_id']]);}else await client[R(0x79)]('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(X){await client['query'](R(0x7a));throw X;}finally{client['release']();}console['log']('Granted\x20permissions\x20for\x20'+login+':\x20'+permissions['join'](',\x20'));}}catch(T){console[R(0x76)](T),process['exitCode']=0x1;}finally{await pg['end']();}}
2
+ const X=O;import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';const SYSTEM_ACTIONS=['logs','audit','list','check','access',X(0xa6),X(0xa7)],RESOURCE_ACTIONS=['read',X(0xa8),'create',X(0xa9)],[login,permissionArg]=process[X(0xaa)]['slice'](0x2);function O(L,E){L=L-0xa6;const c=Z();let t=c[L];return t;}function expandPermissions(L){const j=X,E=L['split'](',')[j(0xab)](t=>t['trim']())[j(0xac)](Boolean),c=new Set();for(const t of E){if(t['includes'](':')){c['add'](t);continue;}const e=t==='system'?SYSTEM_ACTIONS:RESOURCE_ACTIONS;for(const B of e){c[j(0xad)](t+':'+B);}}return[...c];}function Z(){const F=['settings','dictionaries','update','delete','argv','map','filter','add','exitCode','Permissions\x20cleared\x20for\x20','get','connect','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','Granted\x20permissions\x20for\x20','join','error','end'];Z=function(){return F;};return Z();}if(!login||!permissionArg)console['error']('Usage:\x20fcore-permission\x20<login>\x20<system|resource|resource:action[,...]|clear>'),process[X(0xae)]=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['rows'][0x0];if(!user)throw new Error('User\x20not\x20found');if(permissionArg['trim']()==='clear')await pg['query']('DELETE\x20FROM\x20admin.role_access\x20WHERE\x20user_uid\x20=\x20$1\x20AND\x20role_id\x20IS\x20NULL',[user['id']]),console['log'](X(0xaf)+login);else{const permissions=expandPermissions(permissionArg),byResource=new Map();for(const permission of permissions){const [resource,action]=permission['split'](':'),actions=byResource[X(0xb0)](resource)??[];actions['push'](action),byResource['set'](resource,actions);}const client=await pg[X(0xb1)]();try{await client['query']('BEGIN');for(const [resource,actions]of byResource){const existing=await client['query']('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',[user['id'],resource]),row=existing['rows'][0x0];if(row){const merged=[...new Set([...row['actions']??[],...actions])];await client['query'](X(0xb2),[merged,user['id'],row['access_id']]);}else await client['query']('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(g){await client['query']('ROLLBACK');throw g;}finally{client['release']();}console['log'](X(0xb3)+login+':\x20'+permissions[X(0xb4)](',\x20'));}}catch(r){console[X(0xb5)](r),process['exitCode']=0x1;}finally{await pg[X(0xb6)]();}}
@@ -1 +1 @@
1
- function D(){const Z=['GET','body','twofa','config','auth','cookie','save','session','sessionId','permissions','fcore','credentials','/api/auth/login','Sign\x20in','public','/api/auth/registration','Change\x20password','Changes\x20the\x20password\x20for\x20the\x20current\x20user.','Not\x20authorized','post','/api/auth/logout','user','audit','write','destroy','clearCookie','get','Get\x20current\x20user','Returns\x20the\x20authenticated\x20user\x27s\x20safe\x20profile.','query'];D=function(){return Z;};return D();}import{getUserPermissions,verifyUser}from'../../plugins/auth/index.js';import i from'./services/get-current-user.js';import n from'./services/registration.js';import U from'./services/change-password.js';function u(i,n){i=i-0x13e;const U=D();let O=U[i];return O;}import{authSchemas}from'./schema.js';import O from'../../shared/getIP.js';import{UnauthorizedError}from'../../errors.js';export function authRoutes(o){return async I=>{const q=u,X=async T=>{const h=u,R=T['method']===h(0x13e)?T['query']:T[h(0x13f)],g=O(T),k=await verifyUser({...R,'ip':g},o);k['permissions']=await getUserPermissions(k['id'],o);const d=k[h(0x140)]?o['config']['auth']['twoFactorRedirect']:o[h(0x141)][h(0x142)]['redirect'];await T['login'](k);const L=o['config']['auth']['sessionTimeout']*0x3e8*0x3c;return T['session']?.['cookie']&&(T['session'][h(0x143)]['maxAge']=L),await T['session'][h(0x144)](),await o['audit']?.['write']?.({'module':h(0x142),'resource':'session','resourceId':T[h(0x145)][h(0x146)],'action':'login','userId':k['id'],'ipAddress':g}),{'user':{'id':k['id'],'type':k['type'],'permissions':k[h(0x147)]},'redirectUrl':d};};I['get']('/api/auth/login',{'schema':{'tags':[q(0x148),'auth'],'summary':'Sign\x20in','description':'Authenticates\x20a\x20user\x20and\x20returns\x20a\x20bearer\x20access\x20token.','access':'public','permissions':[],'querystring':authSchemas[q(0x149)]}},X),I['post'](q(0x14a),{'schema':{'tags':['fcore','auth'],'summary':q(0x14b),'description':'Authenticates\x20a\x20user\x20and\x20returns\x20a\x20bearer\x20access\x20token.','access':q(0x14c),'permissions':[],'body':authSchemas[q(0x149)]}},X),I['post'](q(0x14d),{'schema':{'tags':['fcore','auth'],'summary':'Register','description':'Creates\x20a\x20regular\x20user\x20account.','access':'admin','permissions':['user:create'],'body':authSchemas['credentials']}},async T=>n(T[q(0x13f)],o)),I['post']('/api/auth/password',{'schema':{'tags':['fcore',q(0x142)],'summary':q(0x14e),'description':q(0x14f),'access':'user','permissions':[],'body':authSchemas['password']}},async T=>{const M=q;if(!T['user'])throw new UnauthorizedError(M(0x150));return await U({'userId':T['user']['id'],...T['body']},o),{'success':!![]};}),I[q(0x151)](q(0x152),{'schema':{'tags':['fcore',q(0x142)],'summary':'Sign\x20out','description':'Terminates\x20the\x20current\x20user\x20session.','access':q(0x153),'permissions':[]}},async(T,R)=>{const y=q,g={'redirectUrl':'/'};if(!T[y(0x153)])return g;return await o[y(0x154)]?.[y(0x155)]?.({'module':'auth','resource':'session','resourceId':T['session'][y(0x146)],'action':'logout','userId':T['user']?.['id']}),await T['session'][y(0x156)](),R[y(0x157)](o['config']['auth']['cookieName']),Object['defineProperty'](T,y(0x145),{'value':null,'writable':![],'configurable':![]}),g;}),I[q(0x158)]('/api/auth/user',{'schema':{'tags':['fcore','auth'],'summary':q(0x159),'description':q(0x15a),'access':'user','permissions':[],'querystring':authSchemas['query']}},async T=>i({'user':T['user'],'token':T[q(0x15b)]['token']}));};}
1
+ import{getUserPermissions,verifyUser}from'../../plugins/auth/index.js';import L from'./services/get-current-user.js';import E from'./services/registration.js';import c from'./services/change-password.js';function O(L,E){L=L-0xcb;const c=Z();let t=c[L];return t;}function Z(){const x=['body','twofa','twoFactorRedirect','auth','config','sessionTimeout','session','type','fcore','public','credentials','post','Authenticates\x20a\x20user\x20and\x20returns\x20a\x20bearer\x20access\x20token.','Creates\x20a\x20regular\x20user\x20account.','clearCookie','get','Get\x20current\x20user','query','token'];Z=function(){return x;};return Z();}import{authSchemas}from'./schema.js';import t from'../../shared/getIP.js';import{UnauthorizedError}from'../../errors.js';export function authRoutes(e){return async B=>{const A=O,g=async r=>{const f=O,X=r['method']==='GET'?r['query']:r[f(0xcb)],j=t(r),F=await verifyUser({...X,'ip':j},e);F['permissions']=await getUserPermissions(F['id'],e);const I=F[f(0xcc)]?e['config']['auth'][f(0xcd)]:e['config'][f(0xce)]['redirect'];await r['login'](F);const T=e[f(0xcf)]['auth'][f(0xd0)]*0x3e8*0x3c;return r['session']?.['cookie']&&(r[f(0xd1)]['cookie']['maxAge']=T),await r['session']['save'](),await e['audit']?.['write']?.({'module':'auth','resource':'session','resourceId':r[f(0xd1)]['sessionId'],'action':'login','userId':F['id'],'ipAddress':j}),{'user':{'id':F['id'],'type':F[f(0xd2)],'permissions':F['permissions']},'redirectUrl':I};};B['get']('/api/auth/login',{'schema':{'tags':[A(0xd3),'auth'],'summary':'Sign\x20in','description':'Authenticates\x20a\x20user\x20and\x20returns\x20a\x20bearer\x20access\x20token.','access':A(0xd4),'permissions':[],'querystring':authSchemas[A(0xd5)]}},g),B[A(0xd6)]('/api/auth/login',{'schema':{'tags':['fcore',A(0xce)],'summary':'Sign\x20in','description':A(0xd7),'access':'public','permissions':[],'body':authSchemas['credentials']}},g),B[A(0xd6)]('/api/auth/registration',{'schema':{'tags':['fcore','auth'],'summary':'Register','description':A(0xd8),'access':'admin','permissions':['user:create'],'body':authSchemas[A(0xd5)]}},async r=>E(r['body'],e)),B['post']('/api/auth/password',{'schema':{'tags':['fcore','auth'],'summary':'Change\x20password','description':'Changes\x20the\x20password\x20for\x20the\x20current\x20user.','access':'user','permissions':[],'body':authSchemas['password']}},async r=>{if(!r['user'])throw new UnauthorizedError('Not\x20authorized');return await c({'userId':r['user']['id'],...r['body']},e),{'success':!![]};}),B[A(0xd6)]('/api/auth/logout',{'schema':{'tags':['fcore','auth'],'summary':'Sign\x20out','description':'Terminates\x20the\x20current\x20user\x20session.','access':'user','permissions':[]}},async(r,X)=>{const G=A,j={'redirectUrl':'/'};if(!r['user'])return j;return await e['audit']?.['write']?.({'module':'auth','resource':'session','resourceId':r['session']['sessionId'],'action':'logout','userId':r['user']?.['id']}),await r['session']['destroy'](),X[G(0xd9)](e['config']['auth']['cookieName']),Object['defineProperty'](r,'session',{'value':null,'writable':![],'configurable':![]}),j;}),B[A(0xda)]('/api/auth/user',{'schema':{'tags':['fcore','auth'],'summary':A(0xdb),'description':'Returns\x20the\x20authenticated\x20user\x27s\x20safe\x20profile.','access':'user','permissions':[],'querystring':authSchemas[A(0xdc)]}},async r=>L({'user':r['user'],'token':r['query'][A(0xdd)]}));};}
@@ -1 +1 @@
1
- const i=u;import{Type}from'@sinclair/typebox';function D(){const n=['Optional','String','Object'];D=function(){return n;};return D();}function u(i,n){i=i-0x9a;const U=D();let O=U[i];return O;}export const authSchemas={'query':Type['Object']({'token':Type[i(0x9a)](Type['Boolean']())}),'credentials':Type['Object']({'user':Type['String']({'minLength':0x1,'maxLength':0x64}),'password':Type['String']({'minLength':0x1,'maxLength':0x64}),'type':Type[i(0x9a)](Type[i(0x9b)]({'minLength':0x1,'maxLength':0x64}))}),'password':Type['Object']({'password':Type['String']({'minLength':0x1,'maxLength':0x64}),'id':Type['Optional'](Type['String']({'minLength':0x1,'maxLength':0x64}))}),'twoFactor':Type[i(0x9c)]({'code':Type['String']({'minLength':0x1})})};
1
+ const L=O;function Z(){const E=['Object','Optional','String'];Z=function(){return E;};return Z();}function O(L,E){L=L-0x192;const c=Z();let t=c[L];return t;}import{Type}from'@sinclair/typebox';export const authSchemas={'query':Type[L(0x192)]({'token':Type['Optional'](Type['Boolean']())}),'credentials':Type['Object']({'user':Type['String']({'minLength':0x1,'maxLength':0x64}),'password':Type['String']({'minLength':0x1,'maxLength':0x64}),'type':Type[L(0x193)](Type[L(0x194)]({'minLength':0x1,'maxLength':0x64}))}),'password':Type['Object']({'password':Type['String']({'minLength':0x1,'maxLength':0x64}),'id':Type[L(0x193)](Type['String']({'minLength':0x1,'maxLength':0x64}))}),'twoFactor':Type[L(0x192)]({'code':Type['String']({'minLength':0x1})})};
@@ -1 +1 @@
1
- import{hashPassword}from'../../../plugins/auth/index.js';export default async function changePassword({id:i,password:n,userId:U},{pg:O}){const o=await hashPassword(n);await O['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',[o,i||U,U]);}
1
+ function O(L,E){L=L-0xfa;const c=Z();let t=c[L];return t;}import{hashPassword}from'../../../plugins/auth/index.js';function Z(){const g=['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'];Z=function(){return g;};return Z();}export default async function changePassword({id:L,password:E,userId:c},{pg:t}){const B=O,e=await hashPassword(E);await t['query'](B(0xfa),[e,L||c,c]);}
@@ -1 +1 @@
1
- import{safeUser}from'../../utils/safe-user.js';function D(){const X=['map'];D=function(){return X;};return D();}function u(i,n){i=i-0x143;const U=D();let O=U[i];return O;}export default async function getCurrentUser(i){const I=u,{user:n}=i;if(!n)return{};if(i['token']){const {jwtSignToken:U}=await import('../../../plugins/jwt.js'),O=await U(n);n['token']=O;}return n['resources']=[...new Set(n?.['permissions'][I(0x143)](o=>o['split'](':')[0x0]))],safeUser(n);}
1
+ function O(L,E){L=L-0xcc;const c=Z();let t=c[L];return t;}function Z(){const g=['token','../../../plugins/jwt.js','permissions','map'];Z=function(){return g;};return Z();}import{safeUser}from'../../utils/safe-user.js';export default async function getCurrentUser(L){const B=O,{user:E}=L;if(!E)return{};if(L[B(0xcc)]){const {jwtSignToken:c}=await import(B(0xcd)),t=await c(E);E['token']=t;}return E['resources']=[...new Set(E?.[B(0xce)][B(0xcf)](e=>e['split'](':')[0x0]))],safeUser(E);}
@@ -1 +1 @@
1
- import{ConflictError}from'../../../errors.js';import{hashPassword}from'../../../plugins/auth/index.js';function u(i,n){i=i-0xdd;const U=D();let O=U[i];return O;}function D(){const R=['regular'];D=function(){return R;};return D();}export default async function registration({user:i,password:n,type:U},{pg:O}){const T=u,o=await hashPassword(n),I=await O['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',[i,o,U||T(0xdd)]),X=I['rows'][0x0];if(!X)throw new ConflictError('Login\x20is\x20already\x20in\x20use');return{'user':X};}
1
+ import{ConflictError}from'../../../errors.js';function Z(){const X=['query','Login\x20is\x20already\x20in\x20use'];Z=function(){return X;};return Z();}function O(L,E){L=L-0x17b;const c=Z();let t=c[L];return t;}import{hashPassword}from'../../../plugins/auth/index.js';export default async function registration({user:L,password:E,type:c},{pg:t}){const r=O,e=await hashPassword(E),B=await t[r(0x17b)]('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',[L,e,c||'regular']),g=B['rows'][0x0];if(!g)throw new ConflictError(r(0x17c));return{'user':g};}
@@ -1 +1 @@
1
- import{unsupported}from'../../utils/unsupported.js';export default async function verifyTwoFactor(i,n){return unsupported('Two-factor\x20provider');}
1
+ import{unsupported}from'../../utils/unsupported.js';export default async function verifyTwoFactor(L,E){return unsupported('Two-factor\x20provider');}
@@ -1 +1 @@
1
- var i=u;function D(){var n=['image/webp','image/tiff','application/vnd.ms-powerpoint','application/vnd.oasis.opendocument.text','application/xml','application/x-rar-compressed','application/x-gzip','audio/ogg','video/mp4','application/octet-stream'];D=function(){return n;};return D();}function u(i,n){i=i-0x1a6;var U=D();var O=U[i];return O;}export default new Set(['image/jpeg','image/png','image/gif',i(0x1a6),'image/bmp',i(0x1a7),'image/svg+xml','image/x-icon','image/avif','application/pdf','application/msword','application/vnd.openxmlformats-officedocument.wordprocessingml.document','application/vnd.ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',i(0x1a8),'application/vnd.openxmlformats-officedocument.presentationml.presentation',i(0x1a9),'application/vnd.oasis.opendocument.spreadsheet','application/vnd.oasis.opendocument.presentation','text/plain','text/csv','text/markdown','application/json',i(0x1aa),'text/xml','application/geo+json','application/vnd.google-earth.kml+xml','application/vnd.google-earth.kmz','application/zip','application/x-zip-compressed','application/x-7z-compressed',i(0x1ab),'application/vnd.rar','application/gzip',i(0x1ac),'application/x-tar','audio/mpeg','audio/wav',i(0x1ad),'audio/webm','audio/mp4',i(0x1ae),'video/mpeg','video/webm','video/quicktime','video/x-msvideo',i(0x1af)]);
1
+ var L=O;function O(L,E){L=L-0x93;var c=Z();var t=c[L];return t;}export default new Set(['image/jpeg',L(0x93),L(0x94),'image/webp',L(0x95),L(0x96),'image/svg+xml','image/x-icon','image/avif','application/pdf','application/msword','application/vnd.openxmlformats-officedocument.wordprocessingml.document','application/vnd.ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','application/vnd.ms-powerpoint',L(0x97),'application/vnd.oasis.opendocument.text','application/vnd.oasis.opendocument.spreadsheet',L(0x98),'text/plain',L(0x99),L(0x9a),L(0x9b),'application/xml',L(0x9c),L(0x9d),'application/vnd.google-earth.kml+xml',L(0x9e),'application/zip',L(0x9f),'application/x-7z-compressed',L(0xa0),'application/vnd.rar','application/gzip','application/x-gzip','application/x-tar','audio/mpeg','audio/wav',L(0xa1),L(0xa2),'audio/mp4','video/mp4','video/mpeg','video/webm','video/quicktime','video/x-msvideo','application/octet-stream']);function Z(){var E=['image/png','image/gif','image/bmp','image/tiff','application/vnd.openxmlformats-officedocument.presentationml.presentation','application/vnd.oasis.opendocument.presentation','text/csv','text/markdown','application/json','text/xml','application/geo+json','application/vnd.google-earth.kmz','application/x-zip-compressed','application/x-rar-compressed','audio/ogg','audio/webm'];Z=function(){return E;};return Z();}
@@ -1 +1 @@
1
- import{fileTypeFromBuffer}from'file-type';function D(){const M=['fcore','fileDownloadQuery','verify','query','startsWith','replace','file','type','header','Cache-Control','public,\x20max-age=86400,\x20immutable','post','/api/file/upload','value','resource','get','/api/file/:token/resize','fileToken','resizeQuery','params','token','image/png','inline'];D=function(){return M;};return D();}import{getFile}from'./services/get-file.js';import{uploadFile}from'./services/upload-file.js';import{resizeFile}from'./services/resize-file.js';import{fileSchemas}from'./schema.js';function u(i,n){i=i-0xc8;const U=D();let O=U[i];return O;}export function fileRoutes(i){return async n=>{const d=u;n['get']('/api/file/:token',{'schema':{'tags':[d(0xc8),'file'],'summary':'Get\x20file\x20by\x20token','description':'Returns\x20a\x20file\x20after\x20verifying\x20its\x20signed\x20access\x20token.','access':'public','permissions':[],'params':fileSchemas['fileToken'],'querystring':fileSchemas[d(0xc9)]}},async(U,O)=>{const L=d,o=i['file'][L(0xca)](U['params']['token']),I=await getFile({'pathOrToken':o},i),X=await fileTypeFromBuffer(I),T=X?.['mime']??'application/octet-stream',R=U[L(0xcb)]['download']===!![],g=T[L(0xcc)]('image/')||T==='application/pdf',k=o['split']('/')['pop']()?.[L(0xcd)](/[^A-Za-z0-9._-]/g,'_')??L(0xce);return O[L(0xcf)](T),O[L(0xd0)]('Content-Disposition',(R||!g?'attachment':'inline')+';\x20filename=\x22'+k+'\x22')['header'](L(0xd1),L(0xd2)),O['send'](I);}),n[d(0xd3)](d(0xd4),{'schema':{'tags':['fcore','file'],'summary':'Upload\x20file','description':'Uploads\x20a\x20file\x20and\x20stores\x20its\x20metadata.','access':'user','permissions':['files:create']}},async U=>{const h=d,O=await U[h(0xce)]();if(!O)throw new Error('File\x20is\x20required');return uploadFile({'file':O,'metadata':{'name':O['filename'],'path':O['fields']['path']?.[h(0xd5)],'resource':O['fields'][h(0xd6)]?.['value'],'resourceId':O['fields']['resourceId']?.['value']},'user':U['user']},i);}),n[d(0xd7)](d(0xd8),{'schema':{'tags':['fcore','file'],'summary':'Resize\x20file','description':'Returns\x20a\x20resized\x20image\x20file.','access':'user','permissions':['files:read'],'params':fileSchemas[d(0xd9)],'querystring':fileSchemas[d(0xda)]}},async(U,O)=>{const q=d,o=await resizeFile({'pathOrToken':i[q(0xce)]?.['verify'](U[q(0xdb)][q(0xdc)]),...U['query']},i),I=await fileTypeFromBuffer(o);return O['type'](I?.['mime']??q(0xdd)),O['header']('Content-Disposition',q(0xde))[q(0xd0)]('Cache-Control','public,\x20max-age=86400,\x20immutable'),O['send'](o);});};}
1
+ import{fileTypeFromBuffer}from'file-type';function O(L,E){L=L-0xf9;const c=Z();let t=c[L];return t;}import{getFile}from'./services/get-file.js';function Z(){const G=['get','fcore','file','Get\x20file\x20by\x20token','Returns\x20a\x20file\x20after\x20verifying\x20its\x20signed\x20access\x20token.','public','fileToken','fileDownloadQuery','query','pop','Cache-Control','post','user','File\x20is\x20required','fields','Returns\x20a\x20resized\x20image\x20file.','params','token','public,\x20max-age=86400,\x20immutable','send'];Z=function(){return G;};return Z();}import{uploadFile}from'./services/upload-file.js';import{resizeFile}from'./services/resize-file.js';import{fileSchemas}from'./schema.js';export function fileRoutes(L){return async E=>{const I=O;E[I(0xf9)]('/api/file/:token',{'schema':{'tags':[I(0xfa),I(0xfb)],'summary':I(0xfc),'description':I(0xfd),'access':I(0xfe),'permissions':[],'params':fileSchemas[I(0xff)],'querystring':fileSchemas[I(0x100)]}},async(c,t)=>{const T=I,e=L[T(0xfb)]['verify'](c['params']['token']),B=await getFile({'pathOrToken':e},L),g=await fileTypeFromBuffer(B),r=g?.['mime']??'application/octet-stream',X=c[T(0x101)]['download']===!![],j=r['startsWith']('image/')||r==='application/pdf',F=e['split']('/')[T(0x102)]()?.['replace'](/[^A-Za-z0-9._-]/g,'_')??T(0xfb);return t['type'](r),t['header']('Content-Disposition',(X||!j?'attachment':'inline')+';\x20filename=\x22'+F+'\x22')['header'](T(0x103),'public,\x20max-age=86400,\x20immutable'),t['send'](B);}),E[I(0x104)]('/api/file/upload',{'schema':{'tags':['fcore','file'],'summary':'Upload\x20file','description':'Uploads\x20a\x20file\x20and\x20stores\x20its\x20metadata.','access':I(0x105),'permissions':['files:create']}},async c=>{const f=I,t=await c['file']();if(!t)throw new Error(f(0x106));return uploadFile({'file':t,'metadata':{'name':t['filename'],'path':t[f(0x107)]['path']?.['value'],'resource':t['fields']['resource']?.['value'],'resourceId':t['fields']['resourceId']?.['value']},'user':c['user']},L);}),E['get']('/api/file/:token/resize',{'schema':{'tags':['fcore','file'],'summary':'Resize\x20file','description':I(0x108),'access':'user','permissions':['files:read'],'params':fileSchemas['fileToken'],'querystring':fileSchemas['resizeQuery']}},async(c,t)=>{const A=I,e=await resizeFile({'pathOrToken':L['file']?.['verify'](c[A(0x109)][A(0x10a)]),...c[A(0x101)]},L),B=await fileTypeFromBuffer(e);return t['type'](B?.['mime']??'image/png'),t['header']('Content-Disposition','inline')['header']('Cache-Control',A(0x10b)),t[A(0x10c)](e);});};}
@@ -1 +1 @@
1
- const i=u;function u(i,n){i=i-0x15e;const U=D();let O=U[i];return O;}import{Type}from'@sinclair/typebox';function D(){const n=['Boolean','Optional','String','Object','Literal','cover','contain','inside'];D=function(){return n;};return D();}export const fileSchemas={'fileId':Type['Object']({'id':Type['String']({'minLength':0x1,'maxLength':0x80})}),'fileToken':Type['Object']({'token':Type['String']({'minLength':0x1,'maxLength':0x800})}),'fileDownloadQuery':Type['Object']({'download':Type['Optional'](Type[i(0x15e)]())}),'filePath':Type['Object']({'*':Type['String']({'minLength':0x1,'maxLength':0x400})}),'upload':Type['Object']({'file':Type['Any'](),'metadata':Type['Object']({'name':Type[i(0x15f)](Type['String']({'minLength':0x1})),'path':Type['Optional'](Type['String']({'minLength':0x1})),'entityType':Type[i(0x15f)](Type['String']({'minLength':0x1})),'entityId':Type['Optional'](Type[i(0x160)]({'minLength':0x1}))})}),'filePatch':Type['Object']({'entityType':Type[i(0x15f)](Type[i(0x160)]({'minLength':0x1})),'entityId':Type['Optional'](Type[i(0x160)]({'minLength':0x1}))}),'resizeQuery':Type[i(0x161)]({'width':Type['Optional'](Type['Integer']({'minimum':0x1,'default':0xc8})),'height':Type[i(0x15f)](Type['Integer']({'minimum':0x1})),'fit':Type[i(0x15f)](Type['Union']([Type[i(0x162)](i(0x163)),Type[i(0x162)](i(0x164)),Type['Literal']('fill'),Type['Literal'](i(0x165)),Type['Literal']('outside')]))})};
1
+ const L=O;import{Type}from'@sinclair/typebox';function O(L,E){L=L-0x144;const c=Z();let t=c[L];return t;}export const fileSchemas={'fileId':Type['Object']({'id':Type['String']({'minLength':0x1,'maxLength':0x80})}),'fileToken':Type['Object']({'token':Type[L(0x144)]({'minLength':0x1,'maxLength':0x800})}),'fileDownloadQuery':Type[L(0x145)]({'download':Type['Optional'](Type[L(0x146)]())}),'filePath':Type[L(0x145)]({'*':Type['String']({'minLength':0x1,'maxLength':0x400})}),'upload':Type['Object']({'file':Type['Any'](),'metadata':Type['Object']({'name':Type['Optional'](Type[L(0x144)]({'minLength':0x1})),'path':Type['Optional'](Type['String']({'minLength':0x1})),'entityType':Type[L(0x147)](Type['String']({'minLength':0x1})),'entityId':Type['Optional'](Type[L(0x144)]({'minLength':0x1}))})}),'filePatch':Type['Object']({'entityType':Type['Optional'](Type['String']({'minLength':0x1})),'entityId':Type['Optional'](Type[L(0x144)]({'minLength':0x1}))}),'resizeQuery':Type[L(0x145)]({'width':Type['Optional'](Type['Integer']({'minimum':0x1,'default':0xc8})),'height':Type['Optional'](Type['Integer']({'minimum':0x1})),'fit':Type['Optional'](Type['Union']([Type[L(0x148)](L(0x149)),Type['Literal']('contain'),Type['Literal']('fill'),Type['Literal'](L(0x14a)),Type[L(0x148)]('outside')]))})};function Z(){const E=['String','Object','Boolean','Optional','Literal','cover','inside'];Z=function(){return E;};return Z();}
@@ -1 +1 @@
1
- function u(i,n){i=i-0x123;var U=D();var O=U[i];return O;}import{NotFoundError}from'../../../errors.js';function D(){var O=['file','exists','pathOrToken'];D=function(){return O;};return D();}export async function getFile(i,n){var U=u;if(!n[U(0x123)])throw new Error('empty\x20file');if(!await n['file'][U(0x124)](i['pathOrToken']))throw new NotFoundError('File\x20not\x20found'+i['pathOrToken']);return n['file']['get'](i[U(0x125)]);}
1
+ function O(L,E){L=L-0x115;var c=Z();var t=c[L];return t;}import{NotFoundError}from'../../../errors.js';export async function getFile(L,E){var c=O;if(!E['file'])throw new Error('empty\x20file');if(!await E[c(0x115)]['exists'](L['pathOrToken']))throw new NotFoundError('File\x20not\x20found'+L[c(0x116)]);return E['file']['get'](L['pathOrToken']);}function Z(){var t=['file','pathOrToken'];Z=function(){return t;};return Z();}
@@ -1 +1 @@
1
- import{NotFoundError,ValidationError}from'../../../errors.js';function D(){const y=['pathOrToken','path','File\x20path\x20is\x20required','cover','logs','join','file','mime','resize','fit','toBuffer','isInteger'];D=function(){return y;};return D();}import{fileTypeFromBuffer}from'file-type';import{createHash}from'node:crypto';function u(i,n){i=i-0x143;const U=D();let O=U[i];return O;}import{mkdir,readFile,writeFile}from'node:fs/promises';import i from'node:path';import n from'sharp';export async function resizeFile(U,O){const q=u,o=U[q(0x143)]??U[q(0x144)];if(!o)throw new ValidationError(q(0x145));const I=parseDimension(U['width'],'width')??0xc8,X=parseDimension(U['height'],'height'),T=createHash('sha256')['update'](o+':'+I+':'+(X??'auto')+':'+(U['fit']??q(0x146)))['digest']('hex'),R=i['resolve'](q(0x147),'resize'),g=i[q(0x148)](R,T+'.jpg');try{return await readFile(g);}catch(h){if(h['code']!=='ENOENT')throw h;}if(!await O['file']['exists'](o))throw new NotFoundError('File\x20not\x20found');const k=await O[q(0x149)]['get'](o),d=await fileTypeFromBuffer(k);if(!d?.[q(0x14a)]['startsWith']('image/'))throw new ValidationError('Only\x20image\x20files\x20can\x20be\x20resized');const L=await n(k)[q(0x14b)]({'width':I,'height':X,'fit':U[q(0x14c)]??'cover'})[q(0x14d)]();return await mkdir(R,{'recursive':!![]}),await writeFile(g,L),L;}function parseDimension(U,O){const M=u;if(U===undefined||U==='')return undefined;const o=Number(U);if(!Number[M(0x14e)](o)||o<=0x0)throw new ValidationError(O+'\x20must\x20be\x20a\x20positive\x20integer');return o;}
1
+ function Z(){const x=['width','height','sha256','auto','fit','hex','logs','.jpg','code','file','resize','toBuffer','isInteger'];Z=function(){return x;};return Z();}import{NotFoundError,ValidationError}from'../../../errors.js';import{fileTypeFromBuffer}from'file-type';import{createHash}from'node:crypto';function O(L,E){L=L-0x1cf;const c=Z();let t=c[L];return t;}import{mkdir,readFile,writeFile}from'node:fs/promises';import L from'node:path';import E from'sharp';export async function resizeFile(c,t){const A=O,e=c['pathOrToken']??c['path'];if(!e)throw new ValidationError('File\x20path\x20is\x20required');const B=parseDimension(c['width'],A(0x1cf))??0xc8,g=parseDimension(c[A(0x1d0)],'height'),r=createHash(A(0x1d1))['update'](e+':'+B+':'+(g??A(0x1d2))+':'+(c[A(0x1d3)]??'cover'))['digest'](A(0x1d4)),X=L['resolve'](A(0x1d5),'resize'),j=L['join'](X,r+A(0x1d6));try{return await readFile(j);}catch(f){if(f[A(0x1d7)]!=='ENOENT')throw f;}if(!await t[A(0x1d8)]['exists'](e))throw new NotFoundError('File\x20not\x20found');const F=await t[A(0x1d8)]['get'](e),I=await fileTypeFromBuffer(F);if(!I?.['mime']['startsWith']('image/'))throw new ValidationError('Only\x20image\x20files\x20can\x20be\x20resized');const T=await E(F)[A(0x1d9)]({'width':B,'height':g,'fit':c['fit']??'cover'})[A(0x1da)]();return await mkdir(X,{'recursive':!![]}),await writeFile(j,T),T;}function parseDimension(c,t){const G=O;if(c===undefined||c==='')return undefined;const e=Number(c);if(!Number[G(0x1db)](e)||e<=0x0)throw new ValidationError(t+'\x20must\x20be\x20a\x20positive\x20integer');return e;}
@@ -1 +1 @@
1
- function D(){const h=['metadata','getFullYear','getDate','padStart','path','mimetype','query','file','split','rows'];D=function(){return h;};return D();}import{fileTypeFromBuffer}from'file-type';function u(i,n){i=i-0xcb;const U=D();let O=U[i];return O;}import i from'../mime.js';import{randomUUID}from'node:crypto';export async function uploadFile(n,U){const L=u,O=(n[L(0xcb)]['name']??randomUUID())['replace'](/[^a-zA-Z0-9._-]/g,'_'),o=new Date(),I=String(o[L(0xcc)]())['slice'](-0x2),X=String(o['getMonth']()+0x1)['padStart'](0x2,'0'),T=String(o[L(0xcd)]())[L(0xce)](0x2,'0'),R=n['metadata'][L(0xcf)]??(n['metadata']['resource']?n[L(0xcb)]['resource']+'/'+(n['metadata']['resourceId']??randomUUID())+'/'+O:null)??'uploads/'+I+'/'+X+'-'+T+'/'+O,g=await n['file']['toBuffer'](),k=await fileTypeFromBuffer(g);if(!i['has'](n['file'][L(0xd0)])&&(k?.['mime']?!i['has'](k['mime']):!![]))throw new Error('Unsupported\x20file\x20type:\x20'+n['file'][L(0xd0)]);await U['file']['put'](R,g);const d=await U['pg'][L(0xd1)]('\x0a\x20\x20\x20\x20\x20\x20\x20\x20INSERT\x20INTO\x20admin.files\x20(resource,\x20resource_id,\x20file_path,\x20file_type,\x20size,uploaded_name,file_name,ext,created_by)\x0a\x20\x20\x20\x20\x20\x20\x20\x20VALUES\x20($1,\x20$2,\x20$3,\x20$4,\x20$5,\x20$6,\x20$7,\x20$8,\x20$9)\x0a\x20\x20\x20\x20\x20\x20\x20\x20RETURNING\x20*\x0a\x20\x20\x20\x20\x20\x20',[n['metadata']['resource']??null,n['metadata']['resourceId']??null,R,n['file']['mimetype'],n[L(0xd2)]['file']['bytesRead'],n['metadata']['name'],O,n['file']['mimetype'][L(0xd3)]('/')['pop']()??null,n['user']?.['id']??null]);return d[L(0xd4)][0x0];}
1
+ function Z(){const f=['replace','getFullYear','padStart','path','metadata','resource','mime','Unsupported\x20file\x20type:\x20','query','resourceId','file','user'];Z=function(){return f;};return Z();}function O(L,E){L=L-0x1c1;const c=Z();let t=c[L];return t;}import{fileTypeFromBuffer}from'file-type';import L from'../mime.js';import{randomUUID}from'node:crypto';export async function uploadFile(E,c){const T=O,t=(E['metadata']['name']??randomUUID())[T(0x1c1)](/[^a-zA-Z0-9._-]/g,'_'),e=new Date(),B=String(e[T(0x1c2)]())['slice'](-0x2),g=String(e['getMonth']()+0x1)['padStart'](0x2,'0'),r=String(e['getDate']())[T(0x1c3)](0x2,'0'),X=E['metadata'][T(0x1c4)]??(E[T(0x1c5)][T(0x1c6)]?E['metadata'][T(0x1c6)]+'/'+(E['metadata']['resourceId']??randomUUID())+'/'+t:null)??'uploads/'+B+'/'+g+'-'+r+'/'+t,j=await E['file']['toBuffer'](),F=await fileTypeFromBuffer(j);if(!L['has'](E['file']['mimetype'])&&(F?.[T(0x1c7)]?!L['has'](F[T(0x1c7)]):!![]))throw new Error(T(0x1c8)+E['file']['mimetype']);await c['file']['put'](X,j);const I=await c['pg'][T(0x1c9)]('\x0a\x20\x20\x20\x20\x20\x20\x20\x20INSERT\x20INTO\x20admin.files\x20(resource,\x20resource_id,\x20file_path,\x20file_type,\x20size,uploaded_name,file_name,ext,created_by)\x0a\x20\x20\x20\x20\x20\x20\x20\x20VALUES\x20($1,\x20$2,\x20$3,\x20$4,\x20$5,\x20$6,\x20$7,\x20$8,\x20$9)\x0a\x20\x20\x20\x20\x20\x20\x20\x20RETURNING\x20*\x0a\x20\x20\x20\x20\x20\x20',[E[T(0x1c5)]['resource']??null,E['metadata'][T(0x1ca)]??null,X,E['file']['mimetype'],E['file'][T(0x1cb)]['bytesRead'],E['metadata']['name'],t,E[T(0x1cb)]['mimetype']['split']('/')['pop']()??null,E[T(0x1cc)]?.['id']??null]);return I['rows'][0x0];}
@@ -1 +1 @@
1
- import{ForbiddenError}from'../../errors.js';import{listResources}from'./services/list-resources.js';import{getResource}from'./services/get-resource.js';import{createResource}from'./services/create-resource.js';import{updateResource}from'./services/update-resource.js';import{deleteResource}from'./services/delete-resource.js';import{listResourceRelation}from'./services/list-resource-relation.js';function D(){const R=['/api/resource/:resource/search','fcore','get','resource','query','Export\x20resource\x20records','params','/api/resource/:resource','Creates\x20a\x20record\x20in\x20a\x20registered\x20resource.','Get\x20resource\x20record','user','resourceId','body','Deletes\x20a\x20record\x20from\x20a\x20registered\x20resource.','Upload\x20resource\x20file','permissions','path','Returns\x20related\x20records\x20for\x20a\x20resource\x20record.','Create\x20resource\x20relation','resourceIdRelation','/api/resource/:resource/:id/:relation/:relationId','Deletes\x20a\x20relation\x20from\x20a\x20resource\x20record.','resourceIdRelationId','Updates\x20a\x20related\x20resource\x20record.'];D=function(){return R;};return D();}import{createResourceRelation}from'./services/create-resource-relation.js';import{updateResourceRelation}from'./services/update-resource-relation.js';import{deleteResourceRelation}from'./services/delete-resource-relation.js';import{searchResource}from'./services/search-resource.js';import{exportResource}from'./services/export-resource.js';import{suggestResource}from'./services/suggest-resource.js';function u(i,n){i=i-0x99;const U=D();let O=U[i];return O;}import{resourceSchemas}from'./schema.js';import{uploadFile}from'../file/services/upload-file.js';const user=i=>i['user'];export function resourceRoutes(i){return async n=>{const X=u;n['get'](X(0x99),{'schema':{'tags':[X(0x9a),'resource'],'summary':'Search\x20resource','description':'Searches\x20records\x20in\x20a\x20registered\x20resource.','access':'user','permissions':[],'params':resourceSchemas['resource']}},async U=>searchResource({...U['query'],...U['params'],'user':user(U)},i)),n[X(0x9b)]('/api/suggest/:resource/:field',{'schema':{'tags':['fcore',X(0x9c)],'summary':'Suggest\x20resource\x20values','description':'Returns\x20suggested\x20values\x20for\x20a\x20resource\x20field.','access':'user','permissions':[],'params':resourceSchemas['resourceField'],'querystring':resourceSchemas['suggestQuery']}},async U=>suggestResource({...U[X(0x9d)],...U['params'],'user':user(U)},i)),n[X(0x9b)]('/api/resource/:resource/export',{'schema':{'tags':['fcore','resource'],'summary':X(0x9e),'description':'Exports\x20readable\x20records\x20from\x20a\x20registered\x20resource.','access':'user','permissions':['*:read'],'params':resourceSchemas['exportResource'],'querystring':resourceSchemas['exportResourceQuery']}},async U=>exportResource({...U['query'],...U[X(0x9f)],'user':user(U)},i)),n[X(0x9b)](X(0xa0),{'schema':{'tags':['fcore',X(0x9c)],'summary':'List\x20resource\x20records','description':'Returns\x20records\x20from\x20a\x20registered\x20resource.','access':'user','permissions':[],'params':resourceSchemas['resource']}},async U=>listResources({...U['query'],...U['params'],'user':user(U)},i)),n['post'](X(0xa0),{'schema':{'tags':[X(0x9a),'resource'],'summary':'Create\x20resource\x20record','description':X(0xa1),'access':'user','permissions':[],'params':resourceSchemas['resource']}},async U=>createResource({...U['params'],'data':U['body'],'user':user(U)},i)),n['get']('/api/resource/:resource/:id',{'schema':{'tags':[X(0x9a),'resource'],'summary':X(0xa2),'description':'Returns\x20one\x20record\x20from\x20a\x20registered\x20resource.','access':X(0xa3),'permissions':[],'params':resourceSchemas['resourceId'],'querystring':resourceSchemas['resourceIncludeQuery']}},async U=>getResource({...U['query'],...U['params'],'user':user(U)},i)),n['put']('/api/resource/:resource/:id',{'schema':{'tags':['fcore','resource'],'summary':'Update\x20resource\x20record','description':'Updates\x20a\x20record\x20in\x20a\x20registered\x20resource.','access':'user','permissions':[],'params':resourceSchemas[X(0xa4)]}},async U=>updateResource({...U['params'],'patch':U[X(0xa5)],'user':user(U)},i)),n['delete']('/api/resource/:resource/:id',{'schema':{'tags':['fcore','resource'],'summary':'Delete\x20resource\x20record','description':X(0xa6),'access':X(0xa3),'permissions':[],'params':resourceSchemas['resourceId']}},async U=>deleteResource({...U['params'],'user':user(U)},i)),n['post']('/api/resource/:resource/:id/upload',{'schema':{'tags':['fcore',X(0x9c)],'summary':X(0xa7),'description':'Uploads\x20a\x20file\x20to\x20a\x20Resource\x20record\x20and\x20stores\x20its\x20metadata.','access':X(0xa3),'permissions':[],'params':resourceSchemas['uploadResourceFile']}},async U=>{const T=X,O=await U['file']();if(!O)throw new Error('File\x20is\x20required');const o=U['params']['resource'],I=U['params']['id'];if(U['user']?.['type']!=='admin'&&!U['user']?.[T(0xa8)]['includes'](o+':update'))throw new ForbiddenError('Missing\x20permission:\x20'+o+':update');return uploadFile({'file':O,'metadata':{'name':O['filename'],'path':O['fields'][T(0xa9)]?.['value'],'resource':o,'resourceId':I},'user':U[T(0xa3)]},i);}),n['get']('/api/resource/:resource/:id/:relation',{'schema':{'tags':[X(0x9a),'resource'],'summary':'List\x20resource\x20relations','description':X(0xaa),'access':'user','permissions':[],'schema':{'params':resourceSchemas['resourceIdRelation']}}},async U=>listResourceRelation({...U['query'],...U['params'],'user':user(U)},i)),n['post']('/api/resource/:resource/:id/:relation',{'schema':{'tags':['fcore','resource'],'summary':X(0xab),'description':'Creates\x20a\x20relation\x20for\x20a\x20resource\x20record.','access':'user','permissions':[],'params':resourceSchemas[X(0xac)]}},async U=>createResourceRelation({...U['params'],'data':U['body'],'user':user(U)},i)),n['delete'](X(0xad),{'schema':{'tags':[X(0x9a),'resource'],'summary':'Delete\x20resource\x20relation','description':X(0xae),'access':X(0xa3),'permissions':[],'params':resourceSchemas[X(0xaf)]}},async U=>deleteResourceRelation({...U['params'],'user':user(U)},i)),n['put'](X(0xad),{'schema':{'tags':[X(0x9a),'resource'],'summary':'Update\x20resource\x20relation','description':X(0xb0),'access':'user','permissions':[],'params':resourceSchemas[X(0xaf)]}},async U=>updateResourceRelation({...U['params'],'data':U['body'],'user':user(U)},i));};}
1
+ import{ForbiddenError}from'../../errors.js';import{listResources}from'./services/list-resources.js';import{getResource}from'./services/get-resource.js';import{createResource}from'./services/create-resource.js';import{updateResource}from'./services/update-resource.js';import{deleteResource}from'./services/delete-resource.js';function Z(){const X=['get','Search\x20resource','/api/suggest/:resource/:field','fcore','resource','Returns\x20suggested\x20values\x20for\x20a\x20resource\x20field.','suggestQuery','*:read','exportResourceQuery','query','List\x20resource\x20records','Returns\x20records\x20from\x20a\x20registered\x20resource.','params','Creates\x20a\x20record\x20in\x20a\x20registered\x20resource.','body','/api/resource/:resource/:id','resourceId','resourceIncludeQuery','put','Update\x20resource\x20record','Updates\x20a\x20record\x20in\x20a\x20registered\x20resource.','user','Deletes\x20a\x20record\x20from\x20a\x20registered\x20resource.','/api/resource/:resource/:id/upload','uploadResourceFile','type',':update','filename','fields','Create\x20resource\x20relation','resourceIdRelationId','Updates\x20a\x20related\x20resource\x20record.'];Z=function(){return X;};return Z();}import{listResourceRelation}from'./services/list-resource-relation.js';import{createResourceRelation}from'./services/create-resource-relation.js';import{updateResourceRelation}from'./services/update-resource-relation.js';import{deleteResourceRelation}from'./services/delete-resource-relation.js';import{searchResource}from'./services/search-resource.js';import{exportResource}from'./services/export-resource.js';import{suggestResource}from'./services/suggest-resource.js';import{resourceSchemas}from'./schema.js';import{uploadFile}from'../file/services/upload-file.js';const user=L=>L['user'];function O(L,E){L=L-0x122;const c=Z();let t=c[L];return t;}export function resourceRoutes(L){return async E=>{const g=O;E[g(0x122)]('/api/resource/:resource/search',{'schema':{'tags':['fcore','resource'],'summary':g(0x123),'description':'Searches\x20records\x20in\x20a\x20registered\x20resource.','access':'user','permissions':[],'params':resourceSchemas['resource']}},async c=>searchResource({...c['query'],...c['params'],'user':user(c)},L)),E['get'](g(0x124),{'schema':{'tags':[g(0x125),g(0x126)],'summary':'Suggest\x20resource\x20values','description':g(0x127),'access':'user','permissions':[],'params':resourceSchemas['resourceField'],'querystring':resourceSchemas[g(0x128)]}},async c=>suggestResource({...c['query'],...c['params'],'user':user(c)},L)),E['get']('/api/resource/:resource/export',{'schema':{'tags':['fcore','resource'],'summary':'Export\x20resource\x20records','description':'Exports\x20readable\x20records\x20from\x20a\x20registered\x20resource.','access':'user','permissions':[g(0x129)],'params':resourceSchemas['exportResource'],'querystring':resourceSchemas[g(0x12a)]}},async c=>exportResource({...c[g(0x12b)],...c['params'],'user':user(c)},L)),E['get']('/api/resource/:resource',{'schema':{'tags':['fcore','resource'],'summary':g(0x12c),'description':g(0x12d),'access':'user','permissions':[],'params':resourceSchemas['resource']}},async c=>listResources({...c['query'],...c[g(0x12e)],'user':user(c)},L)),E['post']('/api/resource/:resource',{'schema':{'tags':[g(0x125),'resource'],'summary':'Create\x20resource\x20record','description':g(0x12f),'access':'user','permissions':[],'params':resourceSchemas[g(0x126)]}},async c=>createResource({...c['params'],'data':c[g(0x130)],'user':user(c)},L)),E[g(0x122)](g(0x131),{'schema':{'tags':[g(0x125),'resource'],'summary':'Get\x20resource\x20record','description':'Returns\x20one\x20record\x20from\x20a\x20registered\x20resource.','access':'user','permissions':[],'params':resourceSchemas[g(0x132)],'querystring':resourceSchemas[g(0x133)]}},async c=>getResource({...c[g(0x12b)],...c['params'],'user':user(c)},L)),E[g(0x134)]('/api/resource/:resource/:id',{'schema':{'tags':['fcore','resource'],'summary':g(0x135),'description':g(0x136),'access':g(0x137),'permissions':[],'params':resourceSchemas['resourceId']}},async c=>updateResource({...c[g(0x12e)],'patch':c['body'],'user':user(c)},L)),E['delete']('/api/resource/:resource/:id',{'schema':{'tags':['fcore','resource'],'summary':'Delete\x20resource\x20record','description':g(0x138),'access':'user','permissions':[],'params':resourceSchemas[g(0x132)]}},async c=>deleteResource({...c['params'],'user':user(c)},L)),E['post'](g(0x139),{'schema':{'tags':['fcore','resource'],'summary':'Upload\x20resource\x20file','description':'Uploads\x20a\x20file\x20to\x20a\x20Resource\x20record\x20and\x20stores\x20its\x20metadata.','access':g(0x137),'permissions':[],'params':resourceSchemas[g(0x13a)]}},async c=>{const r=g,t=await c['file']();if(!t)throw new Error('File\x20is\x20required');const e=c['params']['resource'],B=c['params']['id'];if(c['user']?.[r(0x13b)]!=='admin'&&!c[r(0x137)]?.['permissions']['includes'](e+r(0x13c)))throw new ForbiddenError('Missing\x20permission:\x20'+e+r(0x13c));return uploadFile({'file':t,'metadata':{'name':t[r(0x13d)],'path':t[r(0x13e)]['path']?.['value'],'resource':e,'resourceId':B},'user':c['user']},L);}),E[g(0x122)]('/api/resource/:resource/:id/:relation',{'schema':{'tags':['fcore','resource'],'summary':'List\x20resource\x20relations','description':'Returns\x20related\x20records\x20for\x20a\x20resource\x20record.','access':'user','permissions':[],'schema':{'params':resourceSchemas['resourceIdRelation']}}},async c=>listResourceRelation({...c['query'],...c[g(0x12e)],'user':user(c)},L)),E['post']('/api/resource/:resource/:id/:relation',{'schema':{'tags':['fcore',g(0x126)],'summary':g(0x13f),'description':'Creates\x20a\x20relation\x20for\x20a\x20resource\x20record.','access':'user','permissions':[],'params':resourceSchemas['resourceIdRelation']}},async c=>createResourceRelation({...c['params'],'data':c['body'],'user':user(c)},L)),E['delete']('/api/resource/:resource/:id/:relation/:relationId',{'schema':{'tags':['fcore',g(0x126)],'summary':'Delete\x20resource\x20relation','description':'Deletes\x20a\x20relation\x20from\x20a\x20resource\x20record.','access':'user','permissions':[],'params':resourceSchemas[g(0x140)]}},async c=>deleteResourceRelation({...c['params'],'user':user(c)},L)),E['put']('/api/resource/:resource/:id/:relation/:relationId',{'schema':{'tags':['fcore','resource'],'summary':'Update\x20resource\x20relation','description':g(0x141),'access':'user','permissions':[],'params':resourceSchemas['resourceIdRelationId']}},async c=>updateResourceRelation({...c['params'],'data':c['body'],'user':user(c)},L));};}
@@ -1 +1 @@
1
- const i=u;function D(){const n=['Object','Optional','String','Integer','Any','Array'];D=function(){return n;};return D();}import{Type}from'@sinclair/typebox';function u(i,n){i=i-0x106;const U=D();let O=U[i];return O;}export const identifier=Type['String']({'minLength':0x1,'maxLength':0x80,'pattern':'^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$'});export const resourceSchemas={'dictionaryName':Type['Object']({'name':identifier}),'resource':Type[i(0x106)]({'resource':identifier}),'exportResource':Type['Object']({'resource':identifier}),'resourceField':Type[i(0x106)]({'resource':identifier,'field':identifier}),'suggestQuery':Type['Object']({'q':Type[i(0x107)](Type[i(0x108)]()),'search':Type['Optional'](Type[i(0x108)]()),'limit':Type['Optional'](Type[i(0x109)]({'minimum':0x1,'maximum':0xc8}))}),'resourceId':Type['Object']({'resource':identifier,'id':identifier}),'resourceIncludeQuery':Type['Object']({'include':Type[i(0x107)](Type['String']({'minLength':0x1}))}),'resourceIdRelation':Type[i(0x106)]({'resource':identifier,'id':identifier,'relation':identifier}),'resourceIdRelationId':Type['Object']({'resource':identifier,'id':identifier,'relation':identifier,'relationId':identifier}),'uploadResourceFile':Type['Object']({'resource':identifier,'id':identifier}),'uploadResourceFileBody':Type[i(0x106)]({'file':Type[i(0x10a)](),'fileName':Type['String']({'minLength':0x1,'maxLength':0xff})}),'exportResourceQuery':Type['Object']({'filter':Type['Optional'](Type['Record'](Type['String'](),Type['Unknown']())),'sort':Type['Optional'](Type['Array'](Type[i(0x108)]({'minLength':0x1}))),'search':Type['Optional'](Type['String']()),'limit':Type['Optional'](Type['Integer']({'minimum':0x1,'maximum':0xc8})),'offset':Type['Optional'](Type['Integer']({'minimum':0x0})),'fields':Type['Optional'](Type[i(0x10b)](identifier))})};
1
+ const L=O;function Z(){const E=['Object','String','Optional','Integer','Record'];Z=function(){return E;};return Z();}import{Type}from'@sinclair/typebox';export const identifier=Type['String']({'minLength':0x1,'maxLength':0x80,'pattern':'^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$'});function O(L,E){L=L-0x6f;const c=Z();let t=c[L];return t;}export const resourceSchemas={'dictionaryName':Type[L(0x6f)]({'name':identifier}),'resource':Type['Object']({'resource':identifier}),'exportResource':Type[L(0x6f)]({'resource':identifier}),'resourceField':Type[L(0x6f)]({'resource':identifier,'field':identifier}),'suggestQuery':Type[L(0x6f)]({'q':Type['Optional'](Type[L(0x70)]()),'search':Type[L(0x71)](Type['String']()),'limit':Type['Optional'](Type[L(0x72)]({'minimum':0x1,'maximum':0xc8}))}),'resourceId':Type['Object']({'resource':identifier,'id':identifier}),'resourceIncludeQuery':Type['Object']({'include':Type['Optional'](Type[L(0x70)]({'minLength':0x1}))}),'resourceIdRelation':Type[L(0x6f)]({'resource':identifier,'id':identifier,'relation':identifier}),'resourceIdRelationId':Type['Object']({'resource':identifier,'id':identifier,'relation':identifier,'relationId':identifier}),'uploadResourceFile':Type['Object']({'resource':identifier,'id':identifier}),'uploadResourceFileBody':Type[L(0x6f)]({'file':Type['Any'](),'fileName':Type[L(0x70)]({'minLength':0x1,'maxLength':0xff})}),'exportResourceQuery':Type['Object']({'filter':Type['Optional'](Type[L(0x73)](Type['String'](),Type['Unknown']())),'sort':Type[L(0x71)](Type['Array'](Type['String']({'minLength':0x1}))),'search':Type[L(0x71)](Type[L(0x70)]()),'limit':Type[L(0x71)](Type[L(0x72)]({'minimum':0x1,'maximum':0xc8})),'offset':Type['Optional'](Type[L(0x72)]({'minimum':0x0})),'fields':Type['Optional'](Type['Array'](identifier))})};