@opengis/fcore 0.0.1-beta.7 → 0.0.1-beta.9

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 (99) 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.js +1 -1
  7. package/dist/fcore.js +1 -1
  8. package/dist/migrations/cli.js +1 -1
  9. package/dist/migrations/runner.js +1 -1
  10. package/dist/modules/auth/adduser-cli.js +1 -1
  11. package/dist/modules/auth/passwd-cli.js +1 -1
  12. package/dist/modules/auth/permission-cli.js +1 -1
  13. package/dist/modules/auth/route.js +1 -1
  14. package/dist/modules/auth/schema.js +1 -1
  15. package/dist/modules/auth/services/change-password.js +1 -1
  16. package/dist/modules/auth/services/get-current-user.js +1 -1
  17. package/dist/modules/auth/services/registration.js +1 -1
  18. package/dist/modules/auth/services/verify-two-factor.js +1 -1
  19. package/dist/modules/file/mime.js +1 -1
  20. package/dist/modules/file/route.js +1 -1
  21. package/dist/modules/file/schema.js +1 -1
  22. package/dist/modules/file/services/get-file.js +1 -1
  23. package/dist/modules/file/services/resize-file.js +1 -1
  24. package/dist/modules/file/services/upload-file.js +1 -1
  25. package/dist/modules/resource/route.js +1 -1
  26. package/dist/modules/resource/schema.js +1 -1
  27. package/dist/modules/resource/services/add-note.js +1 -1
  28. package/dist/modules/resource/services/add-resource-file.js +1 -1
  29. package/dist/modules/resource/services/create-resource-relation.js +1 -1
  30. package/dist/modules/resource/services/create-resource.js +1 -1
  31. package/dist/modules/resource/services/delete-resource-relation.js +1 -1
  32. package/dist/modules/resource/services/delete-resource.js +1 -1
  33. package/dist/modules/resource/services/export-resource.js +1 -1
  34. package/dist/modules/resource/services/get-resource.js +1 -1
  35. package/dist/modules/resource/services/list-resource-relation.js +1 -1
  36. package/dist/modules/resource/services/list-resources.js +1 -1
  37. package/dist/modules/resource/services/search-resource.js +1 -1
  38. package/dist/modules/resource/services/suggest-resource.js +1 -1
  39. package/dist/modules/resource/services/update-resource-relation.js +1 -1
  40. package/dist/modules/resource/services/update-resource.js +1 -1
  41. package/dist/modules/resource/services/upload-resource-file.js +1 -1
  42. package/dist/modules/system/route.js +1 -1
  43. package/dist/modules/system/schema.js +1 -1
  44. package/dist/modules/system/services/check-system.js +1 -1
  45. package/dist/modules/system/services/get-access.js +1 -1
  46. package/dist/modules/system/services/get-api-list.js +1 -1
  47. package/dist/modules/system/services/get-audit-log.js +1 -1
  48. package/dist/modules/system/services/get-dictionary.js +1 -1
  49. package/dist/modules/system/services/get-system-log.js +1 -1
  50. package/dist/modules/system/services/get-system-settings.js +1 -1
  51. package/dist/modules/system/services/list-dictionaries.js +1 -1
  52. package/dist/modules/system/services/set-access.js +1 -1
  53. package/dist/modules/system/services/update-dictionary.js +1 -1
  54. package/dist/modules/system/services/update-system-settings.js +1 -1
  55. package/dist/modules/utils/require-admin.js +1 -1
  56. package/dist/modules/utils/safe-user.js +1 -1
  57. package/dist/modules/utils/unsupported.js +1 -1
  58. package/dist/plugins/audit/audit.js +1 -1
  59. package/dist/plugins/audit/services/write-audit.js +1 -1
  60. package/dist/plugins/auth/get-user-permissions.js +1 -1
  61. package/dist/plugins/auth/index.d.ts.map +1 -1
  62. package/dist/plugins/auth/index.js +1 -1
  63. package/dist/plugins/auth/verifyUser.js +1 -1
  64. package/dist/plugins/dictionary.js +1 -1
  65. package/dist/plugins/file.js +1 -1
  66. package/dist/plugins/jwt.js +1 -1
  67. package/dist/plugins/logger/index.js +1 -1
  68. package/dist/plugins/logger/transport.js +1 -1
  69. package/dist/plugins/pg.js +1 -1
  70. package/dist/plugins/redis.js +1 -1
  71. package/dist/plugins/resource/resource.js +1 -1
  72. package/dist/plugins/resource/resource.registry.js +1 -1
  73. package/dist/plugins/resource/resource.types.d.ts +6 -4
  74. package/dist/plugins/resource/resource.types.d.ts.map +1 -1
  75. package/dist/plugins/resource/services/add-dictionary-lookup-data.js +1 -1
  76. package/dist/plugins/resource/services/add-file-token.js +1 -1
  77. package/dist/plugins/resource/services/add-table-lookup-data.d.ts.map +1 -1
  78. package/dist/plugins/resource/services/add-table-lookup-data.js +1 -1
  79. package/dist/plugins/resource/services/create-relation.js +1 -1
  80. package/dist/plugins/resource/services/create.js +1 -1
  81. package/dist/plugins/resource/services/delete-relation.js +1 -1
  82. package/dist/plugins/resource/services/delete.js +1 -1
  83. package/dist/plugins/resource/services/find-one.js +1 -1
  84. package/dist/plugins/resource/services/find-relation.js +1 -1
  85. package/dist/plugins/resource/services/find.js +1 -1
  86. package/dist/plugins/resource/services/update-relation.js +1 -1
  87. package/dist/plugins/resource/services/update.js +1 -1
  88. package/dist/plugins/resource/utils/auto-index.js +1 -1
  89. package/dist/plugins/resource/utils/fields.js +1 -1
  90. package/dist/plugins/resource/utils/filters.js +1 -1
  91. package/dist/plugins/resource/utils/permissions.js +1 -1
  92. package/dist/plugins/resource/utils/sort.js +1 -1
  93. package/dist/plugins/resource/utils/sql.js +1 -1
  94. package/dist/shared/getIP.js +1 -1
  95. package/migrations/20260903130000_move_notes_files_to_admin.sql +17 -17
  96. package/migrations/20260903140000_settings_nulls_not_distinct.sql +18 -18
  97. package/migrations/20260905120000_add_user_foreign_keys.sql +42 -42
  98. package/migrations/20260907090000_core_schema.sql +32 -0
  99. package/package.json +2 -2
package/LICENSE CHANGED
@@ -1,3 +1,3 @@
1
- Copyright (c) OpenGIS. All rights reserved.
2
-
3
- Proprietary and confidential.
1
+ Copyright (c) OpenGIS. All rights reserved.
2
+
3
+ Proprietary and confidential.
package/README.md CHANGED
@@ -1,72 +1,72 @@
1
- # @opengis/fcore
2
-
3
- Reusable backend foundation for OpenGIS Node.js applications: config, typed application context, PostgreSQL, Redis, S3 file storage, audit, trusted Resource CRUD, Core modules, Fastify integration and SQL migration runner.
4
-
5
- ## Install
6
-
7
- ```bash
8
- npm install @opengis/fcore
9
- ```
10
-
11
- ## Bootstrap
12
-
13
- ```ts
14
- import { createFCore } from '@opengis/fcore';
15
- import resources from './resources/index.js';
16
-
17
- export const ctx = await createFCore({ resources });
18
- ```
19
-
20
- ```ts
21
- import Fastify from 'fastify';
22
- import fcoreFastify from '@opengis/fcore/fastify';
23
- import { ctx } from './app.js';
24
-
25
- const app = Fastify();
26
- await app.register(fcoreFastify, { ctx });
27
- await app.listen({ port: ctx.config.port });
28
- ```
29
-
30
- ## Resource
31
-
32
- All dynamic table/column identifiers come from registered `ResourceContract` metadata. Values are SQL parameters.
33
-
34
- ## Migrations
35
-
36
- Project SQL files stay in `./migrations`. Build the package/application, then run `fcore-migrate` or import `runMigrations()`.
37
-
38
- ## Module service convention
39
-
40
- Module services are plain async functions with the canonical `service(params, ctx)` signature. `ctx` is passed explicitly from `fastify.ts` to each module `route.ts`; there is no `service.ts` or `createService()` factory.
41
-
42
- ## Structure
43
-
44
- ```bash
45
- @opengis/fcore
46
- ├── src/
47
- │ ├── plugins/
48
- │ │ ├── logger/
49
- │ │ ├── redis/
50
- │ │ ├── pg/
51
- │ │ ├── file/
52
- │ │ ├── audit/
53
- │ │ └── resource/
54
- │ ├── modules/
55
- │ │ ├── auth/
56
- │ │ ├── access/
57
- │ │ ├── resource/
58
- │ │ ├── file/
59
- │ │ ├── template/
60
- │ │ └── system/
61
- │ ├── migrations/
62
- │ ├── config.ts # loadConfig
63
- │ ├── context.ts # createContext, set, get
64
- │ ├── errors.ts # standard Errors
65
- │ ├── fastify.ts # fastify Plugins
66
- │ ├── fcore.ts # createFcore
67
- │ └── index.ts # export type, methods, etc
68
- ├── test/
69
- ├── engineering/
70
- ├── package.json
71
- └── tsconfig.json
1
+ # @opengis/fcore
2
+
3
+ Reusable backend foundation for OpenGIS Node.js applications: config, typed application context, PostgreSQL, Redis, S3 file storage, audit, trusted Resource CRUD, Core modules, Fastify integration and SQL migration runner.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @opengis/fcore
9
+ ```
10
+
11
+ ## Bootstrap
12
+
13
+ ```ts
14
+ import { createFCore } from '@opengis/fcore';
15
+ import resources from './resources/index.js';
16
+
17
+ export const ctx = await createFCore({ resources });
18
+ ```
19
+
20
+ ```ts
21
+ import Fastify from 'fastify';
22
+ import fcoreFastify from '@opengis/fcore/fastify';
23
+ import { ctx } from './app.js';
24
+
25
+ const app = Fastify();
26
+ await app.register(fcoreFastify, { ctx });
27
+ await app.listen({ port: ctx.config.port });
28
+ ```
29
+
30
+ ## Resource
31
+
32
+ All dynamic table/column identifiers come from registered `ResourceContract` metadata. Values are SQL parameters.
33
+
34
+ ## Migrations
35
+
36
+ Project SQL files stay in `./migrations`. Build the package/application, then run `fcore-migrate` or import `runMigrations()`.
37
+
38
+ ## Module service convention
39
+
40
+ Module services are plain async functions with the canonical `service(params, ctx)` signature. `ctx` is passed explicitly from `fastify.ts` to each module `route.ts`; there is no `service.ts` or `createService()` factory.
41
+
42
+ ## Structure
43
+
44
+ ```bash
45
+ @opengis/fcore
46
+ ├── src/
47
+ │ ├── plugins/
48
+ │ │ ├── logger/
49
+ │ │ ├── redis/
50
+ │ │ ├── pg/
51
+ │ │ ├── file/
52
+ │ │ ├── audit/
53
+ │ │ └── resource/
54
+ │ ├── modules/
55
+ │ │ ├── auth/
56
+ │ │ ├── access/
57
+ │ │ ├── resource/
58
+ │ │ ├── file/
59
+ │ │ ├── template/
60
+ │ │ └── system/
61
+ │ ├── migrations/
62
+ │ ├── config.ts # loadConfig
63
+ │ ├── context.ts # createContext, set, get
64
+ │ ├── errors.ts # standard Errors
65
+ │ ├── fastify.ts # fastify Plugins
66
+ │ ├── fcore.ts # createFcore
67
+ │ └── index.ts # export type, methods, etc
68
+ ├── test/
69
+ ├── engineering/
70
+ ├── package.json
71
+ └── tsconfig.json
72
72
  ```
package/dist/config.js CHANGED
@@ -1 +1 @@
1
- function z(C,N){C=C-0x1b7;const r=U();let p=r[C];return p;}import'dotenv/config';const DEFAULT_LOG_RESPONSE_STATUS_CODES=[0x193,0x199,0x19d,0x19f,0x1ad];function required(C){const N=process.env[C];if(!N)throw new Error('Missing\x20environment\x20variable:\x20'+C);return N;}export function loadConfig(C={}){const p=z,N={'env':process.env.NODE_ENV??'development','debug':process.env.DEBUG===p(0x1b7),'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')['split'](','),'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'](r=>r-0x0):DEFAULT_LOG_RESPONSE_STATUS_CODES,'directory':process.env.LOG_DIRECTORY||process['cwd']()+'/log'},'pg':{'host':process.env.PG_HOST??'localhost','port':Number(process.env.PG_PORT??0x1538),'database':process.env.PG_DATABASE??'','user':process.env.PG_USER??'','password':process.env.PG_PASSWORD??''},'redis':{'host':process.env.REDIS_HOST??'','port':Number(process.env.REDIS_PORT??0x18eb),'password':process.env.REDIS_PASSWORD,'lazyConnect':!![],'db':process.env.REDIS_DB?Number(process.env.REDIS_DB):undefined},'s3':{'endpoint':process.env.S3_ENDPOINT,'region':process.env.S3_REGION??'us-east-1','bucket':process.env.S3_BUCKET??'','accessKey':process.env.S3_ACCESS_KEY,'secretKey':process.env.S3_SECRET_KEY,'folder':process.env.S3_FOLDER,'forcePathStyle':process.env.S3_FORCE_PATH_STYLE!=='false','tokenSecret':process.env.FILE_TOKEN_SECRET,'tokenTtl':Number(process.env.FILE_TOKEN_TTL??0xe10)},'auth':{'accessToken':process.env.AUTH_ACCESS_TOKEN||'Ch7QR4e73Jg0wx0xOjm','user':process.env.AUTH_USER?JSON['parse'](process.env.AUTH_USER):undefined,'sessionTimeout':+(process.env.AUTH_SESSION_TIMEOUT||0x258),'secret':process.env.AUTH_SECRET??'x5y30KBsEKCENT04tu6549Vxx3No1ztJ2q2K8r79S59420RaZ5','cookieName':process.env.AUTH_COOKIE_NAME??'session_user_auth','jwtSecret':process.env.AUTH_JWT_SECRET??p(0x1b8),'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||p(0x1b7)),'secure':Boolean(process.env.AUTH_COOKIE_OPTIONS_SECURE||'true'),'sameSite':process.env.AUTH_COOKIE_OPTIONS_SAME_SITE&&[p(0x1b9),'strict','none'][p(0x1ba)](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{...N,...C,'logger':{...N['logger'],...C['logger']},'pg':{...N['pg'],...C['pg']},'redis':{...N[p(0x1bb)],...C[p(0x1bb)]},'s3':{...N['s3'],...C['s3']},'auth':{...N['auth'],...C[p(0x1bc)]}};}export{required as requireEnv};function U(){const c=['true','0ua4b1Tz21m47z13U3EO0uN9e0WE7hqRFbcZ72cbdWqZBzemf9cAU865xan1s81TdNpUKKfF','lax','includes','redis','auth'];U=function(){return c;};return U();}
1
+ function c(J,e){J=J-0x8e;const p=L();let b=p[J];return b;}import'dotenv/config';const DEFAULT_LOG_RESPONSE_STATUS_CODES=[0x193,0x199,0x19d,0x19f,0x1ad];function L(){const F=['false','split','/log','Ch7QR4e73Jg0wx0xOjm','parse','x5y30KBsEKCENT04tu6549Vxx3No1ztJ2q2K8r79S59420RaZ5','none','logger','auth'];L=function(){return F;};return L();}function required(J){const e=process.env[J];if(!e)throw new Error('Missing\x20environment\x20variable:\x20'+J);return e;}export function loadConfig(J={}){const b=c,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===b(0x8e),'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')[b(0x8f)](','),'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'](p=>p-0x0):DEFAULT_LOG_RESPONSE_STATUS_CODES,'directory':process.env.LOG_DIRECTORY||process['cwd']()+b(0x90)},'pg':{'host':process.env.PG_HOST??'localhost','port':Number(process.env.PG_PORT??0x1538),'database':process.env.PG_DATABASE??'','user':process.env.PG_USER??'','password':process.env.PG_PASSWORD??''},'redis':{'host':process.env.REDIS_HOST??'','port':Number(process.env.REDIS_PORT??0x18eb),'password':process.env.REDIS_PASSWORD,'lazyConnect':!![],'db':process.env.REDIS_DB?Number(process.env.REDIS_DB):undefined},'s3':{'endpoint':process.env.S3_ENDPOINT,'region':process.env.S3_REGION??'us-east-1','bucket':process.env.S3_BUCKET??'','accessKey':process.env.S3_ACCESS_KEY,'secretKey':process.env.S3_SECRET_KEY,'folder':process.env.S3_FOLDER,'forcePathStyle':process.env.S3_FORCE_PATH_STYLE!=='false','tokenSecret':process.env.FILE_TOKEN_SECRET,'tokenTtl':Number(process.env.FILE_TOKEN_TTL??0xe10)},'auth':{'accessToken':process.env.AUTH_ACCESS_TOKEN||b(0x91),'user':process.env.AUTH_USER?JSON[b(0x92)](process.env.AUTH_USER):undefined,'sessionTimeout':+(process.env.AUTH_SESSION_TIMEOUT||0x258),'secret':process.env.AUTH_SECRET??b(0x93),'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','strict',b(0x94)]['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,...J,'logger':{...e[b(0x95)],...J['logger']},'pg':{...e['pg'],...J['pg']},'redis':{...e['redis'],...J['redis']},'s3':{...e['s3'],...J['s3']},'auth':{...e['auth'],...J[b(0x96)]}};}export{required as requireEnv};
package/dist/context.js CHANGED
@@ -1 +1 @@
1
- function z(C,N){C=C-0xbb;const r=U();let p=r[C];return p;}let defaultContext;export function setContext(C){defaultContext=C;}export function getContext(){if(!defaultContext)throw new Error('Application\x20context\x20is\x20not\x20initialized');return defaultContext;}function U(){const r=['redis'];U=function(){return r;};return U();}export function createContext(C){return{...C,async 'close'(){const N=z;await Promise['allSettled']([C[N(0xbb)]?.['close'](),C['pg']?.['end']()]),await C['logger']['close']();}};}
1
+ let defaultContext;function L(){const p=['close'];L=function(){return p;};return L();}export function setContext(J){defaultContext=J;}export function getContext(){if(!defaultContext)throw new Error('Application\x20context\x20is\x20not\x20initialized');return defaultContext;}function c(J,e){J=J-0x1ca;const p=L();let b=p[J];return b;}export function createContext(J){return{...J,async 'close'(){const e=c;await Promise['allSettled']([J['redis']?.[e(0x1ca)](),J['pg']?.['end']()]),await J['logger'][e(0x1ca)]();}};}
package/dist/errors.js CHANGED
@@ -1 +1 @@
1
- var c=z;export class FCoreError extends Error{[c(0x10b)];['statusCode'];[c(0x10c)];constructor(C,N,r=0x1f4,p){super(N),this['code']=C,this['statusCode']=r,this['details']=p,this['name']=new.target.name;}}export class BadRequestError extends FCoreError{constructor(C,N){var x=c;super(x(0x10d),C,0x190,N);}}export class UnauthorizedError extends FCoreError{constructor(C='Authentication\x20required'){var m=c;super(m(0x10e),C,0x191);}}export class ForbiddenError extends FCoreError{constructor(C='Access\x20denied'){super('FORBIDDEN',C,0x193);}}function z(C,N){C=C-0x10b;var r=U();var p=r[C];return p;}export class NotFoundError extends FCoreError{constructor(C='Not\x20found'){var Q=c;super(Q(0x10f),C,0x194);}}export class ConflictError extends FCoreError{constructor(C='Conflict'){super('CONFLICT',C,0x199);}}export class ValidationError extends FCoreError{constructor(C,N){var u=c;super(u(0x110),C,0x1a6,N);}}export class UnsupportedError extends FCoreError{constructor(C=c(0x111)){super('UNSUPPORTED',C,0x1f5);}}function U(){var L=['code','details','BAD_REQUEST_ERROR','UNAUTHORIZED','NOT_FOUND','VALIDATION_ERROR','Operation\x20is\x20not\x20configured'];U=function(){return L;};return U();}
1
+ var h=c;function L(){var u=['name','FORBIDDEN','Conflict'];L=function(){return u;};return L();}export class FCoreError extends Error{['code'];['statusCode'];['details'];constructor(J,e,p=0x1f4,b){var F=c;super(e),this['code']=J,this['statusCode']=p,this['details']=b,this[F(0x116)]=new.target.name;}}export class BadRequestError extends FCoreError{constructor(J,e){super('BAD_REQUEST_ERROR',J,0x190,e);}}export class UnauthorizedError extends FCoreError{constructor(J='Authentication\x20required'){super('UNAUTHORIZED',J,0x191);}}function c(J,e){J=J-0x116;var p=L();var b=p[J];return b;}export class ForbiddenError extends FCoreError{constructor(J='Access\x20denied'){var P=c;super(P(0x117),J,0x193);}}export class NotFoundError extends FCoreError{constructor(J='Not\x20found'){super('NOT_FOUND',J,0x194);}}export class ConflictError extends FCoreError{constructor(J=h(0x118)){super('CONFLICT',J,0x199);}}export class ValidationError extends FCoreError{constructor(J,e){super('VALIDATION_ERROR',J,0x1a6,e);}}export class UnsupportedError extends FCoreError{constructor(J='Operation\x20is\x20not\x20configured'){super('UNSUPPORTED',J,0x1f5);}}
package/dist/fastify.js CHANGED
@@ -1 +1 @@
1
- import{FCoreError}from'./errors.js';function U(){const d=['split','decorate','ctx','onRoute','startsWith','method','package','tags','public','permissions','url','authorization','Route\x20access\x20not\x20defined','access','includes','Missing\x20permission:\x20','@fastify/multipart','message','logger','debug','test','auth','buffer','disabled','register','max','timeWindow','log'];U=function(){return d;};return U();}import{authRoutes}from'./modules/auth/route.js';import{fileRoutes}from'./modules/file/route.js';function z(C,N){C=C-0x6e;const r=U();let p=r[C];return p;}import{resourceRoutes}from'./modules/resource/route.js';import{systemRoutes}from'./modules/system/route.js';import{createSessionStore}from'./plugins/auth/index.js';import{ForbiddenError}from'./errors.js';import{jwtVerifyToken}from'./plugins/jwt.js';function urlencodedContentParser(C,N,r){const p=decodeURIComponent(N['toString']())['split']('&')['reduce']((c,x)=>{const f=z,[m,Q]=x[f(0x6e)]('=');return{...c,[m]:Q};},{});r(null,p);}export default function fcoreFastify(C,N){return async r=>{const F=z;r[F(0x6f)](F(0x70),C);const {config:p}=C,c=new Map();r['addHook'](F(0x71),m=>{const t=F;if(m['url'][t(0x72)]('/api/')){const Q=m['schema'],u=Array['isArray'](m[t(0x73)])?m['method']:[m['method']];for(const L of u){if(L==='HEAD')continue;const T={'method':L,'endpoint':m['url'],'package':Q?.[t(0x74)]??'fcore','tags':Q?.[t(0x75)]??[],'summary':Q?.['summary']??'','description':Q?.['description']??'','access':Q?.['access']??t(0x76),'permissions':Q?.[t(0x77)]??[]};c['set'](L+'\x20'+m[t(0x78)],T);}}}),r['addHook']('preHandler',async m=>{const h=F,Q=c['get'](m['method']+'\x20'+m['routeOptions']['url']),u=m['raw']['headers']?.[h(0x79)],L=u?.['startsWith']('Bearer\x20')?u['slice'](0x7):null,T=m['user']??(L?await jwtVerifyToken(L):null);!m['user']&&L&&process.env.AUTH_JWT_SECRET&&(m['user']=await jwtVerifyToken(L));if(!Q?.['access'])throw new Error(h(0x7a));if(Q['access']==='public')return!![];if(!T)throw new ForbiddenError('User\x20required');if(Q['access']==='user'&&!Q['permissions']?.['length'])return!![];if(T['type']=='admin')return!![];if(Q[h(0x7b)]==='admin')throw new ForbiddenError('Admin\x20access\x20required');for(const Y of Q['permissions']){if(!T['permissions']?.[h(0x7c)](Y))throw new ForbiddenError(h(0x7d)+Y);}return!![];}),await createSessionStore(r,C),await r['register'](import(F(0x7e)),{'limits':{'fileSize':p['maxFileSize']*0x400*0x400}}),r['setErrorHandler']((m,Q,u)=>{const D=F;if(m instanceof FCoreError||m['code']==='FST_ERR_VALIDATION')return u['code'](m['statusCode'])['send']({'error':m['code'],'message':m[D(0x7f)],'details':m['details']});return C[D(0x80)]['error'](m),(p[D(0x81)]||process.env.NODE_ENV===D(0x82)||process.env.VITEST)&&console['error'](m),u['code'](0x1f4)['send']({'error':'INTERNAL_ERROR','message':'Internal\x20server\x20error'});});const x=m=>!N||N[F(0x7c)](m);if(x(F(0x83)))await r['register'](authRoutes(C));if(x('resource'))await r['register'](resourceRoutes(C));if(x('file'))await r['register'](fileRoutes(C));if(x('system'))await r['register'](systemRoutes(C,c));r['addContentTypeParser']('application/x-www-form-urlencoded',{'parseAs':F(0x84)},urlencodedContentParser),!p['rateLimit']?.[F(0x85)]?r[F(0x86)](import('@fastify/rate-limit'),{'max':p['rateLimit']?.[F(0x87)]||0x64,'timeWindow':p['rateLimit']?.[F(0x88)]||0xea60,'hook':'preHandler','global':!![],'keyGenerator':m=>(m['user']?.['id']||m['ip'])+'-'+m['raw'][F(0x78)]['split']('?')[0x0]}):console[F(0x89)]('⚠️\x20rate\x20limit\x20is\x20disabled');};};
1
+ function L(){const a=['toString','isArray','method','package','public','addHook','preHandler','authorization','startsWith','Bearer\x20','access','Route\x20access\x20not\x20defined','User\x20required','user','permissions','includes','Missing\x20permission:\x20','register','code','logger','error','send','resource','buffer','disabled','@fastify/rate-limit','max'];L=function(){return a;};return L();}import{FCoreError}from'./errors.js';import{authRoutes}from'./modules/auth/route.js';import{fileRoutes}from'./modules/file/route.js';function c(J,e){J=J-0x152;const p=L();let b=p[J];return b;}import{resourceRoutes}from'./modules/resource/route.js';import{systemRoutes}from'./modules/system/route.js';import{createSessionStore}from'./plugins/auth/index.js';import{ForbiddenError}from'./errors.js';import{jwtVerifyToken}from'./plugins/jwt.js';function urlencodedContentParser(J,e,p){const X=c,b=decodeURIComponent(e[X(0x152)]())['split']('&')['reduce']((F,P)=>{const [h,u]=P['split']('=');return{...F,[h]:u};},{});p(null,b);}export default function fcoreFastify(J,e){return async p=>{const Q=c;p['decorate']('ctx',J);const {config:b}=J,F=new Map();p['addHook']('onRoute',h=>{const E=c;if(h['url']['startsWith']('/api/')){const u=h['schema'],H=Array[E(0x153)](h[E(0x154)])?h[E(0x154)]:[h[E(0x154)]];for(const D of H){if(D==='HEAD')continue;const U={'method':D,'endpoint':h['url'],'package':u?.[E(0x155)]??'fcore','tags':u?.['tags']??[],'summary':u?.['summary']??'','description':u?.['description']??'','access':u?.['access']??E(0x156),'permissions':u?.['permissions']??[]};F['set'](D+'\x20'+h['url'],U);}}}),p[Q(0x157)](Q(0x158),async h=>{const T=Q,u=F['get'](h['method']+'\x20'+h['routeOptions']['url']),H=h['raw']['headers']?.[T(0x159)],D=H?.[T(0x15a)](T(0x15b))?H['slice'](0x7):null,U=h['user']??(D?await jwtVerifyToken(D):null);!h['user']&&D&&process.env.AUTH_JWT_SECRET&&(h['user']=await jwtVerifyToken(D));if(!u?.[T(0x15c)])throw new Error(T(0x15d));if(u[T(0x15c)]===T(0x156))return!![];if(!U)throw new ForbiddenError(T(0x15e));if(u[T(0x15c)]===T(0x15f)&&!u[T(0x160)]?.['length'])return!![];if(U['type']=='admin')return!![];if(u['access']==='admin')throw new ForbiddenError('Admin\x20access\x20required');for(const w of u[T(0x160)]){if(!U['permissions']?.[T(0x161)](w))throw new ForbiddenError(T(0x162)+w);}return!![];}),await createSessionStore(p,J),await p[Q(0x163)](import('@fastify/multipart'),{'limits':{'fileSize':b['maxFileSize']*0x400*0x400}}),p['setErrorHandler']((h,u,H)=>{const l=Q;if(h instanceof FCoreError||h['code']==='FST_ERR_VALIDATION')return H[l(0x164)](h['statusCode'])['send']({'error':h['code'],'message':h['message'],'details':h['details']});return J[l(0x165)]['error'](h),(b['debug']||process.env.NODE_ENV==='test'||process.env.VITEST)&&console[l(0x166)](h),H[l(0x164)](0x1f4)[l(0x167)]({'error':'INTERNAL_ERROR','message':'Internal\x20server\x20error'});});const P=h=>!e||e['includes'](h);if(P('auth'))await p['register'](authRoutes(J));if(P(Q(0x168)))await p[Q(0x163)](resourceRoutes(J));if(P('file'))await p['register'](fileRoutes(J));if(P('system'))await p['register'](systemRoutes(J,F));p['addContentTypeParser']('application/x-www-form-urlencoded',{'parseAs':Q(0x169)},urlencodedContentParser),!b['rateLimit']?.[Q(0x16a)]?p[Q(0x163)](import(Q(0x16b)),{'max':b['rateLimit']?.[Q(0x16c)]||0x64,'timeWindow':b['rateLimit']?.['timeWindow']||0xea60,'hook':Q(0x158),'global':!![],'keyGenerator':h=>(h['user']?.['id']||h['ip'])+'-'+h['raw']['url']['split']('?')[0x0]}):console['log']('⚠️\x20rate\x20limit\x20is\x20disabled');};};
package/dist/fcore.js CHANGED
@@ -1 +1 @@
1
- function z(C,N){C=C-0xc6;const r=U();let p=r[C];return p;}import{loadConfig}from'./config.js';import{createContext,setContext}from'./context.js';import{createAudit,createDatabase,createDictionary,createFileS3,createLogger,createRedis,createResource}from'./plugins/index.js';function U(){const Y=['redis','endpoint','forcePathStyle','resources'];U=function(){return Y;};return U();}export async function createFCore(C={}){const T=z,N=loadConfig(C['config']),r=createRedis(N[T(0xc6)]),p=createLogger(),c=createDatabase(N['pg']),x=createFileS3({'endpoint':N['s3'][T(0xc7)],'region':N['s3']['region'],'bucket':N['s3']['bucket'],'accessKey':N['s3']['accessKey'],'secretKey':N['s3']['secretKey'],'folder':N['s3']['folder'],'forcePathStyle':N['s3'][T(0xc8)],'tokenSecret':N['s3']['tokenSecret'],'tokenTtl':N['s3']['tokenTtl']}),m=createAudit({'pg':c,'logger':p}),Q=createDictionary({'pg':c,'dictionaries':C['dictionaries']}),u=createResource({'pg':c,'logger':p,'audit':m,'dictionary':Q,'file':x});C[T(0xc9)]?.['length']&&u['register'](C['resources']);const L=createContext({'config':N,'logger':p,'redis':r,'pg':c,'file':x,'resource':u,'audit':m,'dictionary':Q});return setContext(L),L;}
1
+ import{loadConfig}from'./config.js';import{createContext,setContext}from'./context.js';function L(){const w=['config','redis','endpoint','bucket','accessKey','secretKey'];L=function(){return w;};return L();}function c(J,e){J=J-0xc7;const p=L();let b=p[J];return b;}import{createAudit,createDatabase,createDictionary,createFileS3,createLogger,createRedis,createResource}from'./plugins/index.js';export async function createFCore(J={}){const U=c,e=loadConfig(J[U(0xc7)]),p=createRedis(e[U(0xc8)]),b=createLogger(),F=createDatabase(e['pg']),P=createFileS3({'endpoint':e['s3'][U(0xc9)],'region':e['s3']['region'],'bucket':e['s3'][U(0xca)],'accessKey':e['s3'][U(0xcb)],'secretKey':e['s3'][U(0xcc)],'folder':e['s3']['folder'],'forcePathStyle':e['s3']['forcePathStyle'],'tokenSecret':e['s3']['tokenSecret'],'tokenTtl':e['s3']['tokenTtl']}),h=createAudit({'pg':F,'logger':b}),u=createDictionary({'pg':F,'dictionaries':J['dictionaries']}),H=createResource({'pg':F,'logger':b,'audit':h,'dictionary':u,'file':P});J['resources']?.['length']&&H['register'](J['resources']);const D=createContext({'config':e,'logger':b,'redis':p,'pg':F,'file':P,'resource':H,'audit':h,'dictionary':u});return setContext(D),D;}
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- function U(){const p=['status','error','exitCode'];U=function(){return p;};return U();}const N=z;import{runMigrations}from'./runner.js';function z(C,N){C=C-0x7b;const r=U();let p=r[C];return p;}import{loadConfig}from'../config.js';try{const config=loadConfig();console['log']('Loaded\x20configuration:',config['pg']);for(const r of await runMigrations({'database':config['pg']}))console['log']((r[N(0x7b)]==='run'?'OK\x20\x20':'SKIP')+'\x20'+r['file']);}catch(C){console[N(0x7c)](C),process[N(0x7d)]=0x1;}
2
+ function L(){const p=['log','exitCode'];L=function(){return p;};return L();}const e=c;import{runMigrations}from'./runner.js';function c(J,e){J=J-0xb2;const p=L();let b=p[J];return b;}import{loadConfig}from'../config.js';try{const config=loadConfig();console['log']('Loaded\x20configuration:',config['pg']);for(const r of await runMigrations({'database':config['pg']}))console[e(0xb2)]((r['status']==='run'?'OK\x20\x20':'SKIP')+'\x20'+r['file']);}catch(J){console['error'](J),process[e(0xb3)]=0x1;}
@@ -1 +1 @@
1
- import C from'node:fs/promises';import N from'node:path';function z(C,N){C=C-0xff;const r=U();let p=r[C];return p;}function U(){const h=['dir','migrations','databaseUrl','rows','map','version','release','push','end'];U=function(){return h;};return U();}import{createDatabase}from'../plugins/pg.js';export async function runMigrations(r={}){const t=z,p=N['resolve'](r[t(0xff)]??t(0x100)),c=r['database']??databaseFromUrl(r[t(0x101)]??process.env.DATABASE_URL);if(!c)throw new Error('DATABASE_URL\x20or\x20database\x20config\x20is\x20required');const x=createDatabase(c);if(!x)throw new Error('empty\x20pg');const m=[];try{await x['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 Q=await x['query']('SELECT\x20version\x20FROM\x20schema_migrations'),u=new Set(Q[t(0x102)][t(0x103)](T=>T[t(0x104)])),L=(await C['readdir'](p))['filter'](T=>T['endsWith']('.sql'))['sort']();for(const T of L){if(u['has'](T)){m['push']({'file':T,'status':'skip'});continue;}const Y=await C['readFile'](N['join'](p,T),'utf8'),f=await x['connect']();try{await f['query']('BEGIN'),await f['query'](Y),await f['query']('INSERT\x20INTO\x20schema_migrations(version)\x20VALUES\x20($1)',[T]),await f['query']('COMMIT');}catch(F){await f['query']('ROLLBACK');throw F;}finally{f[t(0x105)]();}m[t(0x106)]({'file':T,'status':'run'});}return m;}finally{await x[t(0x107)]();}}function databaseFromUrl(r){if(!r)return undefined;const p=new URL(r);return{'host':p['hostname'],'port':Number(p['port']||0x1538),'database':p['pathname']['slice'](0x1),'user':decodeURIComponent(p['username']),'password':decodeURIComponent(p['password'])};}
1
+ import J from'node:fs/promises';import e from'node:path';import{createDatabase}from'../plugins/pg.js';export async function runMigrations(p={}){const Q=c,b=e[Q(0x86)](p['dir']??'migrations'),F=p['database']??databaseFromUrl(p['databaseUrl']??process.env.DATABASE_URL);if(!F)throw new Error(Q(0x87));const P=createDatabase(F);if(!P)throw new Error('empty\x20pg');const h=[];try{await P['query'](Q(0x88));const u=await P['query']('SELECT\x20version\x20FROM\x20schema_migrations'),H=new Set(u['rows']['map'](U=>U[Q(0x89)])),D=(await J['readdir'](b))[Q(0x8a)](U=>U['endsWith']('.sql'))['sort']();for(const U of D){if(H['has'](U)){h['push']({'file':U,'status':'skip'});continue;}const w=await J['readFile'](e['join'](b,U),'utf8'),X=await P['connect']();try{await X[Q(0x8b)]('BEGIN'),await X[Q(0x8b)](w),await X['query']('INSERT\x20INTO\x20schema_migrations(version)\x20VALUES\x20($1)',[U]),await X['query'](Q(0x8c));}catch(E){await X['query']('ROLLBACK');throw E;}finally{X[Q(0x8d)]();}h['push']({'file':U,'status':'run'});}return h;}finally{await P['end']();}}function c(J,e){J=J-0x86;const p=L();let b=p[J];return b;}function databaseFromUrl(p){if(!p)return undefined;const b=new URL(p);return{'host':b['hostname'],'port':Number(b['port']||0x1538),'database':b['pathname']['slice'](0x1),'user':decodeURIComponent(b['username']),'password':decodeURIComponent(b['password'])};}function L(){const T=['resolve','DATABASE_URL\x20or\x20database\x20config\x20is\x20required','\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','version','filter','query','COMMIT','release'];L=function(){return T;};return L();}
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- const r=z;function U(){const p=['argv','Usage:\x20fcore-registration\x20<login>\x20<password>\x20[type]','exitCode','log','Registered\x20user\x20'];U=function(){return p;};return U();}import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';function z(C,N){C=C-0x102;const r=U();let p=r[C];return p;}import C from'./services/registration.js';const [user,password,type]=process[r(0x102)]['slice'](0x2);if(!user||!password)console['error'](r(0x103)),process[r(0x104)]=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const {user:data}=await C({'user':user,'password':password,'type':type},{'pg':pg});console[r(0x105)](r(0x106)+data['id']+'\x20('+data['type']+')');}catch(N){console['error'](N),process[r(0x104)]=0x1;}finally{await pg['end']();}}
2
+ const p=c;function c(J,e){J=J-0x1ea;const p=L();let b=p[J];return b;}import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';import J from'./services/registration.js';const [user,password,type]=process['argv']['slice'](0x2);function L(){const b=['Usage:\x20fcore-registration\x20<login>\x20<password>\x20[type]','exitCode','error','end'];L=function(){return b;};return L();}if(!user||!password)console['error'](p(0x1ea)),process[p(0x1eb)]=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const {user:data}=await J({'user':user,'password':password,'type':type},{'pg':pg});console['log']('Registered\x20user\x20'+data['id']+'\x20('+data['type']+')');}catch(e){console[p(0x1ec)](e),process['exitCode']=0x1;}finally{await pg[p(0x1ed)]();}}
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- const r=z;import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';function z(C,N){C=C-0x149;const r=U();let p=r[C];return p;}function U(){const p=['error','Usage:\x20fcore-password\x20<login>\x20<password>','query','User\x20not\x20found','log','Password\x20changed\x20for\x20'];U=function(){return p;};return U();}import C from'./services/change-password.js';const [login,password]=process['argv']['slice'](0x2);if(!login||!password)console[r(0x149)](r(0x14a)),process['exitCode']=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const result=await pg[r(0x14b)]('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(r(0x14c));await C({'userId':user['id'],'password':password},{'pg':pg}),console[r(0x14d)](r(0x14e)+login);}catch(N){console['error'](N),process['exitCode']=0x1;}finally{await pg['end']();}}
2
+ const p=c;import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';import J from'./services/change-password.js';function L(){const b=['argv','slice','rows'];L=function(){return b;};return L();}const [login,password]=process[p(0xb3)][p(0xb4)](0x2);function c(J,e){J=J-0xb3;const p=L();let b=p[J];return b;}if(!login||!password)console['error']('Usage:\x20fcore-password\x20<login>\x20<password>'),process['exitCode']=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const result=await pg['query']('SELECT\x20uid\x20AS\x20id\x20FROM\x20admin.users\x20WHERE\x20$1\x20IN\x20(login,\x20email,\x20phone)\x20LIMIT\x201',[login]),user=result[p(0xb5)][0x0];if(!user)throw new Error('User\x20not\x20found');await J({'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
- const u=z;function U(){const T=['audit','access','settings','create','slice','add','error','Usage:\x20fcore-permission\x20<login>\x20<system|resource|resource:action[,...]|clear>','query','User\x20not\x20found','trim','split','get','BEGIN','actions','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','end'];U=function(){return T;};return U();}import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';const SYSTEM_ACTIONS=['logs',u(0x13a),'list','check',u(0x13b),u(0x13c),'dictionaries'],RESOURCE_ACTIONS=['read','update',u(0x13d),'delete'],[login,permissionArg]=process['argv'][u(0x13e)](0x2);function z(C,N){C=C-0x13a;const r=U();let p=r[C];return p;}function expandPermissions(C){const L=u,N=C['split'](',')['map'](p=>p['trim']())['filter'](Boolean),r=new Set();for(const p of N){if(p['includes'](':')){r[L(0x13f)](p);continue;}const c=p==='system'?SYSTEM_ACTIONS:RESOURCE_ACTIONS;for(const x of c){r[L(0x13f)](p+':'+x);}}return[...r];}if(!login||!permissionArg)console[u(0x140)](u(0x141)),process['exitCode']=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const result=await pg[u(0x142)]('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(u(0x143));if(permissionArg[u(0x144)]()==='clear')await pg[u(0x142)]('DELETE\x20FROM\x20admin.role_access\x20WHERE\x20user_uid\x20=\x20$1\x20AND\x20role_id\x20IS\x20NULL',[user['id']]),console['log']('Permissions\x20cleared\x20for\x20'+login);else{const permissions=expandPermissions(permissionArg),byResource=new Map();for(const permission of permissions){const [resource,action]=permission[u(0x145)](':'),actions=byResource[u(0x146)](resource)??[];actions['push'](action),byResource['set'](resource,actions);}const client=await pg['connect']();try{await client[u(0x142)](u(0x147));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[u(0x148)]??[],...actions])];await client['query'](u(0x149),[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[u(0x142)]('COMMIT');}catch(m){await client['query']('ROLLBACK');throw m;}finally{client['release']();}console['log']('Granted\x20permissions\x20for\x20'+login+':\x20'+permissions['join'](',\x20'));}}catch(Q){console['error'](Q),process['exitCode']=0x1;}finally{await pg[u(0x14a)]();}}
2
+ const H=c;function L(){const U=['logs','list','check','argv','split','trim','filter','add','exitCode','clear','DELETE\x20FROM\x20admin.role_access\x20WHERE\x20user_uid\x20=\x20$1\x20AND\x20role_id\x20IS\x20NULL','query','rows','actions','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)','ROLLBACK','release','log','Granted\x20permissions\x20for\x20'];L=function(){return U;};return L();}import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';const SYSTEM_ACTIONS=[H(0x1ce),'audit',H(0x1cf),H(0x1d0),'access','settings','dictionaries'],RESOURCE_ACTIONS=['read','update','create','delete'],[login,permissionArg]=process[H(0x1d1)]['slice'](0x2);function c(J,e){J=J-0x1ce;const p=L();let b=p[J];return b;}function expandPermissions(J){const D=H,e=J[D(0x1d2)](',')['map'](b=>b[D(0x1d3)]())[D(0x1d4)](Boolean),p=new Set();for(const b of e){if(b['includes'](':')){p[D(0x1d5)](b);continue;}const F=b==='system'?SYSTEM_ACTIONS:RESOURCE_ACTIONS;for(const P of F){p['add'](b+':'+P);}}return[...p];}if(!login||!permissionArg)console['error']('Usage:\x20fcore-permission\x20<login>\x20<system|resource|resource:action[,...]|clear>'),process[H(0x1d6)]=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']()===H(0x1d7))await pg['query'](H(0x1d8),[user['id']]),console['log']('Permissions\x20cleared\x20for\x20'+login);else{const permissions=expandPermissions(permissionArg),byResource=new Map();for(const permission of permissions){const [resource,action]=permission['split'](':'),actions=byResource['get'](resource)??[];actions['push'](action),byResource['set'](resource,actions);}const client=await pg['connect']();try{await client['query']('BEGIN');for(const [resource,actions]of byResource){const existing=await client[H(0x1d9)]('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[H(0x1da)][0x0];if(row){const merged=[...new Set([...row[H(0x1db)]??[],...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['query'](H(0x1dc),[resource,actions,user['id'],user['id']]);}await client['query']('COMMIT');}catch(h){await client['query'](H(0x1dd));throw h;}finally{client[H(0x1de)]();}console[H(0x1df)](H(0x1e0)+login+':\x20'+permissions['join'](',\x20'));}}catch(u){console['error'](u),process['exitCode']=0x1;}finally{await pg['end']();}}
@@ -1 +1 @@
1
- import{getUserPermissions,verifyUser}from'../../plugins/auth/index.js';import C from'./services/get-current-user.js';function z(C,N){C=C-0x1d4;const r=U();let p=r[C];return p;}import N from'./services/registration.js';import r from'./services/change-password.js';import{authSchemas}from'./schema.js';import p from'../../shared/getIP.js';import{UnauthorizedError}from'../../errors.js';function U(){const d=['GET','permissions','config','auth','redirect','cookie','maxAge','Sign\x20in','public','/api/auth/login','credentials','fcore','admin','post','/api/auth/password','Changes\x20the\x20password\x20for\x20the\x20current\x20user.','user','Terminates\x20the\x20current\x20user\x20session.','write','session','cookieName','/api/auth/user','query'];U=function(){return d;};return U();}export function authRoutes(c){return async x=>{const t=z,m=async Q=>{const F=z,u=Q['method']===F(0x1d4)?Q['query']:Q['body'],L=p(Q),T=await verifyUser({...u,'ip':L},c);T[F(0x1d5)]=await getUserPermissions(T['id'],c);const Y=T['twofa']?c[F(0x1d6)][F(0x1d7)]['twoFactorRedirect']:c['config']['auth'][F(0x1d8)];await Q['login'](T);const f=c['config']['auth']['sessionTimeout']*0x3e8*0x3c;return Q['session']?.[F(0x1d9)]&&(Q['session']['cookie'][F(0x1da)]=f),await Q['session']['save'](),await c['audit']?.['write']?.({'module':'auth','resource':'session','resourceId':Q['session']['sessionId'],'action':'login','userId':T['id'],'ipAddress':L}),{'user':{'id':T['id'],'type':T['type'],'permissions':T['permissions']},'redirectUrl':Y};};x['get']('/api/auth/login',{'schema':{'tags':['fcore','auth'],'summary':t(0x1db),'description':'Authenticates\x20a\x20user\x20and\x20returns\x20a\x20bearer\x20access\x20token.','access':t(0x1dc),'permissions':[],'querystring':authSchemas['credentials']}},m),x['post'](t(0x1dd),{'schema':{'tags':['fcore','auth'],'summary':'Sign\x20in','description':'Authenticates\x20a\x20user\x20and\x20returns\x20a\x20bearer\x20access\x20token.','access':'public','permissions':[],'body':authSchemas[t(0x1de)]}},m),x['post']('/api/auth/registration',{'schema':{'tags':[t(0x1df),'auth'],'summary':'Register','description':'Creates\x20a\x20regular\x20user\x20account.','access':t(0x1e0),'permissions':['user:create'],'body':authSchemas['credentials']}},async Q=>N(Q['body'],c)),x[t(0x1e1)](t(0x1e2),{'schema':{'tags':['fcore','auth'],'summary':'Change\x20password','description':t(0x1e3),'access':'user','permissions':[],'body':authSchemas['password']}},async Q=>{const h=t;if(!Q['user'])throw new UnauthorizedError('Not\x20authorized');return await r({'userId':Q[h(0x1e4)]['id'],...Q['body']},c),{'success':!![]};}),x['post']('/api/auth/logout',{'schema':{'tags':['fcore',t(0x1d7)],'summary':'Sign\x20out','description':t(0x1e5),'access':'user','permissions':[]}},async(Q,u)=>{const D=t,L={'redirectUrl':'/'};if(!Q['user'])return L;return await c['audit']?.[D(0x1e6)]?.({'module':'auth','resource':'session','resourceId':Q['session']['sessionId'],'action':'logout','userId':Q['user']?.['id']}),await Q[D(0x1e7)]['destroy'](),u['clearCookie'](c['config']['auth'][D(0x1e8)]),Object['defineProperty'](Q,'session',{'value':null,'writable':![],'configurable':![]}),L;}),x['get'](t(0x1e9),{'schema':{'tags':['fcore',t(0x1d7)],'summary':'Get\x20current\x20user','description':'Returns\x20the\x20authenticated\x20user\x27s\x20safe\x20profile.','access':'user','permissions':[],'querystring':authSchemas['query']}},async Q=>C({'user':Q[t(0x1e4)],'token':Q[t(0x1ea)]['token']}));};}
1
+ function L(){const a=['GET','body','auth','redirect','session','cookie','sessionId','login','type','get','Sign\x20in','post','fcore','Register','/api/auth/password','Change\x20password','user','/api/auth/logout','Sign\x20out','defineProperty','token'];L=function(){return a;};return L();}import{getUserPermissions,verifyUser}from'../../plugins/auth/index.js';import J from'./services/get-current-user.js';import e from'./services/registration.js';import p from'./services/change-password.js';import{authSchemas}from'./schema.js';import b from'../../shared/getIP.js';import{UnauthorizedError}from'../../errors.js';function c(J,e){J=J-0x15a;const p=L();let b=p[J];return b;}export function authRoutes(F){return async P=>{const Q=c,h=async u=>{const E=c,H=u['method']===E(0x15a)?u['query']:u[E(0x15b)],D=b(u),U=await verifyUser({...H,'ip':D},F);U['permissions']=await getUserPermissions(U['id'],F);const w=U['twofa']?F['config'][E(0x15c)]['twoFactorRedirect']:F['config']['auth'][E(0x15d)];await u['login'](U);const X=F['config'][E(0x15c)]['sessionTimeout']*0x3e8*0x3c;return u[E(0x15e)]?.['cookie']&&(u[E(0x15e)][E(0x15f)]['maxAge']=X),await u['session']['save'](),await F['audit']?.['write']?.({'module':E(0x15c),'resource':E(0x15e),'resourceId':u['session'][E(0x160)],'action':E(0x161),'userId':U['id'],'ipAddress':D}),{'user':{'id':U['id'],'type':U[E(0x162)],'permissions':U['permissions']},'redirectUrl':w};};P[Q(0x163)]('/api/auth/login',{'schema':{'tags':['fcore','auth'],'summary':Q(0x164),'description':'Authenticates\x20a\x20user\x20and\x20returns\x20a\x20bearer\x20access\x20token.','access':'public','permissions':[],'querystring':authSchemas['credentials']}},h),P[Q(0x165)]('/api/auth/login',{'schema':{'tags':['fcore','auth'],'summary':'Sign\x20in','description':'Authenticates\x20a\x20user\x20and\x20returns\x20a\x20bearer\x20access\x20token.','access':'public','permissions':[],'body':authSchemas['credentials']}},h),P['post']('/api/auth/registration',{'schema':{'tags':[Q(0x166),'auth'],'summary':Q(0x167),'description':'Creates\x20a\x20regular\x20user\x20account.','access':'admin','permissions':['user:create'],'body':authSchemas['credentials']}},async u=>e(u[Q(0x15b)],F)),P[Q(0x165)](Q(0x168),{'schema':{'tags':[Q(0x166),'auth'],'summary':Q(0x169),'description':'Changes\x20the\x20password\x20for\x20the\x20current\x20user.','access':'user','permissions':[],'body':authSchemas['password']}},async u=>{const T=Q;if(!u[T(0x16a)])throw new UnauthorizedError('Not\x20authorized');return await p({'userId':u['user']['id'],...u[T(0x15b)]},F),{'success':!![]};}),P['post'](Q(0x16b),{'schema':{'tags':['fcore','auth'],'summary':Q(0x16c),'description':'Terminates\x20the\x20current\x20user\x20session.','access':'user','permissions':[]}},async(u,H)=>{const l=Q,D={'redirectUrl':'/'};if(!u[l(0x16a)])return D;return await F['audit']?.['write']?.({'module':'auth','resource':'session','resourceId':u['session']['sessionId'],'action':'logout','userId':u['user']?.['id']}),await u[l(0x15e)]['destroy'](),H['clearCookie'](F['config']['auth']['cookieName']),Object[l(0x16d)](u,'session',{'value':null,'writable':![],'configurable':![]}),D;}),P['get']('/api/auth/user',{'schema':{'tags':['fcore','auth'],'summary':'Get\x20current\x20user','description':'Returns\x20the\x20authenticated\x20user\x27s\x20safe\x20profile.','access':'user','permissions':[],'querystring':authSchemas['query']}},async u=>J({'user':u[Q(0x16a)],'token':u['query'][Q(0x16e)]}));};}
@@ -1 +1 @@
1
- function z(C,N){C=C-0xb8;const r=U();let p=r[C];return p;}const C=z;import{Type}from'@sinclair/typebox';function U(){const N=['Optional','String','Object'];U=function(){return N;};return U();}export const authSchemas={'query':Type['Object']({'token':Type['Optional'](Type['Boolean']())}),'credentials':Type['Object']({'user':Type['String']({'minLength':0x1,'maxLength':0x64}),'password':Type['String']({'minLength':0x1,'maxLength':0x64}),'type':Type[C(0xb8)](Type['String']({'minLength':0x1,'maxLength':0x64}))}),'password':Type['Object']({'password':Type[C(0xb9)]({'minLength':0x1,'maxLength':0x64}),'id':Type['Optional'](Type['String']({'minLength':0x1,'maxLength':0x64}))}),'twoFactor':Type[C(0xba)]({'code':Type['String']({'minLength':0x1})})};
1
+ const J=c;import{Type}from'@sinclair/typebox';function L(){const e=['String','Object'];L=function(){return e;};return L();}function c(J,e){J=J-0x6b;const p=L();let b=p[J];return b;}export const authSchemas={'query':Type['Object']({'token':Type['Optional'](Type['Boolean']())}),'credentials':Type['Object']({'user':Type[J(0x6b)]({'minLength':0x1,'maxLength':0x64}),'password':Type['String']({'minLength':0x1,'maxLength':0x64}),'type':Type['Optional'](Type['String']({'minLength':0x1,'maxLength':0x64}))}),'password':Type['Object']({'password':Type[J(0x6b)]({'minLength':0x1,'maxLength':0x64}),'id':Type['Optional'](Type['String']({'minLength':0x1,'maxLength':0x64}))}),'twoFactor':Type[J(0x6c)]({'code':Type['String']({'minLength':0x1})})};
@@ -1 +1 @@
1
- import{hashPassword}from'../../../plugins/auth/index.js';export default async function changePassword({id:C,password:N,userId:r},{pg:p}){const c=await hashPassword(N);await p['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',[c,C||r,r]);}
1
+ import{hashPassword}from'../../../plugins/auth/index.js';export default async function changePassword({id:J,password:e,userId:p},{pg:b}){const F=await hashPassword(e);await b['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',[F,J||p,p]);}
@@ -1 +1 @@
1
- import{safeUser}from'../../utils/safe-user.js';export default async function getCurrentUser(C){const {user:N}=C;if(!N)return{};if(C['token']){const {jwtSignToken:r}=await import('../../../plugins/jwt.js'),p=await r(N);N['token']=p;}return N['resources']=[...new Set(N?.['permissions']['map'](c=>c['split'](':')[0x0]))],safeUser(N);}
1
+ function c(J,e){J=J-0xf6;const p=L();let b=p[J];return b;}import{safeUser}from'../../utils/safe-user.js';export default async function getCurrentUser(J){const P=c,{user:e}=J;if(!e)return{};if(J[P(0xf6)]){const {jwtSignToken:p}=await import('../../../plugins/jwt.js'),b=await p(e);e['token']=b;}return e['resources']=[...new Set(e?.[P(0xf7)]['map'](F=>F['split'](':')[0x0]))],safeUser(e);}function L(){const h=['token','permissions'];L=function(){return h;};return L();}
@@ -1 +1 @@
1
- function z(C,N){C=C-0x1a6;const r=U();let p=r[C];return p;}import{ConflictError}from'../../../errors.js';function U(){const u=['query','Login\x20is\x20already\x20in\x20use'];U=function(){return u;};return U();}import{hashPassword}from'../../../plugins/auth/index.js';export default async function registration({user:C,password:N,type:r},{pg:p}){const Q=z,c=await hashPassword(N),x=await p[Q(0x1a6)]('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',[C,c,r||'regular']),m=x['rows'][0x0];if(!m)throw new ConflictError(Q(0x1a7));return{'user':m};}
1
+ import{ConflictError}from'../../../errors.js';import{hashPassword}from'../../../plugins/auth/index.js';function c(J,e){J=J-0x1d9;const p=L();let b=p[J];return b;}export default async function registration({user:J,password:e,type:p},{pg:b}){const u=c,F=await hashPassword(e),P=await b['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',[J,F,p||u(0x1d9)]),h=P[u(0x1da)][0x0];if(!h)throw new ConflictError('Login\x20is\x20already\x20in\x20use');return{'user':h};}function L(){const H=['regular','rows'];L=function(){return H;};return L();}
@@ -1 +1 @@
1
- import{unsupported}from'../../utils/unsupported.js';export default async function verifyTwoFactor(C,N){return unsupported('Two-factor\x20provider');}
1
+ import{unsupported}from'../../utils/unsupported.js';function L(){var b=['Two-factor\x20provider'];L=function(){return b;};return L();}function c(J,e){J=J-0xaa;var p=L();var b=p[J];return b;}export default async function verifyTwoFactor(J,e){var p=c;return unsupported(p(0xaa));}
@@ -1 +1 @@
1
- var C=z;export default new Set(['image/jpeg','image/png','image/gif','image/webp',C(0x1e6),'image/tiff','image/svg+xml',C(0x1e7),C(0x1e8),C(0x1e9),'application/msword','application/vnd.openxmlformats-officedocument.wordprocessingml.document','application/vnd.ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','application/vnd.ms-powerpoint',C(0x1ea),'application/vnd.oasis.opendocument.text',C(0x1eb),'application/vnd.oasis.opendocument.presentation','text/plain',C(0x1ec),'text/markdown','application/json',C(0x1ed),C(0x1ee),'application/geo+json','application/vnd.google-earth.kml+xml','application/vnd.google-earth.kmz','application/zip','application/x-zip-compressed','application/x-7z-compressed','application/x-rar-compressed','application/vnd.rar','application/gzip',C(0x1ef),'application/x-tar','audio/mpeg','audio/wav',C(0x1f0),'audio/webm','audio/mp4','video/mp4','video/mpeg','video/webm','video/quicktime','video/x-msvideo','application/octet-stream']);function z(C,N){C=C-0x1e6;var r=U();var p=r[C];return p;}function U(){var N=['image/bmp','image/x-icon','image/avif','application/pdf','application/vnd.openxmlformats-officedocument.presentationml.presentation','application/vnd.oasis.opendocument.spreadsheet','text/csv','application/xml','text/xml','application/x-gzip','audio/ogg'];U=function(){return N;};return U();}
1
+ function L(){var e=['image/jpeg','image/svg+xml','image/x-icon','application/msword','application/vnd.openxmlformats-officedocument.wordprocessingml.document','application/vnd.openxmlformats-officedocument.presentationml.presentation','application/vnd.oasis.opendocument.text','application/vnd.oasis.opendocument.spreadsheet','text/plain','text/csv','application/vnd.rar','audio/mpeg','application/octet-stream'];L=function(){return e;};return L();}var J=c;function c(J,e){J=J-0x71;var p=L();var b=p[J];return b;}export default new Set([J(0x71),'image/png','image/gif','image/webp','image/bmp','image/tiff',J(0x72),J(0x73),'image/avif','application/pdf',J(0x74),J(0x75),'application/vnd.ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','application/vnd.ms-powerpoint',J(0x76),J(0x77),J(0x78),'application/vnd.oasis.opendocument.presentation',J(0x79),J(0x7a),'text/markdown','application/json','application/xml','text/xml','application/geo+json','application/vnd.google-earth.kml+xml','application/vnd.google-earth.kmz','application/zip','application/x-zip-compressed','application/x-7z-compressed','application/x-rar-compressed',J(0x7b),'application/gzip','application/x-gzip','application/x-tar',J(0x7c),'audio/wav','audio/ogg','audio/webm','audio/mp4','video/mp4','video/mpeg','video/webm','video/quicktime','video/x-msvideo',J(0x7d)]);
@@ -1 +1 @@
1
- import{fileTypeFromBuffer}from'file-type';import{getFile}from'./services/get-file.js';import{uploadFile}from'./services/upload-file.js';function U(){const h=['fcore','Get\x20file\x20by\x20token','fileDownloadQuery','verify','query','startsWith','split','replace','attachment','Uploads\x20a\x20file\x20and\x20stores\x20its\x20metadata.','filename','resource','Resize\x20file','files:read','resizeQuery','mime','image/png','Cache-Control'];U=function(){return h;};return U();}function z(C,N){C=C-0xa7;const r=U();let p=r[C];return p;}import{resizeFile}from'./services/resize-file.js';import{fileSchemas}from'./schema.js';export function fileRoutes(C){return async N=>{const Y=z;N['get']('/api/file/:token',{'schema':{'tags':[Y(0xa7),'file'],'summary':Y(0xa8),'description':'Returns\x20a\x20file\x20after\x20verifying\x20its\x20signed\x20access\x20token.','access':'public','permissions':[],'params':fileSchemas['fileToken'],'querystring':fileSchemas[Y(0xa9)]}},async(r,p)=>{const f=Y,c=C['file'][f(0xaa)](r['params']['token']),x=await getFile({'pathOrToken':c},C),m=await fileTypeFromBuffer(x),Q=m?.['mime']??'application/octet-stream',u=r[f(0xab)]['download']===!![],L=Q[f(0xac)]('image/')||Q==='application/pdf',T=c[f(0xad)]('/')['pop']()?.[f(0xae)](/[^A-Za-z0-9._-]/g,'_')??'file';return p['type'](Q),p['header']('Content-Disposition',(u||!L?f(0xaf):'inline')+';\x20filename=\x22'+T+'\x22')['header']('Cache-Control','public,\x20max-age=86400,\x20immutable'),p['send'](x);}),N['post']('/api/file/upload',{'schema':{'tags':['fcore','file'],'summary':'Upload\x20file','description':Y(0xb0),'access':'user','permissions':['files:create']}},async r=>{const F=Y,p=await r['file']();if(!p)throw new Error('File\x20is\x20required');return uploadFile({'file':p,'metadata':{'name':p[F(0xb1)],'path':p['fields']['path']?.['value'],'resource':p['fields'][F(0xb2)]?.['value'],'resourceId':p['fields']['resourceId']?.['value']},'user':r['user']},C);}),N['get']('/api/file/:token/resize',{'schema':{'tags':['fcore','file'],'summary':Y(0xb3),'description':'Returns\x20a\x20resized\x20image\x20file.','access':'user','permissions':[Y(0xb4)],'params':fileSchemas['fileToken'],'querystring':fileSchemas[Y(0xb5)]}},async(r,p)=>{const t=Y,c=await resizeFile({'pathOrToken':C['file']?.['verify'](r['params']['token']),...r['query']},C),x=await fileTypeFromBuffer(c);return p['type'](x?.[t(0xb6)]??t(0xb7)),p['header']('Content-Disposition','inline')['header'](t(0xb8),'public,\x20max-age=86400,\x20immutable'),p['send'](c);});};}
1
+ import{fileTypeFromBuffer}from'file-type';import{getFile}from'./services/get-file.js';function L(){const T=['/api/file/:token','fileToken','file','verify','query','startsWith','split','header',';\x20filename=\x22','send','post','Uploads\x20a\x20file\x20and\x20stores\x20its\x20metadata.','fields','/api/file/:token/resize','fcore','Returns\x20a\x20resized\x20image\x20file.','mime'];L=function(){return T;};return L();}import{uploadFile}from'./services/upload-file.js';import{resizeFile}from'./services/resize-file.js';import{fileSchemas}from'./schema.js';function c(J,e){J=J-0xb4;const p=L();let b=p[J];return b;}export function fileRoutes(J){return async e=>{const w=c;e['get'](w(0xb4),{'schema':{'tags':['fcore','file'],'summary':'Get\x20file\x20by\x20token','description':'Returns\x20a\x20file\x20after\x20verifying\x20its\x20signed\x20access\x20token.','access':'public','permissions':[],'params':fileSchemas[w(0xb5)],'querystring':fileSchemas['fileDownloadQuery']}},async(p,b)=>{const X=w,F=J[X(0xb6)][X(0xb7)](p['params']['token']),P=await getFile({'pathOrToken':F},J),h=await fileTypeFromBuffer(P),u=h?.['mime']??'application/octet-stream',H=p[X(0xb8)]['download']===!![],D=u[X(0xb9)]('image/')||u==='application/pdf',U=F[X(0xba)]('/')['pop']()?.['replace'](/[^A-Za-z0-9._-]/g,'_')??X(0xb6);return b['type'](u),b[X(0xbb)]('Content-Disposition',(H||!D?'attachment':'inline')+X(0xbc)+U+'\x22')['header']('Cache-Control','public,\x20max-age=86400,\x20immutable'),b[X(0xbd)](P);}),e[w(0xbe)]('/api/file/upload',{'schema':{'tags':['fcore','file'],'summary':'Upload\x20file','description':w(0xbf),'access':'user','permissions':['files:create']}},async p=>{const E=w,b=await p[E(0xb6)]();if(!b)throw new Error('File\x20is\x20required');return uploadFile({'file':b,'metadata':{'name':b['filename'],'path':b[E(0xc0)]['path']?.['value'],'resource':b['fields']['resource']?.['value'],'resourceId':b['fields']['resourceId']?.['value']},'user':p['user']},J);}),e['get'](w(0xc1),{'schema':{'tags':[w(0xc2),w(0xb6)],'summary':'Resize\x20file','description':w(0xc3),'access':'user','permissions':['files:read'],'params':fileSchemas['fileToken'],'querystring':fileSchemas['resizeQuery']}},async(p,b)=>{const Q=w,F=await resizeFile({'pathOrToken':J['file']?.[Q(0xb7)](p['params']['token']),...p[Q(0xb8)]},J),P=await fileTypeFromBuffer(F);return b['type'](P?.[Q(0xc4)]??'image/png'),b['header']('Content-Disposition','inline')['header']('Cache-Control','public,\x20max-age=86400,\x20immutable'),b['send'](F);});};}
@@ -1 +1 @@
1
- function U(){const N=['Object','String','Optional','Literal','outside'];U=function(){return N;};return U();}function z(C,N){C=C-0xc1;const r=U();let p=r[C];return p;}const C=z;import{Type}from'@sinclair/typebox';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[C(0xc1)]({'download':Type['Optional'](Type['Boolean']())}),'filePath':Type['Object']({'*':Type['String']({'minLength':0x1,'maxLength':0x400})}),'upload':Type['Object']({'file':Type['Any'](),'metadata':Type['Object']({'name':Type['Optional'](Type[C(0xc2)]({'minLength':0x1})),'path':Type['Optional'](Type['String']({'minLength':0x1})),'entityType':Type[C(0xc3)](Type['String']({'minLength':0x1})),'entityId':Type['Optional'](Type['String']({'minLength':0x1}))})}),'filePatch':Type[C(0xc1)]({'entityType':Type[C(0xc3)](Type['String']({'minLength':0x1})),'entityId':Type[C(0xc3)](Type['String']({'minLength':0x1}))}),'resizeQuery':Type[C(0xc1)]({'width':Type['Optional'](Type['Integer']({'minimum':0x1,'default':0xc8})),'height':Type[C(0xc3)](Type['Integer']({'minimum':0x1})),'fit':Type['Optional'](Type['Union']([Type['Literal']('cover'),Type[C(0xc4)]('contain'),Type['Literal']('fill'),Type['Literal']('inside'),Type['Literal'](C(0xc5))]))})};
1
+ function L(){const e=['String','Object','Boolean','Optional','Union','Literal','cover','fill'];L=function(){return e;};return L();}function c(J,e){J=J-0x172;const p=L();let b=p[J];return b;}const J=c;import{Type}from'@sinclair/typebox';export const fileSchemas={'fileId':Type['Object']({'id':Type[J(0x172)]({'minLength':0x1,'maxLength':0x80})}),'fileToken':Type['Object']({'token':Type['String']({'minLength':0x1,'maxLength':0x800})}),'fileDownloadQuery':Type[J(0x173)]({'download':Type['Optional'](Type[J(0x174)]())}),'filePath':Type['Object']({'*':Type['String']({'minLength':0x1,'maxLength':0x400})}),'upload':Type[J(0x173)]({'file':Type['Any'](),'metadata':Type['Object']({'name':Type[J(0x175)](Type['String']({'minLength':0x1})),'path':Type[J(0x175)](Type['String']({'minLength':0x1})),'entityType':Type['Optional'](Type[J(0x172)]({'minLength':0x1})),'entityId':Type[J(0x175)](Type[J(0x172)]({'minLength':0x1}))})}),'filePatch':Type[J(0x173)]({'entityType':Type[J(0x175)](Type[J(0x172)]({'minLength':0x1})),'entityId':Type['Optional'](Type['String']({'minLength':0x1}))}),'resizeQuery':Type['Object']({'width':Type[J(0x175)](Type['Integer']({'minimum':0x1,'default':0xc8})),'height':Type['Optional'](Type['Integer']({'minimum':0x1})),'fit':Type['Optional'](Type[J(0x176)]([Type[J(0x177)](J(0x178)),Type[J(0x177)]('contain'),Type['Literal'](J(0x179)),Type['Literal']('inside'),Type['Literal']('outside')]))})};
@@ -1 +1 @@
1
- import{NotFoundError}from'../../../errors.js';export async function getFile(C,N){var r=z;if(!N[r(0x183)])throw new Error('empty\x20file');if(!await N['file']['exists'](C['pathOrToken']))throw new NotFoundError('File\x20not\x20found'+C['pathOrToken']);return N[r(0x183)][r(0x184)](C['pathOrToken']);}function z(C,N){C=C-0x183;var r=U();var p=r[C];return p;}function U(){var p=['file','get'];U=function(){return p;};return U();}
1
+ function c(J,e){J=J-0x1cf;var p=L();var b=p[J];return b;}import{NotFoundError}from'../../../errors.js';export async function getFile(J,e){var p=c;if(!e[p(0x1cf)])throw new Error('empty\x20file');if(!await e['file'][p(0x1d0)](J['pathOrToken']))throw new NotFoundError('File\x20not\x20found'+J['pathOrToken']);return e[p(0x1cf)]['get'](J[p(0x1d1)]);}function L(){var b=['file','exists','pathOrToken'];L=function(){return b;};return L();}
@@ -1 +1 @@
1
- function U(){const D=['width','height','fit','cover','logs','file','File\x20not\x20found','startsWith','image/','Only\x20image\x20files\x20can\x20be\x20resized','isInteger','\x20must\x20be\x20a\x20positive\x20integer'];U=function(){return D;};return U();}function z(C,N){C=C-0x6f;const r=U();let p=r[C];return p;}import{NotFoundError,ValidationError}from'../../../errors.js';import{fileTypeFromBuffer}from'file-type';import{createHash}from'node:crypto';import{mkdir,readFile,writeFile}from'node:fs/promises';import C from'node:path';import N from'sharp';export async function resizeFile(r,p){const t=z,c=r['pathOrToken']??r['path'];if(!c)throw new ValidationError('File\x20path\x20is\x20required');const x=parseDimension(r[t(0x6f)],t(0x6f))??0xc8,m=parseDimension(r[t(0x70)],'height'),Q=createHash('sha256')['update'](c+':'+x+':'+(m??'auto')+':'+(r[t(0x71)]??t(0x72)))['digest']('hex'),u=C['resolve'](t(0x73),'resize'),L=C['join'](u,Q+'.jpg');try{return await readFile(L);}catch(F){if(F['code']!=='ENOENT')throw F;}if(!await p[t(0x74)]['exists'](c))throw new NotFoundError(t(0x75));const T=await p[t(0x74)]['get'](c),Y=await fileTypeFromBuffer(T);if(!Y?.['mime'][t(0x76)](t(0x77)))throw new ValidationError(t(0x78));const f=await N(T)['resize']({'width':x,'height':m,'fit':r[t(0x71)]??'cover'})['toBuffer']();return await mkdir(u,{'recursive':!![]}),await writeFile(L,f),f;}function parseDimension(r,p){const h=z;if(r===undefined||r==='')return undefined;const c=Number(r);if(!Number[h(0x79)](c)||c<=0x0)throw new ValidationError(p+h(0x7a));return c;}
1
+ import{NotFoundError,ValidationError}from'../../../errors.js';import{fileTypeFromBuffer}from'file-type';function L(){const l=['pathOrToken','auto','cover','join','.jpg','file','get','Only\x20image\x20files\x20can\x20be\x20resized','isInteger'];L=function(){return l;};return L();}import{createHash}from'node:crypto';import{mkdir,readFile,writeFile}from'node:fs/promises';import J from'node:path';import e from'sharp';function c(J,e){J=J-0x102;const p=L();let b=p[J];return b;}export async function resizeFile(p,b){const Q=c,F=p[Q(0x102)]??p['path'];if(!F)throw new ValidationError('File\x20path\x20is\x20required');const P=parseDimension(p['width'],'width')??0xc8,h=parseDimension(p['height'],'height'),u=createHash('sha256')['update'](F+':'+P+':'+(h??Q(0x103))+':'+(p['fit']??Q(0x104)))['digest']('hex'),H=J['resolve']('logs','resize'),D=J[Q(0x105)](H,u+Q(0x106));try{return await readFile(D);}catch(E){if(E['code']!=='ENOENT')throw E;}if(!await b[Q(0x107)]['exists'](F))throw new NotFoundError('File\x20not\x20found');const U=await b[Q(0x107)][Q(0x108)](F),w=await fileTypeFromBuffer(U);if(!w?.['mime']['startsWith']('image/'))throw new ValidationError(Q(0x109));const X=await e(U)['resize']({'width':P,'height':h,'fit':p['fit']??'cover'})['toBuffer']();return await mkdir(H,{'recursive':!![]}),await writeFile(D,X),X;}function parseDimension(p,b){const T=c;if(p===undefined||p==='')return undefined;const F=Number(p);if(!Number[T(0x10a)](F)||F<=0x0)throw new ValidationError(b+'\x20must\x20be\x20a\x20positive\x20integer');return F;}
@@ -1 +1 @@
1
- function z(C,N){C=C-0x12a;const r=U();let p=r[C];return p;}import{fileTypeFromBuffer}from'file-type';import C from'../mime.js';import{randomUUID}from'node:crypto';function U(){const F=['metadata','replace','getFullYear','getDate','padStart','resourceId','file','put','\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','resource','name','split','pop'];U=function(){return F;};return U();}export async function uploadFile(N,r){const f=z,p=(N[f(0x12a)]['name']??randomUUID())[f(0x12b)](/[^a-zA-Z0-9._-]/g,'_'),c=new Date(),x=String(c[f(0x12c)]())['slice'](-0x2),m=String(c['getMonth']()+0x1)['padStart'](0x2,'0'),Q=String(c[f(0x12d)]())[f(0x12e)](0x2,'0'),u=N['metadata']['path']??(N['metadata']['resource']?N['metadata']['resource']+'/'+(N['metadata'][f(0x12f)]??randomUUID())+'/'+p:null)??'uploads/'+x+'/'+m+'-'+Q+'/'+p,L=await N['file']['toBuffer'](),T=await fileTypeFromBuffer(L);if(!C['has'](N[f(0x130)]['mimetype'])&&(T?.['mime']?!C['has'](T['mime']):!![]))throw new Error('Unsupported\x20file\x20type:\x20'+N[f(0x130)]['mimetype']);await r['file'][f(0x131)](u,L);const Y=await r['pg']['query'](f(0x132),[N[f(0x12a)][f(0x133)]??null,N['metadata']['resourceId']??null,u,N[f(0x130)]['mimetype'],N['file'][f(0x130)]['bytesRead'],N['metadata'][f(0x134)],p,N['file']['mimetype'][f(0x135)]('/')[f(0x136)]()??null,N['user']?.['id']??null]);return Y['rows'][0x0];}
1
+ import{fileTypeFromBuffer}from'file-type';import J from'../mime.js';import{randomUUID}from'node:crypto';function c(J,e){J=J-0x159;const p=L();let b=p[J];return b;}function L(){const E=['metadata','getMonth','padStart','resourceId','file','toBuffer','has','mimetype','mime','resource','rows'];L=function(){return E;};return L();}export async function uploadFile(e,p){const X=c,b=(e[X(0x159)]['name']??randomUUID())['replace'](/[^a-zA-Z0-9._-]/g,'_'),F=new Date(),P=String(F['getFullYear']())['slice'](-0x2),h=String(F[X(0x15a)]()+0x1)['padStart'](0x2,'0'),u=String(F['getDate']())[X(0x15b)](0x2,'0'),H=e['metadata']['path']??(e['metadata']['resource']?e['metadata']['resource']+'/'+(e['metadata'][X(0x15c)]??randomUUID())+'/'+b:null)??'uploads/'+P+'/'+h+'-'+u+'/'+b,D=await e[X(0x15d)][X(0x15e)](),U=await fileTypeFromBuffer(D);if(!J[X(0x15f)](e['file'][X(0x160)])&&(U?.[X(0x161)]?!J['has'](U['mime']):!![]))throw new Error('Unsupported\x20file\x20type:\x20'+e['file']['mimetype']);await p['file']['put'](H,D);const w=await p['pg']['query']('\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['metadata'][X(0x162)]??null,e[X(0x159)][X(0x15c)]??null,H,e['file']['mimetype'],e['file'][X(0x15d)]['bytesRead'],e[X(0x159)]['name'],b,e['file']['mimetype']['split']('/')['pop']()??null,e['user']?.['id']??null]);return w[X(0x163)][0x0];}
@@ -1 +1 @@
1
- const m=z;function U(){const L=['user','get','/api/resource/:resource/search','resource','Searches\x20records\x20in\x20a\x20registered\x20resource.','/api/suggest/:resource/:field','fcore','Returns\x20suggested\x20values\x20for\x20a\x20resource\x20field.','suggestQuery','/api/resource/:resource/export','Exports\x20readable\x20records\x20from\x20a\x20registered\x20resource.','params','/api/resource/:resource/:id','resourceIncludeQuery','post','/api/resource/:resource/:id/upload','uploadResourceFile','permissions',':update','fields','resourceIdRelation','/api/resource/:resource/:id/:relation','Delete\x20resource\x20relation'];U=function(){return L;};return U();}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';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 z(C,N){C=C-0x1bf;const r=U();let p=r[C];return p;}import{resourceSchemas}from'./schema.js';import{uploadFile}from'../file/services/upload-file.js';const user=C=>C[m(0x1bf)];export function resourceRoutes(C){return async N=>{const Q=z;N[Q(0x1c0)](Q(0x1c1),{'schema':{'tags':['fcore',Q(0x1c2)],'summary':'Search\x20resource','description':Q(0x1c3),'access':'user','permissions':[],'params':resourceSchemas['resource']}},async r=>searchResource({...r['query'],...r['params'],'user':user(r)},C)),N[Q(0x1c0)](Q(0x1c4),{'schema':{'tags':[Q(0x1c5),Q(0x1c2)],'summary':'Suggest\x20resource\x20values','description':Q(0x1c6),'access':Q(0x1bf),'permissions':[],'params':resourceSchemas['resourceField'],'querystring':resourceSchemas[Q(0x1c7)]}},async r=>suggestResource({...r['query'],...r['params'],'user':user(r)},C)),N['get'](Q(0x1c8),{'schema':{'tags':['fcore',Q(0x1c2)],'summary':'Export\x20resource\x20records','description':Q(0x1c9),'access':'user','permissions':['*:read'],'params':resourceSchemas['exportResource'],'querystring':resourceSchemas['exportResourceQuery']}},async r=>exportResource({...r['query'],...r['params'],'user':user(r)},C)),N['get']('/api/resource/:resource',{'schema':{'tags':['fcore','resource'],'summary':'List\x20resource\x20records','description':'Returns\x20records\x20from\x20a\x20registered\x20resource.','access':'user','permissions':[],'params':resourceSchemas[Q(0x1c2)]}},async r=>listResources({...r['query'],...r['params'],'user':user(r)},C)),N['post']('/api/resource/:resource',{'schema':{'tags':['fcore',Q(0x1c2)],'summary':'Create\x20resource\x20record','description':'Creates\x20a\x20record\x20in\x20a\x20registered\x20resource.','access':'user','permissions':[],'params':resourceSchemas['resource']}},async r=>createResource({...r[Q(0x1ca)],'data':r['body'],'user':user(r)},C)),N['get'](Q(0x1cb),{'schema':{'tags':['fcore','resource'],'summary':'Get\x20resource\x20record','description':'Returns\x20one\x20record\x20from\x20a\x20registered\x20resource.','access':'user','permissions':[],'params':resourceSchemas['resourceId'],'querystring':resourceSchemas[Q(0x1cc)]}},async r=>getResource({...r['query'],...r['params'],'user':user(r)},C)),N['put']('/api/resource/:resource/:id',{'schema':{'tags':['fcore','resource'],'summary':'Update\x20resource\x20record','description':'Updates\x20a\x20record\x20in\x20a\x20registered\x20resource.','access':Q(0x1bf),'permissions':[],'params':resourceSchemas['resourceId']}},async r=>updateResource({...r[Q(0x1ca)],'patch':r['body'],'user':user(r)},C)),N['delete']('/api/resource/:resource/:id',{'schema':{'tags':[Q(0x1c5),'resource'],'summary':'Delete\x20resource\x20record','description':'Deletes\x20a\x20record\x20from\x20a\x20registered\x20resource.','access':'user','permissions':[],'params':resourceSchemas['resourceId']}},async r=>deleteResource({...r[Q(0x1ca)],'user':user(r)},C)),N[Q(0x1cd)](Q(0x1ce),{'schema':{'tags':[Q(0x1c5),'resource'],'summary':'Upload\x20resource\x20file','description':'Uploads\x20a\x20file\x20to\x20a\x20Resource\x20record\x20and\x20stores\x20its\x20metadata.','access':'user','permissions':[],'params':resourceSchemas[Q(0x1cf)]}},async r=>{const u=Q,p=await r['file']();if(!p)throw new Error('File\x20is\x20required');const c=r['params'][u(0x1c2)],x=r['params']['id'];if(r['user']?.['type']!=='admin'&&!r[u(0x1bf)]?.[u(0x1d0)]['includes'](c+':update'))throw new ForbiddenError('Missing\x20permission:\x20'+c+u(0x1d1));return uploadFile({'file':p,'metadata':{'name':p['filename'],'path':p[u(0x1d2)]['path']?.['value'],'resource':c,'resourceId':x},'user':r['user']},C);}),N['get']('/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[Q(0x1d3)]}}},async r=>listResourceRelation({...r['query'],...r['params'],'user':user(r)},C)),N['post'](Q(0x1d4),{'schema':{'tags':[Q(0x1c5),'resource'],'summary':'Create\x20resource\x20relation','description':'Creates\x20a\x20relation\x20for\x20a\x20resource\x20record.','access':'user','permissions':[],'params':resourceSchemas[Q(0x1d3)]}},async r=>createResourceRelation({...r['params'],'data':r['body'],'user':user(r)},C)),N['delete']('/api/resource/:resource/:id/:relation/:relationId',{'schema':{'tags':['fcore','resource'],'summary':Q(0x1d5),'description':'Deletes\x20a\x20relation\x20from\x20a\x20resource\x20record.','access':Q(0x1bf),'permissions':[],'params':resourceSchemas['resourceIdRelationId']}},async r=>deleteResourceRelation({...r['params'],'user':user(r)},C)),N['put']('/api/resource/:resource/:id/:relation/:relationId',{'schema':{'tags':[Q(0x1c5),'resource'],'summary':'Update\x20resource\x20relation','description':'Updates\x20a\x20related\x20resource\x20record.','access':'user','permissions':[],'params':resourceSchemas['resourceIdRelationId']}},async r=>updateResourceRelation({...r[Q(0x1ca)],'data':r['body'],'user':user(r)},C));};}
1
+ const h=c;function L(){const D=['user','get','/api/resource/:resource/search','fcore','Search\x20resource','resource','query','/api/resource/:resource','/api/resource/:resource/:id','Returns\x20one\x20record\x20from\x20a\x20registered\x20resource.','resourceIncludeQuery','params','body','Deletes\x20a\x20record\x20from\x20a\x20registered\x20resource.','post','/api/resource/:resource/:id/upload','file','path','Returns\x20related\x20records\x20for\x20a\x20resource\x20record.','resourceIdRelation','delete','Deletes\x20a\x20relation\x20from\x20a\x20resource\x20record.','resourceIdRelationId','put','/api/resource/:resource/:id/:relation/:relationId','Update\x20resource\x20relation','Updates\x20a\x20related\x20resource\x20record.'];L=function(){return D;};return L();}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 c(J,e){J=J-0x1ef;const p=L();let b=p[J];return b;}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=J=>J[h(0x1ef)];export function resourceRoutes(J){return async e=>{const u=c;e[u(0x1f0)](u(0x1f1),{'schema':{'tags':[u(0x1f2),'resource'],'summary':u(0x1f3),'description':'Searches\x20records\x20in\x20a\x20registered\x20resource.','access':'user','permissions':[],'params':resourceSchemas[u(0x1f4)]}},async p=>searchResource({...p['query'],...p['params'],'user':user(p)},J)),e['get']('/api/suggest/:resource/:field',{'schema':{'tags':[u(0x1f2),'resource'],'summary':'Suggest\x20resource\x20values','description':'Returns\x20suggested\x20values\x20for\x20a\x20resource\x20field.','access':'user','permissions':[],'params':resourceSchemas['resourceField'],'querystring':resourceSchemas['suggestQuery']}},async p=>suggestResource({...p[u(0x1f5)],...p['params'],'user':user(p)},J)),e[u(0x1f0)]('/api/resource/:resource/export',{'schema':{'tags':[u(0x1f2),u(0x1f4)],'summary':'Export\x20resource\x20records','description':'Exports\x20readable\x20records\x20from\x20a\x20registered\x20resource.','access':u(0x1ef),'permissions':['*:read'],'params':resourceSchemas['exportResource'],'querystring':resourceSchemas['exportResourceQuery']}},async p=>exportResource({...p['query'],...p['params'],'user':user(p)},J)),e[u(0x1f0)](u(0x1f6),{'schema':{'tags':[u(0x1f2),u(0x1f4)],'summary':'List\x20resource\x20records','description':'Returns\x20records\x20from\x20a\x20registered\x20resource.','access':'user','permissions':[],'params':resourceSchemas['resource']}},async p=>listResources({...p[u(0x1f5)],...p['params'],'user':user(p)},J)),e['post']('/api/resource/:resource',{'schema':{'tags':['fcore',u(0x1f4)],'summary':'Create\x20resource\x20record','description':'Creates\x20a\x20record\x20in\x20a\x20registered\x20resource.','access':'user','permissions':[],'params':resourceSchemas[u(0x1f4)]}},async p=>createResource({...p['params'],'data':p['body'],'user':user(p)},J)),e['get'](u(0x1f7),{'schema':{'tags':['fcore','resource'],'summary':'Get\x20resource\x20record','description':u(0x1f8),'access':'user','permissions':[],'params':resourceSchemas['resourceId'],'querystring':resourceSchemas[u(0x1f9)]}},async p=>getResource({...p[u(0x1f5)],...p[u(0x1fa)],'user':user(p)},J)),e['put'](u(0x1f7),{'schema':{'tags':['fcore','resource'],'summary':'Update\x20resource\x20record','description':'Updates\x20a\x20record\x20in\x20a\x20registered\x20resource.','access':'user','permissions':[],'params':resourceSchemas['resourceId']}},async p=>updateResource({...p['params'],'patch':p[u(0x1fb)],'user':user(p)},J)),e['delete']('/api/resource/:resource/:id',{'schema':{'tags':['fcore','resource'],'summary':'Delete\x20resource\x20record','description':u(0x1fc),'access':u(0x1ef),'permissions':[],'params':resourceSchemas['resourceId']}},async p=>deleteResource({...p['params'],'user':user(p)},J)),e[u(0x1fd)](u(0x1fe),{'schema':{'tags':[u(0x1f2),'resource'],'summary':'Upload\x20resource\x20file','description':'Uploads\x20a\x20file\x20to\x20a\x20Resource\x20record\x20and\x20stores\x20its\x20metadata.','access':'user','permissions':[],'params':resourceSchemas['uploadResourceFile']}},async p=>{const H=u,b=await p[H(0x1ff)]();if(!b)throw new Error('File\x20is\x20required');const F=p['params']['resource'],P=p['params']['id'];if(p['user']?.['type']!=='admin'&&!p['user']?.['permissions']['includes'](F+':update'))throw new ForbiddenError('Missing\x20permission:\x20'+F+':update');return uploadFile({'file':b,'metadata':{'name':b['filename'],'path':b['fields'][H(0x200)]?.['value'],'resource':F,'resourceId':P},'user':p['user']},J);}),e[u(0x1f0)]('/api/resource/:resource/:id/:relation',{'schema':{'tags':['fcore','resource'],'summary':'List\x20resource\x20relations','description':u(0x201),'access':'user','permissions':[],'schema':{'params':resourceSchemas[u(0x202)]}}},async p=>listResourceRelation({...p['query'],...p['params'],'user':user(p)},J)),e['post']('/api/resource/:resource/:id/:relation',{'schema':{'tags':['fcore','resource'],'summary':'Create\x20resource\x20relation','description':'Creates\x20a\x20relation\x20for\x20a\x20resource\x20record.','access':u(0x1ef),'permissions':[],'params':resourceSchemas['resourceIdRelation']}},async p=>createResourceRelation({...p['params'],'data':p[u(0x1fb)],'user':user(p)},J)),e[u(0x203)]('/api/resource/:resource/:id/:relation/:relationId',{'schema':{'tags':['fcore','resource'],'summary':'Delete\x20resource\x20relation','description':u(0x204),'access':'user','permissions':[],'params':resourceSchemas[u(0x205)]}},async p=>deleteResourceRelation({...p['params'],'user':user(p)},J)),e[u(0x206)](u(0x207),{'schema':{'tags':['fcore','resource'],'summary':u(0x208),'description':u(0x209),'access':u(0x1ef),'permissions':[],'params':resourceSchemas['resourceIdRelationId']}},async p=>updateResourceRelation({...p['params'],'data':p['body'],'user':user(p)},J));};}
@@ -1 +1 @@
1
- const C=z;function z(C,N){C=C-0x1cc;const r=U();let p=r[C];return p;}import{Type}from'@sinclair/typebox';function U(){const N=['Object','Optional','String','Any','Unknown'];U=function(){return N;};return U();}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[C(0x1cc)]({'name':identifier}),'resource':Type[C(0x1cc)]({'resource':identifier}),'exportResource':Type['Object']({'resource':identifier}),'resourceField':Type['Object']({'resource':identifier,'field':identifier}),'suggestQuery':Type['Object']({'q':Type[C(0x1cd)](Type[C(0x1ce)]()),'search':Type['Optional'](Type['String']()),'limit':Type['Optional'](Type['Integer']({'minimum':0x1,'maximum':0xc8}))}),'resourceId':Type['Object']({'resource':identifier,'id':identifier}),'resourceIncludeQuery':Type[C(0x1cc)]({'include':Type['Optional'](Type[C(0x1ce)]({'minLength':0x1}))}),'resourceIdRelation':Type['Object']({'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['Object']({'file':Type[C(0x1cf)](),'fileName':Type['String']({'minLength':0x1,'maxLength':0xff})}),'exportResourceQuery':Type['Object']({'filter':Type['Optional'](Type['Record'](Type[C(0x1ce)](),Type[C(0x1d0)]())),'sort':Type[C(0x1cd)](Type['Array'](Type['String']({'minLength':0x1}))),'search':Type['Optional'](Type[C(0x1ce)]()),'limit':Type['Optional'](Type['Integer']({'minimum':0x1,'maximum':0xc8})),'offset':Type['Optional'](Type['Integer']({'minimum':0x0})),'fields':Type[C(0x1cd)](Type['Array'](identifier))})};
1
+ const J=c;import{Type}from'@sinclair/typebox';function c(J,e){J=J-0x19e;const p=L();let b=p[J];return b;}function L(){const e=['^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$','Object','Optional','String','Integer','Any','Unknown'];L=function(){return e;};return L();}export const identifier=Type['String']({'minLength':0x1,'maxLength':0x80,'pattern':J(0x19e)});export const resourceSchemas={'dictionaryName':Type['Object']({'name':identifier}),'resource':Type['Object']({'resource':identifier}),'exportResource':Type[J(0x19f)]({'resource':identifier}),'resourceField':Type['Object']({'resource':identifier,'field':identifier}),'suggestQuery':Type['Object']({'q':Type[J(0x1a0)](Type['String']()),'search':Type['Optional'](Type[J(0x1a1)]()),'limit':Type['Optional'](Type[J(0x1a2)]({'minimum':0x1,'maximum':0xc8}))}),'resourceId':Type['Object']({'resource':identifier,'id':identifier}),'resourceIncludeQuery':Type['Object']({'include':Type[J(0x1a0)](Type['String']({'minLength':0x1}))}),'resourceIdRelation':Type[J(0x19f)]({'resource':identifier,'id':identifier,'relation':identifier}),'resourceIdRelationId':Type[J(0x19f)]({'resource':identifier,'id':identifier,'relation':identifier,'relationId':identifier}),'uploadResourceFile':Type[J(0x19f)]({'resource':identifier,'id':identifier}),'uploadResourceFileBody':Type['Object']({'file':Type[J(0x1a3)](),'fileName':Type[J(0x1a1)]({'minLength':0x1,'maxLength':0xff})}),'exportResourceQuery':Type['Object']({'filter':Type[J(0x1a0)](Type['Record'](Type['String'](),Type[J(0x1a4)]())),'sort':Type['Optional'](Type['Array'](Type['String']({'minLength':0x1}))),'search':Type['Optional'](Type[J(0x1a1)]()),'limit':Type['Optional'](Type['Integer']({'minimum':0x1,'maximum':0xc8})),'offset':Type['Optional'](Type[J(0x1a2)]({'minimum':0x0})),'fields':Type[J(0x1a0)](Type['Array'](identifier))})};
@@ -1 +1 @@
1
- export async function addNote(C,N){const p=await N['pg']['query']('INSERT\x20INTO\x20admin.notes(resource,resource_id,body)\x20VALUES\x20($1,$2,$3)\x20RETURNING\x20*',[C['resource'],String(C['id']),C['body']]);return p['rows'][0x0];}
1
+ function c(J,e){J=J-0x135;const p=L();let b=p[J];return b;}export async function addNote(J,e){const b=c,p=await e['pg']['query'](b(0x135),[J[b(0x136)],String(J['id']),J[b(0x137)]]);return p['rows'][0x0];}function L(){const F=['INSERT\x20INTO\x20admin.notes(resource,resource_id,body)\x20VALUES\x20($1,$2,$3)\x20RETURNING\x20*','resource','body'];L=function(){return F;};return L();}
@@ -1 +1 @@
1
- function z(C,N){C=C-0x9b;const r=U();let p=r[C];return p;}export async function addResourceFile(C,N){const p=z,r=await N['pg']['query'](p(0x9b),[C['resource'],String(C['id']),C[p(0x9c)],C[p(0x9d)]??null]);return r[p(0x9e)][0x0];}function U(){const c=['\x0a\x20\x20\x20\x20\x20\x20\x20\x20INSERT\x20INTO\x20admin.files\x20(resource,\x20resource_id,\x20file_path,\x20size)\x0a\x20\x20\x20\x20\x20\x20\x20\x20VALUES\x20($1,\x20$2,\x20$3,\x20$4)\x0a\x20\x20\x20\x20\x20\x20\x20\x20RETURNING\x20*\x0a\x20\x20\x20\x20\x20\x20','filePath','size','rows'];U=function(){return c;};return U();}
1
+ function L(){const F=['query','rows'];L=function(){return F;};return L();}function c(J,e){J=J-0xdd;const p=L();let b=p[J];return b;}export async function addResourceFile(J,e){const b=c,p=await e['pg'][b(0xdd)]('\x0a\x20\x20\x20\x20\x20\x20\x20\x20INSERT\x20INTO\x20admin.files\x20(resource,\x20resource_id,\x20file_path,\x20size)\x0a\x20\x20\x20\x20\x20\x20\x20\x20VALUES\x20($1,\x20$2,\x20$3,\x20$4)\x0a\x20\x20\x20\x20\x20\x20\x20\x20RETURNING\x20*\x0a\x20\x20\x20\x20\x20\x20',[J['resource'],String(J['id']),J['filePath'],J['size']??null]);return p[b(0xde)][0x0];}