@decaf-ts/for-nest 0.9.0 → 0.10.0

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 (64) hide show
  1. package/README.md +45 -1
  2. package/dist/for-nest.cjs +1 -1
  3. package/dist/for-nest.cjs.map +1 -1
  4. package/dist/for-nest.js +1 -1
  5. package/dist/for-nest.js.map +1 -1
  6. package/lib/cjs/cli-module.cjs +74 -82
  7. package/lib/cjs/cli-module.cjs.map +1 -1
  8. package/lib/cjs/controllers.cjs +1 -1
  9. package/lib/cjs/controllers.cjs.map +1 -1
  10. package/lib/cjs/core-module.cjs +6 -18
  11. package/lib/cjs/core-module.cjs.map +1 -1
  12. package/lib/cjs/index.cjs +17 -2
  13. package/lib/cjs/index.cjs.map +1 -1
  14. package/lib/cjs/migrations/index.cjs +35 -0
  15. package/lib/cjs/migrations/index.cjs.map +1 -0
  16. package/lib/cjs/migrations/migration-module.cjs +93 -0
  17. package/lib/cjs/migrations/migration-module.cjs.map +1 -0
  18. package/lib/cjs/migrations/migration-options.cjs +4 -0
  19. package/lib/cjs/migrations/migration-options.cjs.map +1 -0
  20. package/lib/cjs/module.cjs +2 -0
  21. package/lib/cjs/module.cjs.map +1 -1
  22. package/lib/cjs/swagger-types.cjs +4 -0
  23. package/lib/cjs/swagger-types.cjs.map +1 -0
  24. package/lib/esm/cli-module.js +73 -82
  25. package/lib/esm/cli-module.js.map +1 -1
  26. package/lib/esm/controllers.js +1 -1
  27. package/lib/esm/controllers.js.map +1 -1
  28. package/lib/esm/core-module.js +5 -17
  29. package/lib/esm/core-module.js.map +1 -1
  30. package/lib/esm/decaf-model/FromModelController.js.map +1 -1
  31. package/lib/esm/index.js +16 -1
  32. package/lib/esm/index.js.map +1 -1
  33. package/lib/esm/migrations/index.js +18 -0
  34. package/lib/esm/migrations/index.js.map +1 -0
  35. package/lib/esm/migrations/migration-module.js +52 -0
  36. package/lib/esm/migrations/migration-module.js.map +1 -0
  37. package/lib/esm/migrations/migration-options.js +7 -0
  38. package/lib/esm/migrations/migration-options.js.map +1 -0
  39. package/lib/esm/module.js +1 -0
  40. package/lib/esm/module.js.map +1 -1
  41. package/lib/esm/overrides/decoration.js.map +1 -1
  42. package/lib/esm/swagger-types.js +2 -0
  43. package/lib/esm/swagger-types.js.map +1 -0
  44. package/lib/types/cli-module.d.cts +9 -0
  45. package/lib/types/cli-module.d.mts +9 -0
  46. package/lib/types/core-module.d.cts +3 -2
  47. package/lib/types/core-module.d.mts +3 -2
  48. package/lib/types/factory/openapi/constants.d.cts +1 -1
  49. package/lib/types/factory/openapi/constants.d.mts +1 -1
  50. package/lib/types/index.d.cts +16 -1
  51. package/lib/types/index.d.mts +16 -1
  52. package/lib/types/migrations/index.d.cts +17 -0
  53. package/lib/types/migrations/index.d.mts +17 -0
  54. package/lib/types/migrations/migration-module.d.cts +15 -0
  55. package/lib/types/migrations/migration-module.d.mts +15 -0
  56. package/lib/types/migrations/migration-options.d.cts +11 -0
  57. package/lib/types/migrations/migration-options.d.mts +11 -0
  58. package/lib/types/module.d.cts +1 -0
  59. package/lib/types/module.d.mts +1 -0
  60. package/lib/types/overrides/decoration.d.cts +1 -3
  61. package/lib/types/overrides/decoration.d.mts +1 -3
  62. package/lib/types/swagger-types.d.cts +67 -0
  63. package/lib/types/swagger-types.d.mts +67 -0
  64. package/package.json +1 -1
package/README.md CHANGED
@@ -28,7 +28,7 @@ This repository is meant to provide an enterprise template for any standard Type
28
28
 
29
29
  Documentation available [here](https://decaf-ts.github.io/for-nest/)
30
30
 
31
- Minimal size: 12.4 KB kb gzipped
31
+ Minimal size: 12.6 KB kb gzipped
32
32
 
33
33
 
34
34
  ### Description
@@ -54,7 +54,51 @@ Now you can create new repositories from this template and enjoy having everythi
54
54
  - [Considerations](./workdocs/tutorials/For%20Developers.md#considerations)
55
55
 
56
56
 
57
+ -## Migration execution
57
58
 
59
+ `DecafCoreModule.migrate` wraps `MigrationService.migrateAdapters` once the persistence layer is ready. Use it to orchestrate upgrades across the adapters you boot in `DecafCoreModule.bootPersistence`.
60
+
61
+ ```ts
62
+ const migrations = await DecafCoreModule.migrate({
63
+ flavours: ["nano", "type-orm"],
64
+ taskMode: true,
65
+ taskService,
66
+ });
67
+
68
+ for (const migration of migrations) {
69
+ await migration.track();
70
+ }
71
+ ```
72
+
73
+ Passing `taskMode: true` causes each semver bump to become a tracked `CompositeTask`. Boot a dedicated `RamAdapter` and `TaskService` (never share the task engine alias with migrating adapters) before calling `migrate`, and make sure your version handlers (`retrieveLastVersion` / `setCurrentVersion`) live inside the module that owns the adapter.
74
+
75
+ From the CLI, the same flow is exposed as `npx decaf nest migrate`. Example:
76
+
77
+ ```bash
78
+ npx decaf nest migrate \
79
+ --input ./dist/app.module.js \
80
+ --flavour nano,type-orm \
81
+ --to 1.2.0 \
82
+ --task-mode \
83
+ --dry-run=false
84
+ ```
85
+
86
+ `DecafCoreModule.migrate` consults the migration handlers you registered per flavour (`retrieveLastVersion`/`setCurrentVersion`) so it always knows the current persisted head before building the execution plan. When `taskMode` is enabled each version is enqueued as a tracked `CompositeTask`; immediately after each task resolves `MigrationService.track()` calls `setCurrentVersion` for that version so the stored `currentVersion` equals the last fully applied hop. Failed tasks leave the version untouched, allowing `MigrationService.retry(taskId)` (optionally observed via `taskService.track(id)`) to reset the `TaskModel` to `PENDING`, clear its error/lease metadata, and replay only the incomplete version before proceeding.
87
+
88
+ In inline (non-task) mode the version marker updates only once after the entire batch completes, whereas task mode updates after each version so the next run always resumes at the correct semantic boundary even if an earlier version already succeeded. Specify `toVersion` (CLI `--to`) to define your goal; `MigrationService` filters migrations to those whose normalized versions fall strictly between the persisted `currentVersion` and the requested target so every run progressively walks the system through its lifecycle.
89
+
90
+ Control precedence through the `@migration` decorator:
91
+
92
+ - `reference`: the canonical label (typically semver) used in logs and dependency hints.
93
+ - `precedence`: point to another migration (constructor, token, or object) to force ordering between migrations with identical version/flavour.
94
+ - `flavour`: restricts the migration to a given adapter flavour (`"nano"`, `"type-orm"`, `"hlf-fabric"`, ...).
95
+ - `rules`: async predicates `(qr, adapter, ctx)` that gate execution; if a rule returns `false` the migration is skipped without failing the run.
96
+
97
+ Keep your TaskEngine on a `RamAdapter` alias that never overlaps the adapters being migrated so lease metadata stays isolated, and let `MigrationService` track each version to ensure `currentVersion` only advances after a migration succeeds.
98
+
99
+ The CLI boots the Nest context without opening HTTP ports, creates a `RamAdapter` task engine (`decaf-cli-task-engine`), attaches the logger to every queued migration tracker, and waits on `migration.track()` before shutting down the task service, adapter, and Nest app. CLI flags always win over `decaf.migration` entries inside `package.json`. `--dry-run` remains a compatibility flag and no longer skips persistence.
100
+
101
+ Refer to the [CLI module](../cli/workdocs/5-HowToUse.md) for how to boot the command runner; this migration command is implemented inside `for-nest` and reuses the `DecafCoreModule.migrate` wiring described above.
58
102
 
59
103
  ## Coding Principles
60
104
 
package/dist/for-nest.cjs CHANGED
@@ -1,2 +1,2 @@
1
- var e,t;e=this,t=function(e,t,r,o,a,s,i,n,c,p,d,l,u,h,m,f,y){"use strict";function g(e){var t=Object.create(null);return e&&Object.keys(e).forEach(r=>{if("default"!==r){var o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,o.get?o:{enumerable:!0,get:()=>e[r]})}}),t.default=e,Object.freeze(t)}var _=g(m);const A="swagger",b={API_OPERATION:A+"/apiOperation",API_RESPONSE:A+"/apiResponse",API_PRODUCES:A+"/apiProduces",API_CONSUMES:A+"/apiConsumes",API_TAGS:A+"/apiUseTags",API_CALLBACKS:A+"/apiCallbacks",API_PARAMETERS:A+"/apiParameters",API_HEADERS:A+"/apiHeaders",API_MODEL_PROPERTIES:A+"/apiModelProperties",API_MODEL_PROPERTIES_ARRAY:A+"/apiModelPropertiesArray",API_SECURITY:A+"/apiSecurity",API_EXCLUDE_ENDPOINT:A+"/apiExcludeEndpoint",API_EXCLUDE_CONTROLLER:A+"/apiExcludeController",API_EXTRA_MODELS:A+"/apiExtraModels",API_EXTENSION:A+"/apiExtension",API_SCHEMA:A+"/apiSchema",API_DEFAULT_GETTER:A+"/apiDefaultGetter",API_LINK:A+"/apiLink"},E=e=>void 0===e;function P(e){if("function"==typeof e)return P(e());if(Array.isArray(e))return e;if("object"!=typeof e)return[];const t=Object.values(e).filter(e=>"number"==typeof e).map(e=>e.toString());return Object.keys(e).filter(e=>!t.includes(e)).map(t=>e[t])}function O(e){return e.filter(i.isString).length>0?"string":"number"}function R(e,t,r=!0){return(o,a)=>{const s=Reflect.getMetadata(b.API_MODEL_PROPERTIES_ARRAY,o)||[],n=":"+a;s.includes(n)||Reflect.defineMetadata(b.API_MODEL_PROPERTIES_ARRAY,[...s,":"+a],o);const c=Reflect.getMetadata(e,o,a);if(c){const s=i.pickBy(t,i.negate(E)),n=r?{...c,...s}:{...s,...c};Reflect.defineMetadata(e,n,o,a)}else{const r=o?.constructor?._OPENAPI_METADATA_FACTORY?.()[a]?.type??Reflect.getMetadata("design:type",o,a);Reflect.defineMetadata(e,{type:r,required:!1,...i.pickBy(t,i.negate(E))},o,a)}}}function v(e={}){return w(e)}function w(e={},t=!0){const[r,o]=((e,t)=>{if(!e)return[e,t];if(t)return[e,t];const r=i.isArray(e);return[r?e[0]:e,r]})(e.type,e.isArray);if((a=e={...e,type:r,isArray:o}).isArray&&"enum"in a&&void 0!==a.enum){e.type="array";const t=P(e.enum);e.items={type:O(t),enum:t},delete e.enum}else if("enum"in e&&void 0!==e.enum){const t=P(e.enum);e.enum=t,e.type=O(t)}var a;return Array.isArray(e.type)&&(e.type="array",e.items={type:"array",items:{type:e.type[0]}}),R(b.API_MODEL_PROPERTIES,e,t)}function D(e,r){const{handler:o,args:a}=t.Metadata.get(e,c.OperationKeys.REFLECT+c.OperationKeys.BLOCK)||{};return!!o&&(o(...a,r)??!1)}function S(e,r,a){const s={GET:[c.OperationKeys.READ,o.Get],POST:[c.OperationKeys.CREATE,o.Post],PUT:[c.OperationKeys.UPDATE,o.Put],PATCH:[c.OperationKeys.UPDATE,o.Patch],DELETE:[c.OperationKeys.DELETE,o.Delete]},[i,p]=s[r];return D(e,i)?t.apply(n.ApiExcludeEndpoint()):t.apply(p(a))}function T(e=[]){const t=e.map(e=>n.ApiParam({name:e.name,description:e.description??"Path parameter: "+e.name,required:e.required??!0,type:e.type??String}));return o.applyDecorators(...t)}const C=o.createParamDecorator((e,t)=>{const r=t.switchToHttp().getRequest().body,a=t.getClass(),s=a.class;if(!s)throw new o.InternalServerErrorException(`ModelConstructor not found on controller ${a.name}. Ensure the controller was created via FromModelController.`);return r?Array.isArray(r)?r.map(e=>new s(e)):new s(r):r}),x=o.createParamDecorator((e,t)=>{const r=t.switchToHttp().getRequest(),o=r?.params??{},a=e??Object.keys(o),s=a.map(e=>o[e]);return{raw:o,valuesInOrder:s,keysInOrder:a}});function I(e=[]){const t=e.map(e=>e.name);return x(t)}const M=o.createParamDecorator((e,t)=>{const r={...t.switchToHttp().getRequest().query??{}};if(void 0!==r.limit){const e=Number(r.limit);Number.isNaN(e)||(r.limit=e)}if(void 0!==r.offset){const e=Number(r.offset);Number.isNaN(e)||(r.offset=e)}if(void 0!==r.bookmark){const e=Number(r.bookmark);r.bookmark=Number.isNaN(e)?r.bookmark:e}return r});function $(e){const t={GET:o.Get,POST:o.Post,PUT:o.Put,PATCH:o.Patch,DELETE:o.Delete}[e];if(!t)throw Error(`Unsupported HTTP verb "${e}". No NestJS decorator mapping was found.`);return t}const q="DecafModuleOptions",F="DecafAdapter",k="DecafRoute",N=Symbol("DecafHandlers"),j=Symbol("DecafAdapterForOptions"),L=Symbol("AUTH_HANDLER"),K="auth:meta",B=Symbol("decaf:context");function U(t){const r=t?"string"==typeof t?t:t.name:void 0,a=[n.ApiBearerAuth(),o.UseInterceptors(e.AuthInterceptor)];return r&&a.push(o.SetMetadata(K,r)),o.applyDecorators(...a)}e.AuthInterceptor=class{constructor(e,t){this.reflector=e,this.authHandler=t}async intercept(e,t){const r=l.Logging.for(this).for(this.intercept),o=this.reflector.get(K,e.getHandler())??this.reflector.get(K,e.getClass());return r.verbose("Intercepted request"+(o?" for "+o:"")),this.authHandler?await this.authHandler.authorize(e,o):r.debug("No auth handler/model"),t.handle()}},e.AuthInterceptor=p.__decorate([o.Injectable(),p.__param(1,o.Optional()),p.__param(1,o.Inject(L)),p.__metadata("design:paramtypes",[d.Reflector,Object])],e.AuthInterceptor);class H{parseRequest(e){const t=e.headers.authorization?.split(" ")[1];return t}async authorize(e,r){const o=e.switchToHttp().getRequest(),i=this.parseRequest(o);if(!i)throw new s.AuthorizationError("Unauthenticated");if(!t.Metadata.get(a.Model.get(r),s.PersistenceKeys.AUTH_ROLE).includes(i))throw new s.AuthorizationError("Missing role: "+i)}}var G;e.DecafRequestContext=class{constructor(e){this.req=e,this.uuid=s.UUID.instance.generate()}get request(){return this.req}put(e){let t;try{t=this.ctx.get("overrides")}catch(e){t={}}this._ctx=this.ctx.accumulate({overrides:Object.assign(t,e)})}applyCtx(e){if(this._ctx)throw new c.InternalError("Trying to overwrite context");this._ctx=e}get ctx(){if(!this._ctx)throw new c.InternalError("Context not initialized for request");return this._ctx}},e.DecafRequestContext=p.__decorate([o.Injectable({scope:o.Scope.REQUEST}),p.__param(0,o.Inject(d.REQUEST)),p.__metadata("design:paramtypes",[Request])],e.DecafRequestContext),e.DecafHandlerExecutor=G=class{constructor(e,t){this.handlers=e,this.context=t}async exec(e,t){l.Logging.for(G.name).for(this.exec).debug(`CONTEXT ${this.context.uuid} running ${this.handlers.length} handlers for request ${e.method} ${e.url}`);for(const r of this.handlers)await r.handle(this.context,e,t)}},e.DecafHandlerExecutor=G=p.__decorate([o.Injectable({scope:o.Scope.REQUEST}),p.__param(0,o.Inject(N)),p.__metadata("design:paramtypes",[Array,e.DecafRequestContext])],e.DecafHandlerExecutor),e.DecafResponseInterceptor=class{constructor(e){this.ctx=e}intercept(e,t){let r=e.switchToHttp().getResponse();return t.handle().pipe(u.tap(e=>{r=this.ctx.ctx.toResponse(r)}))}},e.DecafResponseInterceptor=p.__decorate([o.Injectable(),p.__metadata("design:paramtypes",[e.DecafRequestContext])],e.DecafResponseInterceptor);const z=e=>({name:e,description:e+" parameter for the query",required:!0,type:String});function Q(e,t,r,a=!1){const i=$(r),c=(e=>e.split("/").filter(e=>e.startsWith(":")).map(e=>e.slice(1)))(t).map(z),p=[];return"GET"===r&&a&&p.push(n.ApiQuery({name:"direction",required:!1,enum:s.OrderDirection,description:"the sort order when applicable"}),n.ApiQuery({name:"limit",required:!1,description:"limit or page size when applicable"}),n.ApiQuery({name:"offset",required:!1,description:"offset or bookmark when applicable"})),{method:[i(t),...c.map(n.ApiParam),...p,n.ApiOperation({summary:`Retrieve records using according to "${e}".`}),n.ApiOkResponse({description:"Result successfully retrieved."}),n.ApiNoContentResponse({description:"No content returned by the method."})],params:[I(c),o.Query()]}}function V(e,t,r,o){const a=e?.prototype??e;o.method.forEach(e=>e(a,t,r)),o.params?.forEach((e,r)=>e(a,t,r))}function Y(e,t,...r){if(e instanceof s.ModelService)return"function"==typeof e[t]?e[t](...r):e.statement(t,...r);if("function"==typeof e[t])return e[t](...r);throw Error(`Persistence method "${t}" not found on ${e?.constructor?.name}`)}function J(e){return async function(t,r){const o=this.log.for(e);try{o.debug(`Invoking persistence method "${e}" given parameters: ${JSON.stringify(t.valuesInOrder)}`);const{direction:a,limit:s,offset:i}=r;return await Y(this.persistence(),e,...t.valuesInOrder,a,s,i)}catch(t){throw o.error(`Custom query "${e}" failed`,t),t}}}function X(e,t,r){return Object.defineProperty(e.prototype||e,t,{value:r,writable:!1}),Object.getOwnPropertyDescriptor(e.prototype||e,t)}class W extends s.Service{constructor(e,t){super(t),this.clientContext=e}logCtx(e,t,r=!1,o){const a=this.clientContext.ctx;let i;e=e.filter(e=>void 0!==e),o&&(o.headers||o.ip)&&(i=o,o={});const n=s.ContextualLoggedClass.logCtx.call(this,t,o||{},r,...e,a);return this.bindLoggerToRequest(n,i)}bindLoggerToRequest(e,t){const r=this;function o(e,t){return e.log=((e,t)=>{const o=(e=>{if(!e)return;const t=e.headers,r=ee(t?.["x-forwarded-for"])??ee(t?.["x-real-ip"])??ee(t?.["X-Forwarded-For"])??ee(t?.["X-Real-IP"]);if(r)return r;if("string"==typeof e.ip&&e.ip.length)return e.ip;const o=e.socket||e.connection;return o&&"string"==typeof o.remoteAddress&&o.remoteAddress.length?o.remoteAddress:void 0})(t??r.clientContext.request);if(!o)return e;const a={ip:o};return e.for(a)})(e.log,t),e}return(e=>"object"==typeof e&&null!==e&&"function"==typeof e.then)(e)?e.then(e=>o(e,t)):o(e,t)}}class Z extends W{persistence(e){if(!this._persistence)try{this._persistence=s.Service.get(this.class)}catch(e){try{this._persistence=s.ModelService.getService(this.class)}catch(e){this._persistence=s.Repository.forModel(this.class)}}const t=this.clientContext.request[j]||{};return e&&this.clientContext.put(t),e?this._persistence instanceof s.Repository?this._persistence.override(t):this._persistence.for(t):this._persistence}constructor(e,t){super(e,t)}logCtx(e,t,r=!1,o){const a=this.clientContext.ctx;let i;o&&(o.headers||o.ip)&&(i=o,o={});try{o=a.get("overrides")}catch(e){}const n=this.persistence(a);let c,p;return n instanceof s.ModelService?c=n.repo._adapter:n instanceof s.Repository?c=n._adapter:n.context&&(c=n),r?c.logCtx(e,t,!0,o).then(e=>this.bindLoggerToRequest(e,i)):(p=c.logCtx(e,t,!1,o),this.bindLoggerToRequest(p,i))}}function ee(e){if(e)return(Array.isArray(e)?e[0]:e).split(",").map(e=>e.trim()).filter(Boolean)[0]}const te=new Map;function re(e,r){if(!s.TransactionOperationKeys.includes(e))return r;const o=(e=>(te.has(e)||te.set(e,new WeakMap),te.get(e)))(e),i=o.get(r);if(i)return i;const n=[c.OperationKeys.UPDATE,c.BulkCrudOperationKeys.UPDATE_ALL].includes(e);class p{}o.set(r,p),Object.defineProperty(p,"name",{value:`${l.toPascalCase(r.name)}${l.toPascalCase(e)}DTO`});const d=(()=>{try{return a.Model.pk(r)}catch{return}})(),u=d?a.Model.pkProps(r):void 0,h=d?Reflect.getMetadata("design:type",r.prototype,d):void 0,m=h===Number||h===BigInt,f=!!u?.generated||!!d&&(a.Model.generatedBySequence(r,d)||se(r,d)||m),y=Array.from(new Set(t.Metadata.properties(r)||[])),g=new Set(a.Model.relations(r)||[]),_=[];for(const e of y)e&&(g.has(e)||e===d&&!n&&f||e!==d&&se(r,e)||_.push(e));for(const e of _){const t=ie(r,e),o=!!t?.[a.ValidationKeys.REQUIRED],s=ne(r,e)??Reflect.getMetadata("design:type",r.prototype,e),i={required:o};s&&(i.type=s),v(i)(p.prototype,e);const n=Reflect.getMetadata("design:type",r.prototype,e)??s;void 0!==n&&Reflect.defineMetadata("design:type",n,p.prototype,e),Object.defineProperty(p.prototype,e,{value:void 0,writable:!0,enumerable:!0,configurable:!0})}for(const o of g){const s=t.Metadata.relations(r,o);if(!s)throw new c.InternalError(`Metadata for relation ${o} not found`);let i=s.class;if("function"!=typeof i||i.name||(i=i()),!i||"function"!=typeof i)throw new c.InternalError(`Type for relation ${o} not found`);if(!a.Model.get(i.name))continue;const d=t.Metadata.validationFor(r,o),l=!!d?.[a.ValidationKeys.LIST],u=!!d?.[a.ValidationKeys.REQUIRED],h=re(e,i);n?ae(p,o,i,h,l,u):oe(p,o,h,l,u)}return p}function oe(e,t,r,o,a){v({type:r,required:a,isArray:o})(e.prototype,t),Reflect.defineMetadata("design:type",o?Array:r,e.prototype,t),Object.defineProperty(e.prototype,t,{value:void 0,writable:!0,enumerable:!0,configurable:!0})}function ae(e,t,r,o,s,i){const n=Reflect.getMetadata(b.API_EXTRA_MODELS,e)||[];n.includes(o)||Reflect.defineMetadata(b.API_EXTRA_MODELS,[...n,o],e);const c="#/components/schemas/"+o.name,p=(e=>{try{const t=a.Model.pkProps(e),r=t?.type;return r===Number||r===BigInt?"integer":"string"}catch{return"string"}})(r),d=[{$ref:c},{type:p}];v(s?{type:"array",required:i,oneOf:d}:{type:Object,required:i,oneOf:d})(e.prototype,t),Reflect.defineMetadata("design:type",s?Array:Object,e.prototype,t),Object.defineProperty(e.prototype,t,{value:void 0,writable:!0,enumerable:!0,configurable:!0})}function se(e,t){let r=e;for(;r&&r!==Object&&r!==Function;){if(a.Model.generated(r,t))return!0;r=Object.getPrototypeOf(r)}return!1}function ie(e,r){let o=e;for(;o&&o!==Object&&o!==Function;){const e=t.Metadata.validationFor(o,r);if(e)return e;o=Object.getPrototypeOf(o)}}function ne(e,r){let o=e;for(;o&&o!==Object&&o!==Function;){const e=t.Metadata.type(o,r);if(e)return e;o=Object.getPrototypeOf(o)}}s.Adapter.transformerFor=(e=>{const r="string"==typeof e?e:e.alias;return t.Metadata.innerGet(Symbol.for("transformers"),r)}).bind(s.Adapter),s.Adapter.flavoursToTransform=(()=>{const e=t.Metadata.innerGet(Symbol.for("transformers"));if(e)return Object.keys(e)}).bind(s.Adapter),s.Context.prototype.toResponse=function(e){const t=this.pending();return t&&e.header("x-pending-task",JSON.stringify(t)),e};const ce=a.ModelBuilder.prototype;if(ce.decorateClass||(ce.decorateClass=function(e){return this._classDecorators||(this._classDecorators=[]),this._classDecorators.push(e),this}),ce.Auth=function(e){return this.decorateClass(U(e))},!ce.__hasClassDecoratorSupport){const e=ce.build;ce.build=function(){let t=e.call(this);const r=this._classDecorators;if(r?.length)for(const e of r){const r=e(t);r&&(t=r)}return t},ce.__hasClassDecoratorSupport=!0}class pe{static{this.log=l.Logging.for(pe.name)}static getPersistence(e){try{return s.Service.get(e)}catch(t){try{return s.ModelService.getService(e)}catch(t){return s.Repository.forModel(e)}}}static createQueryRoutesFromRepository(e,r=s.PersistenceKeys.QUERY){const o=pe.log.for(pe.createQueryRoutesFromRepository),a=e instanceof s.ModelService?e.repo:e,i=a.class,n=t.Metadata.get(a.constructor,t.Metadata.key(s.PersistenceKeys.QUERY))??{},c=t.Metadata.get(e.constructor,t.Metadata.key(k))??{};class p extends Z{get class(){throw Error("Method not implemented.")}constructor(e,t){super(e,t)}}for(const[e,t]of Object.entries(c)){const r=[t.path.replace(/^\/+|\/+$/g,"")].filter(e=>e&&e.trim()).join("/"),a=J(e);if(!a){const t=`Invalid or missing handler for model ${i.name} on decorated method ${e}`;throw o.error(t),Error(t)}const s=X(p,e,a);s&&V(p,e,s,Q(e,r,t.httpMethod))}for(const[e,t]of Object.entries(n)){const o=[r,e,...(t.fields??[]).map(e=>":"+e)].filter(e=>e&&e.trim()).join("/"),a=X(p,e,J(e));a&&V(p,e,a,Q(e,o,"GET",!0))}return p}static create(t){const r=pe.log.for(pe.create),i=a.Model.tableName(t),d=l.toKebabCase(i),u=t.name,h=pe.getPersistence(t),{description:m,getPK:f,apiProperties:y,path:g}=pe.getRouteParametersFromModel(t);r.debug("Creating controller for model: "+u);const _=pe.createQueryRoutesFromRepository(h);let A=class extends _{static get class(){return t}get class(){return t}constructor(e){super(e),this.pk=a.Model.pk(t),r.info(`Registering dynamic controller for model: ${this.class.name} route: /${d}`)}async listBy(e,t){const{ctx:r}=(await this.logCtx([],s.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return this.persistence(r).listBy(e,t.direction,r)}async paginateBy(e,t){const{ctx:r}=(await this.logCtx([],s.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);return this.persistence(r).paginateBy(e,t.direction,t,r)}async find(e,t){const{ctx:r}=(await this.logCtx([],s.PreparedStatementKeys.FIND,!0)).for(this.find),o=t.direction??s.OrderDirection.ASC;return Y(this.persistence(r),this.find.name,e,o,r)}async page(e,t){const{ctx:r}=(await this.logCtx([],s.PreparedStatementKeys.PAGE,!0)).for(this.page),{direction:o=s.OrderDirection.ASC,limit:a,offset:i,bookmark:n}=t,c={offset:i??1,limit:a??10,bookmark:n};return Y(this.persistence(r),this.page.name,e,o,c,r)}async findOneBy(e,t){const{ctx:r}=(await this.logCtx([],s.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);return this.persistence(r).findOneBy(e,t,r)}async findBy(e,t,r){const{ctx:o}=(await this.logCtx([],s.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return this.persistence(o).for(o.toOverrides()).findBy(e,t,o)}async statement(e,t,r){const{ctx:o}=(await this.logCtx([],s.PersistenceKeys.STATEMENT,!0)).for(this.statement),{direction:a,offset:i,limit:n,bookmark:c}=r,p=(t=t.map(e=>("string"==typeof e?parseInt(e):e)||e)).length>1?t[1]:void 0,d=a??p;switch(d&&t.length>1&&(t[1]=d),e){case s.PreparedStatementKeys.FIND:case s.PreparedStatementKeys.FIND_BY:break;case s.PreparedStatementKeys.LIST_BY:t.push(a);break;case s.PreparedStatementKeys.PAGE:case s.PreparedStatementKeys.PAGE_BY:t=[t[0],d,{limit:n,offset:i,bookmark:c}];case s.PreparedStatementKeys.FIND_ONE_BY:case s.PreparedStatementKeys.COUNT_OF:case s.PreparedStatementKeys.MAX_OF:case s.PreparedStatementKeys.MIN_OF:case s.PreparedStatementKeys.AVG_OF:case s.PreparedStatementKeys.SUM_OF:case s.PreparedStatementKeys.DISTINCT_OF:case s.PreparedStatementKeys.GROUP_OF:}return this.persistence(o).statement(e,...t,o)}async createAll(e,r){const{ctx:o,log:a}=(await this.logCtx([],c.BulkCrudOperationKeys.CREATE_ALL,!0)).for(this.createAll);let s;a.verbose("creating new "+u);try{s=await this.persistence(o).createAll(e.map(e=>new t(e)),o)}catch(e){throw a.error("Failed to create new "+u,e),e}return a.info(`created new ${u} with id ${s[this.pk]}`),o.toResponse(r),s}async create(e,t){const{ctx:r,log:o}=(await this.logCtx([],c.OperationKeys.CREATE,!0)).for(this.create);let a;o.verbose("creating new "+u);try{const t=this.persistence(r);a=await t.create(e,r)}catch(e){throw o.error("Failed to create new "+u,e),e}return o.info(`created new ${u} with id ${a[this.pk]}`),r.toResponse(t),a}async readAll(e){const{ctx:t,log:r}=(await this.logCtx([],c.BulkCrudOperationKeys.READ_ALL,!0)).for(this.readAll);let o;try{r.debug(`reading ${e.length} ${u}: ${e}`);const a=this.persistence(t);o=await a.readAll(e,t)}catch(t){throw r.error(`Failed to ${u} with id ${e}`,t),t}return r.info(`read ${o.length} ${u}`),o}async read(e){const{ctx:t,log:r}=(await this.logCtx([],c.OperationKeys.READ,!0)).for(this.read),o=f(...e.valuesInOrder);if(void 0===o)throw new c.ValidationError(`No ${this.pk} provided`);let a;try{r.debug(`reading ${u} with ${this.pk} ${o}`);const e=this.persistence(t);a=await e.read(o,t)}catch(e){throw r.error(`Failed to read ${u} with id ${o}`,e),e}return r.info(`read ${u} with id ${a[this.pk]}`),a}async updateAll(e,t){const{ctx:r,log:o}=(await this.logCtx([],c.BulkCrudOperationKeys.UPDATE_ALL,!0)).for(this.updateAll);let a;try{o.info(`updating ${e.length} ${u}`),a=await this.persistence(r).updateAll(e,r)}catch(e){throw o.error(e),e}return r.toResponse(t),a}async update(e,r,o){const{ctx:a,log:s}=(await this.logCtx([],c.OperationKeys.UPDATE,!0)).for(this.update),i=f(...e.valuesInOrder);if(void 0===i)throw new c.ValidationError(`No ${this.pk} provided`);let n;try{s.info(`updating ${u} with ${this.pk} ${i}`);const e=JSON.parse(JSON.stringify(r)),o=this.persistence(a);n=await o.update(new t({...e,[this.pk]:i}),a)}catch(e){throw s.error(e),e}return a.toResponse(o),n}async deleteAll(e,t){const{ctx:r,log:o}=(await this.logCtx([],c.BulkCrudOperationKeys.DELETE_ALL,!0)).for(this.deleteAll);let a;try{o.debug(`deleting ${e.length} ${u}: ${e}`),a=await this.persistence(r).deleteAll(e,r)}catch(t){throw o.error(`Failed to delete ${u} with id ${e}`,t),t}return o.info(`deleted ${a.length} ${u}`),r.toResponse(t),a}async delete(e,t){const{ctx:r,log:o}=(await this.logCtx([],c.OperationKeys.DELETE,!0)).for(this.delete),a=f(...e.valuesInOrder);if(void 0===a)throw new c.ValidationError(`No ${this.pk} provided`);let s;try{o.debug(`deleting ${u} with ${this.pk} ${a}`),s=await this.persistence(r).delete(a,r)}catch(e){throw o.error(`Failed to delete ${u} with id ${a}`,e),e}return o.info(`deleted ${u} with id ${a}`),r.toResponse(t),s}};return p.__decorate([S(t,"GET","listBy/:key"),n.ApiOperation({summary:`Retrieve ${u} records by query.`}),n.ApiParam({name:"key",description:"the model key to sort by"}),n.ApiQuery({name:"direction",required:!0,enum:s.OrderDirection}),n.ApiOkResponse({description:u+" listed successfully."}),p.__param(0,o.Param("key")),p.__param(1,M()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"listBy",null),p.__decorate([S(t,"GET","paginateBy/:key/:page"),n.ApiOperation({summary:`Retrieve ${u} records by query.`}),n.ApiParam({name:"key",description:"the model key to sort by"}),n.ApiParam({name:"page",description:"the page to retrieve or the bookmark"}),n.ApiQuery({name:"direction",required:!0,enum:s.OrderDirection,description:"the sort order"}),n.ApiQuery({name:"limit",required:!0,description:"the page size"}),n.ApiQuery({name:"offset",description:"the bookmark when necessary"}),n.ApiOkResponse({description:u+" listed paginated."}),p.__param(0,o.Param("key")),p.__param(1,M()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"paginateBy",null),p.__decorate([S(t,"GET","find/:value"),n.ApiOperation({summary:`Find ${u} records using the default query attributes.`}),n.ApiParam({name:"value",description:"The string to match against the default query attributes"}),n.ApiQuery({name:"direction",required:!1,enum:s.OrderDirection,description:"the sort order for the matching results"}),n.ApiOkResponse({description:u+" records matching the provided prefix."}),p.__param(0,o.Param("value")),p.__param(1,M()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"find",null),p.__decorate([S(t,"GET","page/:value"),n.ApiOperation({summary:`Page ${u} records using the default query attributes.`}),n.ApiParam({name:"value",description:"The string to match against the default query attributes"}),n.ApiQuery({name:"direction",required:!1,enum:s.OrderDirection,description:"the sort order for the paged results"}),n.ApiQuery({name:"limit",required:!1,description:"page size"}),n.ApiQuery({name:"offset",required:!1,description:"page number"}),n.ApiQuery({name:"bookmark",required:!1,description:"bookmark for cursor pagination"}),n.ApiOkResponse({description:u+" records paged by the provided prefix."}),p.__param(0,o.Param("value")),p.__param(1,M()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"page",null),p.__decorate([S(t,"GET","findOneBy/:key"),n.ApiOperation({summary:`Retrieve ${u} records by query.`}),n.ApiParam({name:"key",description:"the model key to sort by"}),n.ApiOkResponse({description:u+" listed found."}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,o.Param("key")),p.__param(1,o.Param("value")),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"findOneBy",null),p.__decorate([S(t,"GET","findBy/:key/:value"),n.ApiOperation({summary:`Retrieve ${u} records by query.`}),n.ApiParam({name:"key",description:"the model key to compare"}),n.ApiParam({name:"value",description:"the value to match"}),n.ApiQuery({name:"direction",required:!0,enum:s.OrderDirection,description:"the sort order when applicable"}),n.ApiOkResponse({description:u+" listed found."}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,o.Param("key")),p.__param(1,o.Param("value")),p.__param(2,M()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"findBy",null),p.__decorate([S(t,"GET","statement/:method/*args"),n.ApiOperation({summary:`Executes a prepared statement on ${u}.`}),n.ApiParam({name:"method",description:"the prepared statement to execute"}),n.ApiParam({name:"args",description:"concatenated list of arguments the prepared statement can accept"}),n.ApiQuery({name:"direction",required:!0,enum:s.OrderDirection,description:"the sort order when applicable"}),n.ApiQuery({name:"limit",required:!0,description:"limit or page size when applicable"}),n.ApiQuery({name:"offset",required:!0,description:"offset or bookmark when applicable"}),n.ApiOkResponse({description:u+" listed found."}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,o.Param("method")),p.__param(1,o.Param("args")),p.__param(2,M()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Array,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"statement",null),p.__decorate([S(t,"POST","bulk"),n.ApiOperation({summary:`Create a new ${u}.`}),n.ApiBody({description:"Payload for "+u,schema:{type:"array",items:{$ref:n.getSchemaPath(t)}}}),n.ApiCreatedResponse({description:u+" created successfully.",schema:{type:"array",items:{$ref:n.getSchemaPath(t)}}}),n.ApiBadRequestResponse({description:"Payload validation failed."}),n.ApiUnprocessableEntityResponse({description:"Repository rejected the provided payload."}),p.__param(0,C()),p.__param(1,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Array,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"createAll",null),p.__decorate([S(t,"POST"),n.ApiOperation({summary:`Create a new ${u}.`}),n.ApiBody({description:"Payload for "+u,type:re(c.OperationKeys.CREATE,t)}),n.ApiCreatedResponse({description:u+" created successfully.",schema:{$ref:n.getSchemaPath(t)}}),n.ApiBadRequestResponse({description:"Payload validation failed."}),n.ApiUnprocessableEntityResponse({description:"Repository rejected the provided payload."}),p.__param(0,C()),p.__param(1,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Object,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"create",null),p.__decorate([S(t,"GET","bulk"),n.ApiOperation({summary:`Retrieve a ${u} record by id.`}),n.ApiQuery({name:"ids",required:!0,type:"array"}),n.ApiOkResponse({description:u+" retrieved successfully.",schema:{type:"array",items:{$ref:n.getSchemaPath(t)}}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,o.Query("ids")),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Array]),p.__metadata("design:returntype",Promise)],A.prototype,"readAll",null),p.__decorate([S(t,"GET",g),T(y),n.ApiOperation({summary:`Retrieve a ${u} record by id.`}),n.ApiOkResponse({description:u+" retrieved successfully.",schema:{$ref:n.getSchemaPath(t)}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,I(y)),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Object]),p.__metadata("design:returntype",Promise)],A.prototype,"read",null),p.__decorate([S(t,"PUT","bulk"),T(y),n.ApiOperation({summary:`Replace an existing ${u} record with a new payload.`}),n.ApiBody({description:"Payload for replace a existing record of "+u,schema:{type:"array",$ref:n.getSchemaPath(re(c.OperationKeys.UPDATE,t))}}),n.ApiOkResponse({description:u+" updated successfully.",schema:{type:"array",items:{$ref:n.getSchemaPath(t)}}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),n.ApiBadRequestResponse({description:"Payload validation failed."}),p.__param(0,C()),p.__param(1,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Array,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"updateAll",null),p.__decorate([S(t,"PUT",g),T(y),n.ApiOperation({summary:`Replace an existing ${u} record with a new payload.`}),n.ApiBody({description:"Payload for replace a existing record of "+u,type:re(c.OperationKeys.UPDATE,t)}),n.ApiOkResponse({description:u+" updated successfully.",schema:{$ref:n.getSchemaPath(t)}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),n.ApiBadRequestResponse({description:"Payload validation failed."}),p.__param(0,I(y)),p.__param(1,C()),p.__param(2,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Object,Object,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"update",null),p.__decorate([S(t,"DELETE","bulk"),T(y),n.ApiOperation({summary:`Retrieve a ${u} record by id.`}),n.ApiQuery({name:"ids",required:!0,type:"array"}),n.ApiOkResponse({description:u+" deleted successfully.",schema:{type:"array",items:{$ref:n.getSchemaPath(t)}}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,o.Query("ids")),p.__param(1,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Array,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"deleteAll",null),p.__decorate([S(t,"DELETE",g),T(y),n.ApiOperation({summary:`Delete a ${u} record by id.`}),n.ApiOkResponse({description:u+" deleted successfully.",schema:{$ref:n.getSchemaPath(t)}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,I(y)),p.__param(1,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Object,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"delete",null),A=p.__decorate([o.Controller(d),n.ApiTags(u),n.ApiExtraModels(t),U(t),p.__metadata("design:paramtypes",[e.DecafRequestContext])],A),A}static getRouteParametersFromModel(e){const r=a.Model.pk(e),o=t.Metadata.get(e,t.Metadata.key(c.DBKeys.COMPOSED,r)),s=o?.args??[],i=Array.isArray(s)&&s.length>0?Array.from(new Set([...s])):Array.from(new Set([r])),n=t.Metadata.description(e);return{path:":"+i.join("/:"),description:n,apiProperties:i.map(r=>({name:r,description:t.Metadata.description(e,r),required:!0,type:String})),getPK:(...e)=>o?.separator?e.join(o.separator):e.join("")}}}function de(e){var t;let r=class{static{t=this}static{this.log=l.Logging.for(t.name).for(e)}static createModelServices(e){return e.map(e=>({provide:e.name+"Service",useFactory:()=>s.ModelService.forModel(e)}))}static forRoot(e,r={}){const o=this.log.for(this.forRoot);o.info("Generating controllers for flavour...");const a=s.Adapter.models(e);let i=[];r.autoServices&&(o.info("Auto-services enabled. Initializing service generation."),i=this.createModelServices(a),o.info(`Auto-services completed. ${i.length} services initialized.`));const n=a.map(pe.create);return o.info(`Generated ${n.length} controllers`),{module:t,controllers:n,providers:[...i]}}};return r=t=p.__decorate([o.Module({})],r),Object.assign(r,"name",{value:"DecafModule"+e}),r}t.Decoration.for(r.InjectablesKeys.INJECTABLE).extend({decorator:(e,t)=>(t=t||("object"==typeof e?Object.assign(e,r.DefaultInjectablesConfig):r.DefaultInjectablesConfig),o.Injectable({scope:t.singleton?o.Scope.DEFAULT:o.Scope.REQUEST,durable:!t.singleton||void 0}))}).apply(),t.Decoration.for(r.InjectablesKeys.INJECT).extend({decorator:(e,t)=>(t,r,a)=>o.Inject(e||t)(t,r,a)}).apply(),t.Decoration.for(a.ValidationKeys.REQUIRED).extend(v({required:!0})).apply(),t.Decoration.for(a.ValidationKeys.MAX).extend({decorator:e=>v({maximum:e,required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.MIN).extend({decorator:e=>v({minimum:e,required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.MAX_LENGTH).extend({decorator:e=>v({maxLength:e,required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.MIN_LENGTH).extend({decorator:e=>v({minLength:e,required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.TYPE).extend({decorator:e=>(t,r)=>("function"!=typeof(e=Array.isArray(e)?e[0]:e)||e.name||(e=e()),v({type:e,required:!1})(t,r))}).apply(),t.Decoration.for(a.ValidationKeys.DATE).extend({decorator:e=>v({type:String,format:"date-time",required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.ENUM).extend({decorator:e=>v({enum:Array.isArray(e)?e:Object.values(e),required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.PATTERN).extend({decorator:e=>v({pattern:"string"==typeof e?e:e.source,required:!1})}).apply(),t.Decoration.for(s.PersistenceKeys.COLUMN).extend({decorator:e=>v({name:e,required:!1})}).apply(),t.Decoration.for(t.DecorationKeys.DESCRIPTION).extend({decorator:e=>v({description:e,required:!1})}).apply(),t.Decoration.for(s.PersistenceKeys.AUTH).extend({decorator:U}).apply();class le extends s.ForbiddenError{constructor(e){super(e,le.name)}}class ue extends c.BaseError{constructor(e){super(ue.name,e,429)}}e.DecafExceptionFilter=class{catch(e,t){const r=t.switchToHttp(),a=r.getResponse(),i=r.getRequest(),n="production"===l.LoggedEnvironment.env;let p;e instanceof o.NotFoundException||e instanceof s.UnsupportedError?p=(e=new o.NotAcceptableException(e.message)).getStatus():e instanceof c.BaseError||(e=429===e.status?new ue(e.message):new c.InternalError(e.message)),a.status(e.code||p).json({status:e.code||p,error:n?e.name:e.message,timestamp:(new Date).toISOString(),path:i.url,method:i.method})}},e.DecafExceptionFilter=p.__decorate([o.Catch()],e.DecafExceptionFilter);const he={path:"docs",auth:{type:"http",scheme:"bearer",bearerFormat:"JWT",name:"Authorization",description:"Enter JWT token",in:"header"},topbarBgColor:"#000000"};class me{constructor(e){this.options={...e}}customCSS(){let e="";return this.options.topbarIconPath&&(e+=`.topbar-wrapper { content: url('data:image/png;base64,${this.b64(this.options.topbarIconPath)}'); width: 200px; height: auto; }\n`),e+`\n .topbar-wrapper svg { visibility: hidden; }\n .swagger-ui .topbar { background-color: ${this.options.topbarBgColor||he.topbarBgColor}; }\n `}getCustomOptions(){const e={};return this.options.faviconPath&&(e.customfavIcon=this.b64(this.options.faviconPath,!0)),{customSiteTitle:this.options.title,...e,customCss:this.customCSS(),swaggerOptions:{persistAuthorization:this.options.persistAuthorization}}}b64(e,t=!1){const r=_.join(this.options.assetsPath||"",e),o=h.readFileSync(r,{encoding:"base64"});return t?"data:image/png;base64,"+o:o}}class fe{constructor(e,t){this.app=e,this.options=t}createDocument(){const e=this.options.path?this.options.description+""+`<br><br><a href="${this.options.openApiJsonPath}">OpenAPI JSON Spec</a> | `+`<a href="${this.options.openApiYamlPath}">OpenAPI YAML Spec</a>`:this.options.description,t=(new n.DocumentBuilder).setTitle(this.options.title).setDescription(e).setVersion(this.options.version||"0.0.1").addBearerAuth(this.options.auth||he.auth).build();return n.SwaggerModule.createDocument(this.app,t,{extraModels:this.options.extraModels||[]})}registerOpenApiRoute(e,t,r){if(!e)return;const o=this.app.getHttpAdapter();e=e.startsWith("/")?e:"/"+e,o.get(e,(e,a)=>{o.reply(a,r(),200,{"Content-Type":t})})}setupSwagger(){const e=this.createDocument(),t=new me({title:this.options.title,path:this.options.path||he.path,persistAuthorization:this.options.persistAuthorization??!0,assetsPath:this.options.assetsPath,faviconPath:this.options.faviconFilePath,topbarIconPath:this.options.topbarIconFilePath,topbarBgColor:this.options.topbarBgColor});n.SwaggerModule.setup(this.options.path||he.path,this.app,e,{...t.getCustomOptions(),jsonDocumentUrl:this.options.openApiJsonPath?""+this.options.openApiJsonPath:void 0,yamlDocumentUrl:this.options.openApiYamlPath?""+this.options.openApiYamlPath:void 0}),this.registerOpenApiRoute(this.options.openApiJsonPath,"application/json",()=>e),this.registerOpenApiRoute(this.options.openApiYamlPath,"application/x-yaml",()=>f.stringify(e))}}var ye,ge;function _e(e){return r=>(t.Metadata.set("transformers",e,r),"function"==typeof r?t.metadata("transformers",e)(r):r)}e.DecafRequestHandlerInterceptor=ye=class{constructor(e,t){this.requestContext=e,this.executor=t}async contextualize(e){const t={headers:e.headers,overrides:{}},r=s.Adapter.flavoursToTransform();if(r)for(const o of r)try{const r=s.Adapter.transformerFor(o),a=await r.from(e);Object.assign(t.overrides,a)}catch(e){throw new c.InternalError("Failed to contextualize request: "+e)}return(new s.Context).accumulate(Object.assign({},s.DefaultAdapterFlags,{logger:l.Logging.get(),timestamp:new Date},t))}async intercept(e,t){const r=e.switchToHttp().getRequest(),o=e.switchToHttp().getResponse(),a=l.Logging.for(ye).for(this.intercept);a.debug(`CONTEXT ${this.requestContext.uuid} - request: ${r.method} ${r.url}`);const s=await this.contextualize(r);return a.debug(`CONTEXT ${this.requestContext.uuid} contextualized - request: ${r.method} ${r.url}`),this.requestContext.applyCtx(s),a.debug(`CONTEXT ${this.requestContext.uuid} applied - request: ${r.method} ${r.url}`),await this.executor.exec(r,o),a.debug(`CONTEXT ${this.requestContext.uuid} executors finished - request: ${r.method} ${r.url}`),t.handle()}},e.DecafRequestHandlerInterceptor=ye=p.__decorate([o.Injectable({scope:o.Scope.REQUEST}),p.__metadata("design:paramtypes",[e.DecafRequestContext,e.DecafHandlerExecutor])],e.DecafRequestHandlerInterceptor),e.DecafCoreModule=class{static{ge=this}static get persistence(){if(!this._persistence)throw new c.InternalError("Persistence service not initialized");return this._persistence}static get log(){return this._logger||(this._logger=l.Logging.for(ge)),this._logger}constructor(e,t){this.options=e,this.moduleRef=t}static forRoot(t){const r=this.log.for(this.forRoot);return{module:ge,providers:[{provide:q,useValue:t},{provide:F,useValue:this.persistence.client},{provide:N,useFactory:()=>t.handlers?.map(e=>(r.info("Registered request handler: "+e.name),new e))??[]},e.AuthInterceptor,{provide:d.APP_INTERCEPTOR,useExisting:e.AuthInterceptor},e.DecafRequestContext,e.DecafHandlerExecutor,{provide:d.APP_INTERCEPTOR,useClass:e.DecafRequestHandlerInterceptor}],exports:[q,F,N,e.DecafRequestContext,e.DecafHandlerExecutor]}}static async bootPersistence(e){const t=this.log.for(this.bootPersistence);if(!this._persistence){const r=e.conf.map(([e,t,...r])=>r.pop()?[e,t,...r]:[e,t]);this._persistence=new s.PersistenceService,await this._persistence.boot(r);const o=this._persistence.client;for(let t=0;t<o.length;t++){const r=e.conf[t];let a=r.slice(2,r.length).pop();if(!a||!a.from){const e=s.Adapter.transformerFor(o[t].flavour);if(!e)throw new c.InternalError(`No transformer found for flavour ${o[t].flavour}. you should either @requestToContextTransformer or provide a transformer in the config`);try{a=e.from?e:new e}catch(e){throw new c.InternalError(`Failed to boot transformer for ${o[t].flavour}: ${e}`)}}_e(o[t].flavour)(a)}if(t.info("persistence layer created successfully!"),e.initialization)try{await e.initialization()}catch(e){throw new c.InternalError("Failed to initialize application: "+e)}}return this.persistence.client}async onApplicationShutdown(){const e=ge.log.for(this.onApplicationShutdown),t=this.moduleRef.get(F);for(const r of t)try{r&&(e.info("Shutting down "+r.toString()),await r.shutdown())}catch(t){e.error("Failed to shutdown application",t)}}},e.DecafCoreModule=ge=p.__decorate([o.Global(),o.Module({}),p.__param(0,o.Inject(q)),p.__metadata("design:paramtypes",[Object,d.ModuleRef])],e.DecafCoreModule);const Ae=Symbol("LISTENING_ADAPTERS_FLAVOURS");var be,Ee,Pe;e.EventsController=be=class extends W{constructor(e,t){super(e,be.name),this.adapters=t.map(e=>s.Adapter.get(e))}listen(){const e=l.Logging.for(be.name),t=new u.Observable(t=>{const r=("B-"+Math.random().toString(36).slice(2,8)).toUpperCase();e.info(`Creating SSE observer: ${r} for client ${this.clientContext.uuid}`);const o=new class{constructor(){this.observerId=r}refresh(...r){return e.debug(`SSE observer ${this.observerId} received refresh event`),Promise.resolve().then(()=>{const o=(e=>{const[t,r,o,a]=e;return[t?.name??t,r,o,Array.isArray(a)?a.map(e=>{try{return"function"==typeof e.serialize?e.serialize():"string"==typeof e?e:JSON.stringify(e)}catch(e){return}}):a&&"function"==typeof a.serialize?a.serialize():"string"==typeof a?a:JSON.stringify(a)]})(r);t.next({type:"message",data:o}),e.debug(`SSE observer ${this.observerId} event pushed to client`)})}};e.verbose(`Registering observer ${r} across ${this.adapters.length} adapter(s)`);for(const t of this.adapters){const a=t?.constructor?.name??"UnknownAdapter";try{e.debug(`Registering observer ${r} in adapter ${a}`),t.observe(o)}catch(t){e.debug(`Failed to register observer ${r} in adapter ${a}: ${t?.message||t}`),e.error(t)}}return()=>{e.debug("Cleaning up SSE observer "+r);for(const t of this.adapters){const a=t?.constructor?.name??"UnknownAdapter";try{e.debug(`Unregistering observer ${r} from adapter ${a}`),t.unObserve(o)}catch(t){e.debug(`Failed during cleanup of observer ${r} in adapter ${a}: ${t?.message||t}`),e.error(t)}}}}),r=u.interval(15e3).pipe(y.tap(()=>{e.debug("Sending heartbeat")}),y.map(()=>({type:"heartbeat",data:{ts:(new Date).toISOString()}})));return u.merge(t,r)}listenForModel(e){const t=l.Logging.for(be.name);return new u.Observable(e=>{const r=new class{refresh(...t){return Promise.resolve().then(()=>{e.next({data:t})})}};try{for(const e of this.adapters)e.observe(r)}catch(t){e.error("Failed to observe event: "+(t.message||t))}return()=>{try{for(const e of this.adapters)e.unObserve(r)}catch(e){t.error(e)}}})}},p.__decorate([o.Sse(),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[]),p.__metadata("design:returntype",u.Observable)],e.EventsController.prototype,"listen",null),p.__decorate([o.Sse("/:model"),p.__param(0,o.Query("model")),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String]),p.__metadata("design:returntype",u.Observable)],e.EventsController.prototype,"listenForModel",null),e.EventsController=be=p.__decorate([o.Controller(),p.__param(1,o.Inject(Ae)),p.__metadata("design:paramtypes",[e.DecafRequestContext,Array])],e.EventsController),e.DecafStreamModule=Ee=class{static forFlavours(t,r="events"){return{module:Ee,controllers:[e.EventsController],imports:[d.RouterModule.register([{path:r.replace(/^\//,""),module:Ee}])],providers:[e.DecafRequestContext,{provide:Ae,useValue:t??[]}]}}},e.DecafStreamModule=Ee=p.__decorate([o.Module({})],e.DecafStreamModule),e.DecafModule=Pe=class{static async forRootAsync(t){const{autoControllers:r,autoServices:o}=t,a=(await e.DecafCoreModule.bootPersistence(t)).map(e=>e.flavour),s=[e.DecafCoreModule.forRoot(t)];return r&&a.forEach(e=>{s.push(de(e).forRoot(e,{autoServices:o}))}),t.observerOptions?.enableObserverEvents&&s.push(e.DecafStreamModule.forFlavours(t.observerOptions.observerFlavours||a)),{module:Pe,imports:s}}},e.DecafModule=Pe=p.__decorate([o.Module({})],e.DecafModule);const Oe="##VERSION##",Re="##PACKAGE##";t.Metadata.allowReregistration(!0),t.Metadata.registerLibrary(Re,Oe),t.Metadata.allowReregistration(!1),e.AUTH_HANDLER=L,e.AUTH_META_KEY=K,e.ApiOperationFromModel=S,e.ApiParamsFromModel=T,e.ApiProperty=v,e.Auth=U,e.BulkApiOperationFromModel=(e,r,a)=>{const s={GET:[c.BulkCrudOperationKeys.READ_ALL,o.Get],POST:[c.BulkCrudOperationKeys.CREATE_ALL,o.Post],PUT:[c.BulkCrudOperationKeys.UPDATE_ALL,o.Put],PATCH:[c.BulkCrudOperationKeys.UPDATE_ALL,o.Patch],DELETE:[c.BulkCrudOperationKeys.DELETE_ALL,o.Delete]},[i,p]=s[r];return D(e,i)?t.apply(n.ApiExcludeEndpoint()):t.apply(p(a))},e.CorsError=le,e.DECAF_ADAPTER_ID=F,e.DECAF_ADAPTER_OPTIONS=j,e.DECAF_CONTEXT_KEY=B,e.DECAF_HANDLERS=N,e.DECAF_MODULE_OPTIONS=q,e.DECAF_ROUTE=k,e.DECORATORS=b,e.DECORATORS_PREFIX=A,e.DecafAuthHandler=H,e.DecafBody=C,e.DecafController=W,e.DecafModelController=Z,e.DecafParams=I,e.DecafQuery=M,e.DecafRoleAuthHandler=class extends H{constructor(){super()}async authorize(e,r){const o=e.switchToHttp().getRequest(),i=this.parseRequest(o);if(!i)throw new s.AuthorizationError("Unauthenticated");const n=t.Metadata.get(a.Model.get(r),s.PersistenceKeys.AUTH_ROLE);if(!n.includes(i))throw new s.AuthorizationError("Missing role: "+i);return n}},e.DtoFor=re,e.FromModelController=pe,e.HttpVerbToDecorator=$,e.NestBootstraper=class{static get logger(){return this._logger||(this._logger=new o.Logger("NestBootstrap")),this._logger}static initialize(e){return this.app=e,this}static enableLogger(e){return this._logger=e||new o.Logger("NestBootstrap"),this.app.useLogger(this._logger),this}static enableCors(e=[],t=["GET","POST","PUT","DELETE"]){const r="*"===e?"*":e.map(e=>e.trim().toLowerCase()),o={origin:(e,t)=>e?"*"===r||Array.isArray(r)&&r.includes(e.toLowerCase())?t(null,!0):void t(new le(`Origin ${e} not allowed`)):t(null,!0),credentials:!0,methods:t.join(",")};return this.app.enableCors(o),this}static useHelmet(e){try{const t=require("helmet");this.app.use(t(e)),this.logger.log("Helmet middleware enabled successfully.")}catch(e){this.logger.warn("Helmet not installed. Skipping middleware.")}return this}static setupSwagger(e){return new fe(this.app,{title:e.title,description:e.description,version:e.version,path:e.path||"api",persistAuthorization:e.persistAuthorization??!0,assetsPath:e.assetsPath,faviconFilePath:e.faviconPath,topbarIconFilePath:e.topbarIconPath,topbarBgColor:e.topbarBgColor,openApiJsonPath:e.openApiJsonPath,openApiYamlPath:e.openApiYamlPath}).setupSwagger(),this}static useGlobalPipes(...e){return e.length>0&&this.app.useGlobalPipes(...e),this}static useGlobalFilters(...t){return this.app.useGlobalFilters(...t.length>0?t:[new e.DecafExceptionFilter]),this}static useGlobalInterceptors(...e){return e.length>0&&this.app.useGlobalInterceptors(...e),this}static async start(e=Number(process.env.PORT)||3e3,t=void 0,r=!0){this.app.listen(e,t).then(async()=>{if(r){const e=await this.app.getUrl();this.logger.log("\ud83d\ude80 Application is running at: "+e)}})}},e.PACKAGE_NAME=Re,e.RequestToContextTransformer=class{},e.SwaggerBuilder=fe,e.UseDecafFilter=()=>o.UseFilters(new e.DecafExceptionFilter),e.UseDecafHeaders=()=>o.UseInterceptors(e.DecafResponseInterceptor),e.VERSION=Oe,e.createApiPropertyDecorator=w,e.createPropertyDecorator=R,e.getEnumType=O,e.getEnumValues=P,e.getModuleFor=de,e.isOperationBlocked=D,e.isUndefined=E,e.repoForModel=e=>{const t=a.Model.get(e);if(!t)throw new c.InternalError("Failed to find repository for "+e);return s.Repository.forModel(t)},e.requestToContextTransformer=_e},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/decoration"),require("@decaf-ts/injectable-decorators"),require("@nestjs/common"),require("@decaf-ts/decorator-validation"),require("@decaf-ts/core"),require("lodash"),require("@nestjs/swagger"),require("@decaf-ts/db-decorators"),require("tslib"),require("@nestjs/core"),require("@decaf-ts/logging"),require("rxjs"),require("fs"),require("path"),require("yaml"),require("rxjs/operators")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/decoration","@decaf-ts/injectable-decorators","@nestjs/common","@decaf-ts/decorator-validation","@decaf-ts/core","lodash","@nestjs/swagger","@decaf-ts/db-decorators","tslib","@nestjs/core","@decaf-ts/logging","rxjs","fs","path","yaml","rxjs/operators"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["for-nest"]={},e.decafTsDecoration,e.decafTsInjectableDecorators,e.nestjsCommon,e.decafTsDecoratorValidation,e.decafTsCore,e.lodash,e.nestjsSwagger,e.decafTsDbDecorators,e.tslib,e.nestjsCore,e.decafTsLogging,e.rxjs,e.fs,e.path,e.yaml,e.operators);
1
+ var e,t;e=this,t=function(e,t,r,o,a,s,i,n,c,p,d,l,u,h,m,f,y){"use strict";function g(e){var t=Object.create(null);return e&&Object.keys(e).forEach(r=>{if("default"!==r){var o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,o.get?o:{enumerable:!0,get:()=>e[r]})}}),t.default=e,Object.freeze(t)}var _=g(m);const A="swagger",b={API_OPERATION:A+"/apiOperation",API_RESPONSE:A+"/apiResponse",API_PRODUCES:A+"/apiProduces",API_CONSUMES:A+"/apiConsumes",API_TAGS:A+"/apiUseTags",API_CALLBACKS:A+"/apiCallbacks",API_PARAMETERS:A+"/apiParameters",API_HEADERS:A+"/apiHeaders",API_MODEL_PROPERTIES:A+"/apiModelProperties",API_MODEL_PROPERTIES_ARRAY:A+"/apiModelPropertiesArray",API_SECURITY:A+"/apiSecurity",API_EXCLUDE_ENDPOINT:A+"/apiExcludeEndpoint",API_EXCLUDE_CONTROLLER:A+"/apiExcludeController",API_EXTRA_MODELS:A+"/apiExtraModels",API_EXTENSION:A+"/apiExtension",API_SCHEMA:A+"/apiSchema",API_DEFAULT_GETTER:A+"/apiDefaultGetter",API_LINK:A+"/apiLink"},E=e=>void 0===e;function P(e){if("function"==typeof e)return P(e());if(Array.isArray(e))return e;if("object"!=typeof e)return[];const t=Object.values(e).filter(e=>"number"==typeof e).map(e=>e.toString());return Object.keys(e).filter(e=>!t.includes(e)).map(t=>e[t])}function O(e){return e.filter(i.isString).length>0?"string":"number"}function R(e,t,r=!0){return(o,a)=>{const s=Reflect.getMetadata(b.API_MODEL_PROPERTIES_ARRAY,o)||[],n=":"+a;s.includes(n)||Reflect.defineMetadata(b.API_MODEL_PROPERTIES_ARRAY,[...s,":"+a],o);const c=Reflect.getMetadata(e,o,a);if(c){const s=i.pickBy(t,i.negate(E)),n=r?{...c,...s}:{...s,...c};Reflect.defineMetadata(e,n,o,a)}else{const r=o?.constructor?._OPENAPI_METADATA_FACTORY?.()[a]?.type??Reflect.getMetadata("design:type",o,a);Reflect.defineMetadata(e,{type:r,required:!1,...i.pickBy(t,i.negate(E))},o,a)}}}function v(e={}){return w(e)}function w(e={},t=!0){const[r,o]=((e,t)=>{if(!e)return[e,t];if(t)return[e,t];const r=i.isArray(e);return[r?e[0]:e,r]})(e.type,e.isArray);if((a=e={...e,type:r,isArray:o}).isArray&&"enum"in a&&void 0!==a.enum){e.type="array";const t=P(e.enum);e.items={type:O(t),enum:t},delete e.enum}else if("enum"in e&&void 0!==e.enum){const t=P(e.enum);e.enum=t,e.type=O(t)}var a;return Array.isArray(e.type)&&(e.type="array",e.items={type:"array",items:{type:e.type[0]}}),R(b.API_MODEL_PROPERTIES,e,t)}function D(e,r){const{handler:o,args:a}=t.Metadata.get(e,c.OperationKeys.REFLECT+c.OperationKeys.BLOCK)||{};return!!o&&(o(...a,r)??!1)}function S(e,r,a){const s={GET:[c.OperationKeys.READ,o.Get],POST:[c.OperationKeys.CREATE,o.Post],PUT:[c.OperationKeys.UPDATE,o.Put],PATCH:[c.OperationKeys.UPDATE,o.Patch],DELETE:[c.OperationKeys.DELETE,o.Delete]},[i,p]=s[r];return D(e,i)?t.apply(n.ApiExcludeEndpoint()):t.apply(p(a))}function T(e=[]){const t=e.map(e=>n.ApiParam({name:e.name,description:e.description??"Path parameter: "+e.name,required:e.required??!0,type:e.type??String}));return o.applyDecorators(...t)}const C=o.createParamDecorator((e,t)=>{const r=t.switchToHttp().getRequest().body,a=t.getClass(),s=a.class;if(!s)throw new o.InternalServerErrorException(`ModelConstructor not found on controller ${a.name}. Ensure the controller was created via FromModelController.`);return r?Array.isArray(r)?r.map(e=>new s(e)):new s(r):r}),x=o.createParamDecorator((e,t)=>{const r=t.switchToHttp().getRequest(),o=r?.params??{},a=e??Object.keys(o),s=a.map(e=>o[e]);return{raw:o,valuesInOrder:s,keysInOrder:a}});function M(e=[]){const t=e.map(e=>e.name);return x(t)}const I=o.createParamDecorator((e,t)=>{const r={...t.switchToHttp().getRequest().query??{}};if(void 0!==r.limit){const e=Number(r.limit);Number.isNaN(e)||(r.limit=e)}if(void 0!==r.offset){const e=Number(r.offset);Number.isNaN(e)||(r.offset=e)}if(void 0!==r.bookmark){const e=Number(r.bookmark);r.bookmark=Number.isNaN(e)?r.bookmark:e}return r});function $(e){const t={GET:o.Get,POST:o.Post,PUT:o.Put,PATCH:o.Patch,DELETE:o.Delete}[e];if(!t)throw Error(`Unsupported HTTP verb "${e}". No NestJS decorator mapping was found.`);return t}const q="DecafModuleOptions",F="DecafAdapter",k="DecafRoute",N=Symbol("DecafHandlers"),j=Symbol("DecafAdapterForOptions"),L=Symbol("AUTH_HANDLER"),K="auth:meta",B=Symbol("decaf:context");function U(t){const r=t?"string"==typeof t?t:t.name:void 0,a=[n.ApiBearerAuth(),o.UseInterceptors(e.AuthInterceptor)];return r&&a.push(o.SetMetadata(K,r)),o.applyDecorators(...a)}e.AuthInterceptor=class{constructor(e,t){this.reflector=e,this.authHandler=t}async intercept(e,t){const r=l.Logging.for(this).for(this.intercept),o=this.reflector.get(K,e.getHandler())??this.reflector.get(K,e.getClass());return r.verbose("Intercepted request"+(o?" for "+o:"")),this.authHandler?await this.authHandler.authorize(e,o):r.debug("No auth handler/model"),t.handle()}},e.AuthInterceptor=p.__decorate([o.Injectable(),p.__param(1,o.Optional()),p.__param(1,o.Inject(L)),p.__metadata("design:paramtypes",[d.Reflector,Object])],e.AuthInterceptor);class H{parseRequest(e){const t=e.headers.authorization?.split(" ")[1];return t}async authorize(e,r){const o=e.switchToHttp().getRequest(),i=this.parseRequest(o);if(!i)throw new s.AuthorizationError("Unauthenticated");if(!t.Metadata.get(a.Model.get(r),s.PersistenceKeys.AUTH_ROLE).includes(i))throw new s.AuthorizationError("Missing role: "+i)}}var G;e.DecafRequestContext=class{constructor(e){this.req=e,this.uuid=s.UUID.instance.generate()}get request(){return this.req}put(e){let t;try{t=this.ctx.get("overrides")}catch(e){t={}}this._ctx=this.ctx.accumulate({overrides:Object.assign(t,e)})}applyCtx(e){if(this._ctx)throw new c.InternalError("Trying to overwrite context");this._ctx=e}get ctx(){if(!this._ctx)throw new c.InternalError("Context not initialized for request");return this._ctx}},e.DecafRequestContext=p.__decorate([o.Injectable({scope:o.Scope.REQUEST}),p.__param(0,o.Inject(d.REQUEST)),p.__metadata("design:paramtypes",[Request])],e.DecafRequestContext),e.DecafHandlerExecutor=G=class{constructor(e,t){this.handlers=e,this.context=t}async exec(e,t){l.Logging.for(G.name).for(this.exec).debug(`CONTEXT ${this.context.uuid} running ${this.handlers.length} handlers for request ${e.method} ${e.url}`);for(const r of this.handlers)await r.handle(this.context,e,t)}},e.DecafHandlerExecutor=G=p.__decorate([o.Injectable({scope:o.Scope.REQUEST}),p.__param(0,o.Inject(N)),p.__metadata("design:paramtypes",[Array,e.DecafRequestContext])],e.DecafHandlerExecutor),e.DecafResponseInterceptor=class{constructor(e){this.ctx=e}intercept(e,t){let r=e.switchToHttp().getResponse();return t.handle().pipe(u.tap(e=>{r=this.ctx.ctx.toResponse(r)}))}},e.DecafResponseInterceptor=p.__decorate([o.Injectable(),p.__metadata("design:paramtypes",[e.DecafRequestContext])],e.DecafResponseInterceptor);const z=e=>({name:e,description:e+" parameter for the query",required:!0,type:String});function Q(e,t,r,a=!1){const i=$(r),c=(e=>e.split("/").filter(e=>e.startsWith(":")).map(e=>e.slice(1)))(t).map(z),p=[];return"GET"===r&&a&&p.push(n.ApiQuery({name:"direction",required:!1,enum:s.OrderDirection,description:"the sort order when applicable"}),n.ApiQuery({name:"limit",required:!1,description:"limit or page size when applicable"}),n.ApiQuery({name:"offset",required:!1,description:"offset or bookmark when applicable"})),{method:[i(t),...c.map(n.ApiParam),...p,n.ApiOperation({summary:`Retrieve records using according to "${e}".`}),n.ApiOkResponse({description:"Result successfully retrieved."}),n.ApiNoContentResponse({description:"No content returned by the method."})],params:[M(c),o.Query()]}}function V(e,t,r,o){const a=e?.prototype??e;o.method.forEach(e=>e(a,t,r)),o.params?.forEach((e,r)=>e(a,t,r))}function Y(e,t,...r){if(e instanceof s.ModelService)return"function"==typeof e[t]?e[t](...r):e.statement(t,...r);if("function"==typeof e[t])return e[t](...r);throw Error(`Persistence method "${t}" not found on ${e?.constructor?.name}`)}function J(e){return async function(t,r){const o=this.log.for(e);try{o.debug(`Invoking persistence method "${e}" given parameters: ${JSON.stringify(t.valuesInOrder)}`);const{direction:a,limit:s,offset:i}=r;return await Y(this.persistence(),e,...t.valuesInOrder,a,s,i)}catch(t){throw o.error(`Custom query "${e}" failed`,t),t}}}function X(e,t,r){return Object.defineProperty(e.prototype||e,t,{value:r,writable:!1}),Object.getOwnPropertyDescriptor(e.prototype||e,t)}class W extends s.Service{constructor(e,t){super(),this.clientContext=e}logCtx(e,t,r=!1,o){const a=this.clientContext.ctx;let i;e=e.filter(e=>void 0!==e),o&&(o.headers||o.ip)&&(i=o,o={});const n=s.ContextualLoggedClass.logCtx.call(this,t,o||{},r,...e,a);return this.bindLoggerToRequest(n,i)}bindLoggerToRequest(e,t){const r=this;function o(e,t){return e.log=((e,t)=>{const o=(e=>{if(!e)return;const t=e.headers,r=ee(t?.["x-forwarded-for"])??ee(t?.["x-real-ip"])??ee(t?.["X-Forwarded-For"])??ee(t?.["X-Real-IP"]);if(r)return r;if("string"==typeof e.ip&&e.ip.length)return e.ip;const o=e.socket||e.connection;return o&&"string"==typeof o.remoteAddress&&o.remoteAddress.length?o.remoteAddress:void 0})(t??r.clientContext.request);if(!o)return e;const a={ip:o};return e.for(a)})(e.log,t),e}return(e=>"object"==typeof e&&null!==e&&"function"==typeof e.then)(e)?e.then(e=>o(e,t)):o(e,t)}}class Z extends W{persistence(e){if(!this._persistence)try{this._persistence=s.Service.get(this.class)}catch(e){try{this._persistence=s.ModelService.getService(this.class)}catch(e){this._persistence=s.Repository.forModel(this.class)}}const t=this.clientContext.request[j]||{};return e&&this.clientContext.put(t),e?this._persistence instanceof s.Repository?this._persistence.override(t):this._persistence.for(t):this._persistence}constructor(e,t){super(e,t)}logCtx(e,t,r=!1,o){const a=this.clientContext.ctx;let i;o&&(o.headers||o.ip)&&(i=o,o={});try{o=a.get("overrides")}catch(e){}const n=this.persistence(a);let c,p;return n instanceof s.ModelService?c=n.repo._adapter:n instanceof s.Repository?c=n._adapter:n.context&&(c=n),r?c.logCtx(e,t,!0,o).then(e=>this.bindLoggerToRequest(e,i)):(p=c.logCtx(e,t,!1,o),this.bindLoggerToRequest(p,i))}}function ee(e){if(e)return(Array.isArray(e)?e[0]:e).split(",").map(e=>e.trim()).filter(Boolean)[0]}const te=new Map;function re(e,r){if(!s.TransactionOperationKeys.includes(e))return r;const o=(e=>(te.has(e)||te.set(e,new WeakMap),te.get(e)))(e),i=o.get(r);if(i)return i;const n=[c.OperationKeys.UPDATE,c.BulkCrudOperationKeys.UPDATE_ALL].includes(e);class p{}o.set(r,p),Object.defineProperty(p,"name",{value:`${l.toPascalCase(r.name)}${l.toPascalCase(e)}DTO`});const d=(()=>{try{return a.Model.pk(r)}catch{return}})(),u=d?a.Model.pkProps(r):void 0,h=d?Reflect.getMetadata("design:type",r.prototype,d):void 0,m=h===Number||h===BigInt,f=!!u?.generated||!!d&&(a.Model.generatedBySequence(r,d)||se(r,d)||m),y=Array.from(new Set(t.Metadata.properties(r)||[])),g=new Set(a.Model.relations(r)||[]),_=[];for(const e of y)e&&(g.has(e)||e===d&&!n&&f||e!==d&&se(r,e)||_.push(e));for(const e of _){const t=ie(r,e),o=!!t?.[a.ValidationKeys.REQUIRED],s=ne(r,e)??Reflect.getMetadata("design:type",r.prototype,e),i={required:o};s&&(i.type=s),v(i)(p.prototype,e);const n=Reflect.getMetadata("design:type",r.prototype,e)??s;void 0!==n&&Reflect.defineMetadata("design:type",n,p.prototype,e),Object.defineProperty(p.prototype,e,{value:void 0,writable:!0,enumerable:!0,configurable:!0})}for(const o of g){const s=t.Metadata.relations(r,o);if(!s)throw new c.InternalError(`Metadata for relation ${o} not found`);let i=s.class;if("function"!=typeof i||i.name||(i=i()),!i||"function"!=typeof i)throw new c.InternalError(`Type for relation ${o} not found`);if(!a.Model.get(i.name))continue;const d=t.Metadata.validationFor(r,o),l=!!d?.[a.ValidationKeys.LIST],u=!!d?.[a.ValidationKeys.REQUIRED],h=re(e,i);n?ae(p,o,i,h,l,u):oe(p,o,h,l,u)}return p}function oe(e,t,r,o,a){v({type:r,required:a,isArray:o})(e.prototype,t),Reflect.defineMetadata("design:type",o?Array:r,e.prototype,t),Object.defineProperty(e.prototype,t,{value:void 0,writable:!0,enumerable:!0,configurable:!0})}function ae(e,t,r,o,s,i){const n=Reflect.getMetadata(b.API_EXTRA_MODELS,e)||[];n.includes(o)||Reflect.defineMetadata(b.API_EXTRA_MODELS,[...n,o],e);const c="#/components/schemas/"+o.name,p=(e=>{try{const t=a.Model.pkProps(e),r=t?.type;return r===Number||r===BigInt?"integer":"string"}catch{return"string"}})(r),d=[{$ref:c},{type:p}];v(s?{type:"array",required:i,oneOf:d}:{type:Object,required:i,oneOf:d})(e.prototype,t),Reflect.defineMetadata("design:type",s?Array:Object,e.prototype,t),Object.defineProperty(e.prototype,t,{value:void 0,writable:!0,enumerable:!0,configurable:!0})}function se(e,t){let r=e;for(;r&&r!==Object&&r!==Function;){if(a.Model.generated(r,t))return!0;r=Object.getPrototypeOf(r)}return!1}function ie(e,r){let o=e;for(;o&&o!==Object&&o!==Function;){const e=t.Metadata.validationFor(o,r);if(e)return e;o=Object.getPrototypeOf(o)}}function ne(e,r){let o=e;for(;o&&o!==Object&&o!==Function;){const e=t.Metadata.type(o,r);if(e)return e;o=Object.getPrototypeOf(o)}}s.Adapter.transformerFor=(e=>{const r="string"==typeof e?e:e.alias;return t.Metadata.innerGet(Symbol.for("transformers"),r)}).bind(s.Adapter),s.Adapter.flavoursToTransform=(()=>{const e=t.Metadata.innerGet(Symbol.for("transformers"));if(e)return Object.keys(e)}).bind(s.Adapter),s.Context.prototype.toResponse=function(e){const t=this.pending();return t&&e.header("x-pending-task",JSON.stringify(t)),e};const ce=a.ModelBuilder.prototype;if(ce.decorateClass||(ce.decorateClass=function(e){return this._classDecorators||(this._classDecorators=[]),this._classDecorators.push(e),this}),ce.Auth=function(e){return this.decorateClass(U(e))},!ce.__hasClassDecoratorSupport){const e=ce.build;ce.build=function(){let t=e.call(this);const r=this._classDecorators;if(r?.length)for(const e of r){const r=e(t);r&&(t=r)}return t},ce.__hasClassDecoratorSupport=!0}class pe{static{this.log=l.Logging.for(pe.name)}static getPersistence(e){try{return s.Service.get(e)}catch(t){try{return s.ModelService.getService(e)}catch(t){return s.Repository.forModel(e)}}}static createQueryRoutesFromRepository(e,r=s.PersistenceKeys.QUERY){const o=pe.log.for(pe.createQueryRoutesFromRepository),a=e instanceof s.ModelService?e.repo:e,i=a.class,n=t.Metadata.get(a.constructor,t.Metadata.key(s.PersistenceKeys.QUERY))??{},c=t.Metadata.get(e.constructor,t.Metadata.key(k))??{};class p extends Z{get class(){throw Error("Method not implemented.")}constructor(e,t){super(e,t)}}for(const[e,t]of Object.entries(c)){const r=[t.path.replace(/^\/+|\/+$/g,"")].filter(e=>e&&e.trim()).join("/"),a=J(e);if(!a){const t=`Invalid or missing handler for model ${i.name} on decorated method ${e}`;throw o.error(t),Error(t)}const s=X(p,e,a);s&&V(p,e,s,Q(e,r,t.httpMethod))}for(const[e,t]of Object.entries(n)){const o=[r,e,...(t.fields??[]).map(e=>":"+e)].filter(e=>e&&e.trim()).join("/"),a=X(p,e,J(e));a&&V(p,e,a,Q(e,o,"GET",!0))}return p}static create(t){const r=pe.log.for(pe.create),i=a.Model.tableName(t),d=l.toKebabCase(i),u=t.name,h=pe.getPersistence(t),{description:m,getPK:f,apiProperties:y,path:g}=pe.getRouteParametersFromModel(t);r.debug("Creating controller for model: "+u);const _=pe.createQueryRoutesFromRepository(h);let A=class extends _{static get class(){return t}get class(){return t}constructor(e){super(e),this.pk=a.Model.pk(t),r.info(`Registering dynamic controller for model: ${this.class.name} route: /${d}`)}async listBy(e,t){const{ctx:r}=(await this.logCtx([],s.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return this.persistence(r).listBy(e,t.direction,r)}async paginateBy(e,t){const{ctx:r}=(await this.logCtx([],s.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);return this.persistence(r).paginateBy(e,t.direction,t,r)}async find(e,t){const{ctx:r}=(await this.logCtx([],s.PreparedStatementKeys.FIND,!0)).for(this.find),o=t.direction??s.OrderDirection.ASC;return Y(this.persistence(r),this.find.name,e,o,r)}async page(e,t){const{ctx:r}=(await this.logCtx([],s.PreparedStatementKeys.PAGE,!0)).for(this.page),{direction:o=s.OrderDirection.ASC,limit:a,offset:i,bookmark:n}=t,c={offset:i??1,limit:a??10,bookmark:n};return Y(this.persistence(r),this.page.name,e,o,c,r)}async findOneBy(e,t){const{ctx:r}=(await this.logCtx([],s.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);return this.persistence(r).findOneBy(e,t,r)}async findBy(e,t,r){const{ctx:o}=(await this.logCtx([],s.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return this.persistence(o).for(o.toOverrides()).findBy(e,t,o)}async statement(e,t,r){const{ctx:o}=(await this.logCtx([],s.PersistenceKeys.STATEMENT,!0)).for(this.statement),{direction:a,offset:i,limit:n,bookmark:c}=r,p=(t=t.map(e=>("string"==typeof e?parseInt(e):e)||e)).length>1?t[1]:void 0,d=a??p;switch(d&&t.length>1&&(t[1]=d),e){case s.PreparedStatementKeys.FIND:case s.PreparedStatementKeys.FIND_BY:break;case s.PreparedStatementKeys.LIST_BY:t.push(a);break;case s.PreparedStatementKeys.PAGE:case s.PreparedStatementKeys.PAGE_BY:t=[t[0],d,{limit:n,offset:i,bookmark:c}];case s.PreparedStatementKeys.FIND_ONE_BY:case s.PreparedStatementKeys.COUNT_OF:case s.PreparedStatementKeys.MAX_OF:case s.PreparedStatementKeys.MIN_OF:case s.PreparedStatementKeys.AVG_OF:case s.PreparedStatementKeys.SUM_OF:case s.PreparedStatementKeys.DISTINCT_OF:case s.PreparedStatementKeys.GROUP_OF:}return this.persistence(o).statement(e,...t,o)}async createAll(e,r){const{ctx:o,log:a}=(await this.logCtx([],c.BulkCrudOperationKeys.CREATE_ALL,!0)).for(this.createAll);let s;a.verbose("creating new "+u);try{s=await this.persistence(o).createAll(e.map(e=>new t(e)),o)}catch(e){throw a.error("Failed to create new "+u,e),e}return a.info(`created new ${u} with id ${s[this.pk]}`),o.toResponse(r),s}async create(e,t){const{ctx:r,log:o}=(await this.logCtx([],c.OperationKeys.CREATE,!0)).for(this.create);let a;o.verbose("creating new "+u);try{const t=this.persistence(r);a=await t.create(e,r)}catch(e){throw o.error("Failed to create new "+u,e),e}return o.info(`created new ${u} with id ${a[this.pk]}`),r.toResponse(t),a}async readAll(e){const{ctx:t,log:r}=(await this.logCtx([],c.BulkCrudOperationKeys.READ_ALL,!0)).for(this.readAll);let o;try{r.debug(`reading ${e.length} ${u}: ${e}`);const a=this.persistence(t);o=await a.readAll(e,t)}catch(t){throw r.error(`Failed to ${u} with id ${e}`,t),t}return r.info(`read ${o.length} ${u}`),o}async read(e){const{ctx:t,log:r}=(await this.logCtx([],c.OperationKeys.READ,!0)).for(this.read),o=f(...e.valuesInOrder);if(void 0===o)throw new c.ValidationError(`No ${this.pk} provided`);let a;try{r.debug(`reading ${u} with ${this.pk} ${o}`);const e=this.persistence(t);a=await e.read(o,t)}catch(e){throw r.error(`Failed to read ${u} with id ${o}`,e),e}return r.info(`read ${u} with id ${a[this.pk]}`),a}async updateAll(e,t){const{ctx:r,log:o}=(await this.logCtx([],c.BulkCrudOperationKeys.UPDATE_ALL,!0)).for(this.updateAll);let a;try{o.info(`updating ${e.length} ${u}`),a=await this.persistence(r).updateAll(e,r)}catch(e){throw o.error(e),e}return r.toResponse(t),a}async update(e,r,o){const{ctx:a,log:s}=(await this.logCtx([],c.OperationKeys.UPDATE,!0)).for(this.update),i=f(...e.valuesInOrder);if(void 0===i)throw new c.ValidationError(`No ${this.pk} provided`);let n;try{s.info(`updating ${u} with ${this.pk} ${i}`);const e=JSON.parse(JSON.stringify(r)),o=this.persistence(a);n=await o.update(new t({...e,[this.pk]:i}),a)}catch(e){throw s.error(e),e}return a.toResponse(o),n}async deleteAll(e,t){const{ctx:r,log:o}=(await this.logCtx([],c.BulkCrudOperationKeys.DELETE_ALL,!0)).for(this.deleteAll);let a;try{o.debug(`deleting ${e.length} ${u}: ${e}`),a=await this.persistence(r).deleteAll(e,r)}catch(t){throw o.error(`Failed to delete ${u} with id ${e}`,t),t}return o.info(`deleted ${a.length} ${u}`),r.toResponse(t),a}async delete(e,t){const{ctx:r,log:o}=(await this.logCtx([],c.OperationKeys.DELETE,!0)).for(this.delete),a=f(...e.valuesInOrder);if(void 0===a)throw new c.ValidationError(`No ${this.pk} provided`);let s;try{o.debug(`deleting ${u} with ${this.pk} ${a}`),s=await this.persistence(r).delete(a,r)}catch(e){throw o.error(`Failed to delete ${u} with id ${a}`,e),e}return o.info(`deleted ${u} with id ${a}`),r.toResponse(t),s}};return p.__decorate([S(t,"GET","listBy/:key"),n.ApiOperation({summary:`Retrieve ${u} records by query.`}),n.ApiParam({name:"key",description:"the model key to sort by"}),n.ApiQuery({name:"direction",required:!0,enum:s.OrderDirection}),n.ApiOkResponse({description:u+" listed successfully."}),p.__param(0,o.Param("key")),p.__param(1,I()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"listBy",null),p.__decorate([S(t,"GET","paginateBy/:key/:page"),n.ApiOperation({summary:`Retrieve ${u} records by query.`}),n.ApiParam({name:"key",description:"the model key to sort by"}),n.ApiParam({name:"page",description:"the page to retrieve or the bookmark"}),n.ApiQuery({name:"direction",required:!0,enum:s.OrderDirection,description:"the sort order"}),n.ApiQuery({name:"limit",required:!0,description:"the page size"}),n.ApiQuery({name:"offset",description:"the bookmark when necessary"}),n.ApiOkResponse({description:u+" listed paginated."}),p.__param(0,o.Param("key")),p.__param(1,I()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"paginateBy",null),p.__decorate([S(t,"GET","find/:value"),n.ApiOperation({summary:`Find ${u} records using the default query attributes.`}),n.ApiParam({name:"value",description:"The string to match against the default query attributes"}),n.ApiQuery({name:"direction",required:!1,enum:s.OrderDirection,description:"the sort order for the matching results"}),n.ApiOkResponse({description:u+" records matching the provided prefix."}),p.__param(0,o.Param("value")),p.__param(1,I()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"find",null),p.__decorate([S(t,"GET","page/:value"),n.ApiOperation({summary:`Page ${u} records using the default query attributes.`}),n.ApiParam({name:"value",description:"The string to match against the default query attributes"}),n.ApiQuery({name:"direction",required:!1,enum:s.OrderDirection,description:"the sort order for the paged results"}),n.ApiQuery({name:"limit",required:!1,description:"page size"}),n.ApiQuery({name:"offset",required:!1,description:"page number"}),n.ApiQuery({name:"bookmark",required:!1,description:"bookmark for cursor pagination"}),n.ApiOkResponse({description:u+" records paged by the provided prefix."}),p.__param(0,o.Param("value")),p.__param(1,I()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"page",null),p.__decorate([S(t,"GET","findOneBy/:key"),n.ApiOperation({summary:`Retrieve ${u} records by query.`}),n.ApiParam({name:"key",description:"the model key to sort by"}),n.ApiOkResponse({description:u+" listed found."}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,o.Param("key")),p.__param(1,o.Param("value")),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"findOneBy",null),p.__decorate([S(t,"GET","findBy/:key/:value"),n.ApiOperation({summary:`Retrieve ${u} records by query.`}),n.ApiParam({name:"key",description:"the model key to compare"}),n.ApiParam({name:"value",description:"the value to match"}),n.ApiQuery({name:"direction",required:!0,enum:s.OrderDirection,description:"the sort order when applicable"}),n.ApiOkResponse({description:u+" listed found."}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,o.Param("key")),p.__param(1,o.Param("value")),p.__param(2,I()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"findBy",null),p.__decorate([S(t,"GET","statement/:method/*args"),n.ApiOperation({summary:`Executes a prepared statement on ${u}.`}),n.ApiParam({name:"method",description:"the prepared statement to execute"}),n.ApiParam({name:"args",description:"concatenated list of arguments the prepared statement can accept"}),n.ApiQuery({name:"direction",required:!0,enum:s.OrderDirection,description:"the sort order when applicable"}),n.ApiQuery({name:"limit",required:!0,description:"limit or page size when applicable"}),n.ApiQuery({name:"offset",required:!0,description:"offset or bookmark when applicable"}),n.ApiOkResponse({description:u+" listed found."}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,o.Param("method")),p.__param(1,o.Param("args")),p.__param(2,I()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Array,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"statement",null),p.__decorate([S(t,"POST","bulk"),n.ApiOperation({summary:`Create a new ${u}.`}),n.ApiBody({description:"Payload for "+u,schema:{type:"array",items:{$ref:n.getSchemaPath(t)}}}),n.ApiCreatedResponse({description:u+" created successfully.",schema:{type:"array",items:{$ref:n.getSchemaPath(t)}}}),n.ApiBadRequestResponse({description:"Payload validation failed."}),n.ApiUnprocessableEntityResponse({description:"Repository rejected the provided payload."}),p.__param(0,C()),p.__param(1,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Array,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"createAll",null),p.__decorate([S(t,"POST"),n.ApiOperation({summary:`Create a new ${u}.`}),n.ApiBody({description:"Payload for "+u,type:re(c.OperationKeys.CREATE,t)}),n.ApiCreatedResponse({description:u+" created successfully.",schema:{$ref:n.getSchemaPath(t)}}),n.ApiBadRequestResponse({description:"Payload validation failed."}),n.ApiUnprocessableEntityResponse({description:"Repository rejected the provided payload."}),p.__param(0,C()),p.__param(1,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Object,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"create",null),p.__decorate([S(t,"GET","bulk"),n.ApiOperation({summary:`Retrieve a ${u} record by id.`}),n.ApiQuery({name:"ids",required:!0,type:"array"}),n.ApiOkResponse({description:u+" retrieved successfully.",schema:{type:"array",items:{$ref:n.getSchemaPath(t)}}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,o.Query("ids")),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Array]),p.__metadata("design:returntype",Promise)],A.prototype,"readAll",null),p.__decorate([S(t,"GET",g),T(y),n.ApiOperation({summary:`Retrieve a ${u} record by id.`}),n.ApiOkResponse({description:u+" retrieved successfully.",schema:{$ref:n.getSchemaPath(t)}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,M(y)),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Object]),p.__metadata("design:returntype",Promise)],A.prototype,"read",null),p.__decorate([S(t,"PUT","bulk"),T(y),n.ApiOperation({summary:`Replace an existing ${u} record with a new payload.`}),n.ApiBody({description:"Payload for replace a existing record of "+u,schema:{type:"array",$ref:n.getSchemaPath(re(c.OperationKeys.UPDATE,t))}}),n.ApiOkResponse({description:u+" updated successfully.",schema:{type:"array",items:{$ref:n.getSchemaPath(t)}}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),n.ApiBadRequestResponse({description:"Payload validation failed."}),p.__param(0,C()),p.__param(1,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Array,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"updateAll",null),p.__decorate([S(t,"PUT",g),T(y),n.ApiOperation({summary:`Replace an existing ${u} record with a new payload.`}),n.ApiBody({description:"Payload for replace a existing record of "+u,type:re(c.OperationKeys.UPDATE,t)}),n.ApiOkResponse({description:u+" updated successfully.",schema:{$ref:n.getSchemaPath(t)}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),n.ApiBadRequestResponse({description:"Payload validation failed."}),p.__param(0,M(y)),p.__param(1,C()),p.__param(2,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Object,Object,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"update",null),p.__decorate([S(t,"DELETE","bulk"),T(y),n.ApiOperation({summary:`Retrieve a ${u} record by id.`}),n.ApiQuery({name:"ids",required:!0,type:"array"}),n.ApiOkResponse({description:u+" deleted successfully.",schema:{type:"array",items:{$ref:n.getSchemaPath(t)}}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,o.Query("ids")),p.__param(1,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Array,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"deleteAll",null),p.__decorate([S(t,"DELETE",g),T(y),n.ApiOperation({summary:`Delete a ${u} record by id.`}),n.ApiOkResponse({description:u+" deleted successfully.",schema:{$ref:n.getSchemaPath(t)}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,M(y)),p.__param(1,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Object,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"delete",null),A=p.__decorate([o.Controller(d),n.ApiTags(u),n.ApiExtraModels(t),U(t),p.__metadata("design:paramtypes",[e.DecafRequestContext])],A),A}static getRouteParametersFromModel(e){const r=a.Model.pk(e),o=t.Metadata.get(e,t.Metadata.key(c.DBKeys.COMPOSED,r)),s=o?.args??[],i=Array.isArray(s)&&s.length>0?Array.from(new Set([...s])):Array.from(new Set([r])),n=t.Metadata.description(e);return{path:":"+i.join("/:"),description:n,apiProperties:i.map(r=>({name:r,description:t.Metadata.description(e,r),required:!0,type:String})),getPK:(...e)=>o?.separator?e.join(o.separator):e.join("")}}}function de(e){var t;let r=class{static{t=this}static{this.log=l.Logging.for(t.name).for(e)}static createModelServices(e){return e.map(e=>({provide:e.name+"Service",useFactory:()=>s.ModelService.forModel(e)}))}static forRoot(e,r={}){const o=this.log.for(this.forRoot);o.info("Generating controllers for flavour...");const a=s.Adapter.models(e);let i=[];r.autoServices&&(o.info("Auto-services enabled. Initializing service generation."),i=this.createModelServices(a),o.info(`Auto-services completed. ${i.length} services initialized.`));const n=a.map(pe.create);return o.info(`Generated ${n.length} controllers`),{module:t,controllers:n,providers:[...i]}}};return r=t=p.__decorate([o.Module({})],r),Object.assign(r,"name",{value:"DecafModule"+e}),r}t.Decoration.for(r.InjectablesKeys.INJECTABLE).extend({decorator:(e,t)=>(t=t||("object"==typeof e?Object.assign(e,r.DefaultInjectablesConfig):r.DefaultInjectablesConfig),o.Injectable({scope:t.singleton?o.Scope.DEFAULT:o.Scope.REQUEST,durable:!t.singleton||void 0}))}).apply(),t.Decoration.for(r.InjectablesKeys.INJECT).extend({decorator:(e,t)=>(t,r,a)=>o.Inject(e||t)(t,r,a)}).apply(),t.Decoration.for(a.ValidationKeys.REQUIRED).extend(v({required:!0})).apply(),t.Decoration.for(a.ValidationKeys.MAX).extend({decorator:e=>v({maximum:e,required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.MIN).extend({decorator:e=>v({minimum:e,required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.MAX_LENGTH).extend({decorator:e=>v({maxLength:e,required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.MIN_LENGTH).extend({decorator:e=>v({minLength:e,required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.TYPE).extend({decorator:e=>(t,r)=>("function"!=typeof(e=Array.isArray(e)?e[0]:e)||e.name||(e=e()),v({type:e,required:!1})(t,r))}).apply(),t.Decoration.for(a.ValidationKeys.DATE).extend({decorator:e=>v({type:String,format:"date-time",required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.ENUM).extend({decorator:e=>v({enum:Array.isArray(e)?e:Object.values(e),required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.PATTERN).extend({decorator:e=>v({pattern:"string"==typeof e?e:e.source,required:!1})}).apply(),t.Decoration.for(s.PersistenceKeys.COLUMN).extend({decorator:e=>v({name:e,required:!1})}).apply(),t.Decoration.for(t.DecorationKeys.DESCRIPTION).extend({decorator:e=>v({description:e,required:!1})}).apply(),t.Decoration.for(s.PersistenceKeys.AUTH).extend({decorator:U}).apply();class le extends s.ForbiddenError{constructor(e){super(e,le.name)}}class ue extends c.BaseError{constructor(e){super(ue.name,e,429)}}e.DecafExceptionFilter=class{catch(e,t){const r=t.switchToHttp(),a=r.getResponse(),i=r.getRequest(),n="production"===l.LoggedEnvironment.env;let p;e instanceof o.NotFoundException||e instanceof s.UnsupportedError?p=(e=new o.NotAcceptableException(e.message)).getStatus():e instanceof c.BaseError||(e=429===e.status?new ue(e.message):new c.InternalError(e.message)),a.status(e.code||p).json({status:e.code||p,error:n?e.name:e.message,timestamp:(new Date).toISOString(),path:i.url,method:i.method})}},e.DecafExceptionFilter=p.__decorate([o.Catch()],e.DecafExceptionFilter);const he={path:"docs",auth:{type:"http",scheme:"bearer",bearerFormat:"JWT",name:"Authorization",description:"Enter JWT token",in:"header"},topbarBgColor:"#000000"};class me{constructor(e){this.options={...e}}customCSS(){let e="";return this.options.topbarIconPath&&(e+=`.topbar-wrapper { content: url('data:image/png;base64,${this.b64(this.options.topbarIconPath)}'); width: 200px; height: auto; }\n`),e+`\n .topbar-wrapper svg { visibility: hidden; }\n .swagger-ui .topbar { background-color: ${this.options.topbarBgColor||he.topbarBgColor}; }\n `}getCustomOptions(){const e={};return this.options.faviconPath&&(e.customfavIcon=this.b64(this.options.faviconPath,!0)),{customSiteTitle:this.options.title,...e,customCss:this.customCSS(),swaggerOptions:{persistAuthorization:this.options.persistAuthorization}}}b64(e,t=!1){const r=_.join(this.options.assetsPath||"",e),o=h.readFileSync(r,{encoding:"base64"});return t?"data:image/png;base64,"+o:o}}class fe{constructor(e,t){this.app=e,this.options=t}createDocument(){const e=this.options.path?this.options.description+""+`<br><br><a href="${this.options.openApiJsonPath}">OpenAPI JSON Spec</a> | `+`<a href="${this.options.openApiYamlPath}">OpenAPI YAML Spec</a>`:this.options.description,t=(new n.DocumentBuilder).setTitle(this.options.title).setDescription(e).setVersion(this.options.version||"0.0.1").addBearerAuth(this.options.auth||he.auth).build();return n.SwaggerModule.createDocument(this.app,t,{extraModels:this.options.extraModels||[]})}registerOpenApiRoute(e,t,r){if(!e)return;const o=this.app.getHttpAdapter();e=e.startsWith("/")?e:"/"+e,o.get(e,(e,a)=>{o.reply(a,r(),200,{"Content-Type":t})})}setupSwagger(){const e=this.createDocument(),t=new me({title:this.options.title,path:this.options.path||he.path,persistAuthorization:this.options.persistAuthorization??!0,assetsPath:this.options.assetsPath,faviconPath:this.options.faviconFilePath,topbarIconPath:this.options.topbarIconFilePath,topbarBgColor:this.options.topbarBgColor});n.SwaggerModule.setup(this.options.path||he.path,this.app,e,{...t.getCustomOptions(),jsonDocumentUrl:this.options.openApiJsonPath?""+this.options.openApiJsonPath:void 0,yamlDocumentUrl:this.options.openApiYamlPath?""+this.options.openApiYamlPath:void 0}),this.registerOpenApiRoute(this.options.openApiJsonPath,"application/json",()=>e),this.registerOpenApiRoute(this.options.openApiYamlPath,"application/x-yaml",()=>f.stringify(e))}}var ye,ge;function _e(e){return r=>(t.Metadata.set("transformers",e,r),"function"==typeof r?t.metadata("transformers",e)(r):r)}e.DecafRequestHandlerInterceptor=ye=class{constructor(e,t){this.requestContext=e,this.executor=t}async contextualize(e){const t={headers:e.headers,overrides:{}},r=s.Adapter.flavoursToTransform();if(r)for(const o of r)try{const r=s.Adapter.transformerFor(o),a=await r.from(e);Object.assign(t.overrides,a)}catch(e){throw new c.InternalError("Failed to contextualize request: "+e)}return(new s.Context).accumulate(Object.assign({},s.DefaultAdapterFlags,{logger:l.Logging.get(),timestamp:new Date},t))}async intercept(e,t){const r=e.switchToHttp().getRequest(),o=e.switchToHttp().getResponse(),a=l.Logging.for(ye).for(this.intercept);a.debug(`CONTEXT ${this.requestContext.uuid} - request: ${r.method} ${r.url}`);const s=await this.contextualize(r);return a.debug(`CONTEXT ${this.requestContext.uuid} contextualized - request: ${r.method} ${r.url}`),this.requestContext.applyCtx(s),a.debug(`CONTEXT ${this.requestContext.uuid} applied - request: ${r.method} ${r.url}`),await this.executor.exec(r,o),a.debug(`CONTEXT ${this.requestContext.uuid} executors finished - request: ${r.method} ${r.url}`),t.handle()}},e.DecafRequestHandlerInterceptor=ye=p.__decorate([o.Injectable({scope:o.Scope.REQUEST}),p.__metadata("design:paramtypes",[e.DecafRequestContext,e.DecafHandlerExecutor])],e.DecafRequestHandlerInterceptor),e.DecafCoreModule=class{static{ge=this}static get persistence(){if(!this._persistence)throw new c.InternalError("Persistence service not initialized");return this._persistence}static get log(){return this._logger||(this._logger=l.Logging.for(ge)),this._logger}constructor(e,t){this.options=e,this.moduleRef=t}static forRoot(t){const r=this.log.for(this.forRoot);return{module:ge,providers:[{provide:q,useValue:t},{provide:F,useValue:this.persistence?.client},{provide:N,useFactory:()=>t.handlers?.map(e=>(r.info("Registered request handler: "+e.name),new e))??[]},e.AuthInterceptor,{provide:d.APP_INTERCEPTOR,useExisting:e.AuthInterceptor},e.DecafRequestContext,e.DecafHandlerExecutor,{provide:d.APP_INTERCEPTOR,useClass:e.DecafRequestHandlerInterceptor}],exports:[q,F,N,e.DecafRequestContext,e.DecafHandlerExecutor]}}static async bootPersistence(e){const t=this.log.for(this.bootPersistence);if(!this._persistence){const r=e.conf.map(([e,t,...r])=>r.pop()?[e,t,...r]:[e,t]);this._persistence=new s.PersistenceService,await this._persistence.boot(r);const o=this._persistence.client;for(let t=0;t<o.length;t++){const r=e.conf[t];let a=r.slice(2,r.length).pop();if(!a||!a.from){const e=s.Adapter.transformerFor(o[t].flavour);if(!e)throw new c.InternalError(`No transformer found for flavour ${o[t].flavour}. you should either @requestToContextTransformer or provide a transformer in the config`);try{a=e.from?e:new e}catch(e){throw new c.InternalError(`Failed to boot transformer for ${o[t].flavour}: ${e}`)}}_e(o[t].flavour)(a)}if(t.info("persistence layer created successfully!"),e.initialization)try{await e.initialization()}catch(e){throw new c.InternalError("Failed to initialize application: "+e)}}return this.persistence.client}async onApplicationShutdown(){const e=ge.log.for(this.onApplicationShutdown),t=this.moduleRef.get(F);for(const r of t)try{r&&(e.info("Shutting down "+r.toString()),await r.shutdown())}catch(t){e.error("Failed to shutdown application",t)}}},e.DecafCoreModule=ge=p.__decorate([o.Global(),o.Module({}),p.__param(0,o.Inject(q)),p.__metadata("design:paramtypes",[Object,d.ModuleRef])],e.DecafCoreModule);const Ae=Symbol("LISTENING_ADAPTERS_FLAVOURS");var be,Ee,Pe,Oe;e.EventsController=be=class extends W{constructor(e,t){super(e,be.name),this.adapters=t.map(e=>s.Adapter.get(e))}listen(){const e=l.Logging.for(be.name),t=new u.Observable(t=>{const r=("B-"+Math.random().toString(36).slice(2,8)).toUpperCase();e.info(`Creating SSE observer: ${r} for client ${this.clientContext.uuid}`);const o=new class{constructor(){this.observerId=r}refresh(...r){return e.debug(`SSE observer ${this.observerId} received refresh event`),Promise.resolve().then(()=>{const o=(e=>{const[t,r,o,a]=e;return[t?.name??t,r,o,Array.isArray(a)?a.map(e=>{try{return"function"==typeof e.serialize?e.serialize():"string"==typeof e?e:JSON.stringify(e)}catch(e){return}}):a&&"function"==typeof a.serialize?a.serialize():"string"==typeof a?a:JSON.stringify(a)]})(r);t.next({type:"message",data:o}),e.debug(`SSE observer ${this.observerId} event pushed to client`)})}};e.verbose(`Registering observer ${r} across ${this.adapters.length} adapter(s)`);for(const t of this.adapters){const a=t?.constructor?.name??"UnknownAdapter";try{e.debug(`Registering observer ${r} in adapter ${a}`),t.observe(o)}catch(t){e.debug(`Failed to register observer ${r} in adapter ${a}: ${t?.message||t}`),e.error(t)}}return()=>{e.debug("Cleaning up SSE observer "+r);for(const t of this.adapters){const a=t?.constructor?.name??"UnknownAdapter";try{e.debug(`Unregistering observer ${r} from adapter ${a}`),t.unObserve(o)}catch(t){e.debug(`Failed during cleanup of observer ${r} in adapter ${a}: ${t?.message||t}`),e.error(t)}}}}),r=u.interval(15e3).pipe(y.tap(()=>{e.debug("Sending heartbeat")}),y.map(()=>({type:"heartbeat",data:{ts:(new Date).toISOString()}})));return u.merge(t,r)}listenForModel(e){const t=l.Logging.for(be.name);return new u.Observable(e=>{const r=new class{refresh(...t){return Promise.resolve().then(()=>{e.next({data:t})})}};try{for(const e of this.adapters)e.observe(r)}catch(t){e.error("Failed to observe event: "+(t.message||t))}return()=>{try{for(const e of this.adapters)e.unObserve(r)}catch(e){t.error(e)}}})}},p.__decorate([o.Sse(),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[]),p.__metadata("design:returntype",u.Observable)],e.EventsController.prototype,"listen",null),p.__decorate([o.Sse("/:model"),p.__param(0,o.Query("model")),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String]),p.__metadata("design:returntype",u.Observable)],e.EventsController.prototype,"listenForModel",null),e.EventsController=be=p.__decorate([o.Controller(),p.__param(1,o.Inject(Ae)),p.__metadata("design:paramtypes",[e.DecafRequestContext,Array])],e.EventsController),e.DecafStreamModule=Ee=class{static forFlavours(t,r="events"){return{module:Ee,controllers:[e.EventsController],imports:[d.RouterModule.register([{path:r.replace(/^\//,""),module:Ee}])],providers:[e.DecafRequestContext,{provide:Ae,useValue:t??[]}]}}},e.DecafStreamModule=Ee=p.__decorate([o.Module({})],e.DecafStreamModule),e.DecafModule=Pe=class{static async forRootAsync(t){const{autoControllers:r,autoServices:o}=t,a=(await e.DecafCoreModule.bootPersistence(t)).map(e=>e.flavour),s=[e.DecafCoreModule.forRoot(t)];return r&&a.forEach(e=>{s.push(de(e).forRoot(e,{autoServices:o}))}),t.observerOptions?.enableObserverEvents&&s.push(e.DecafStreamModule.forFlavours(t.observerOptions.observerFlavours||a)),{module:Pe,imports:s}}},e.DecafModule=Pe=p.__decorate([o.Module({})],e.DecafModule);const Re=l.Logging.for("DecafMigrationModule");e.DecafMigrationModule=Oe=class{static forRoot(){return{module:Oe}}static async migrate(e,t){const r=Re.for(this.migrate);if(!t||0===t.length)throw new c.InternalError("No adapters provided. Make sure DecafCoreModule is configured and adapters are available.");return r.info("Running migrations with config: "+JSON.stringify(e)),(await import("@decaf-ts/core/migrations")).MigrationService.migrateAdapters(t,e||{})}},e.DecafMigrationModule=Oe=p.__decorate([o.Global(),o.Module({providers:[{provide:"MIGRATION_ADAPTERS",useFactory:e=>e,inject:[F]}],exports:["MIGRATION_ADAPTERS"]})],e.DecafMigrationModule);const ve="##VERSION##",we="##PACKAGE##";t.Metadata.allowReregistration(!0),t.Metadata.registerLibrary(we,ve),t.Metadata.allowReregistration(!1),e.AUTH_HANDLER=L,e.AUTH_META_KEY=K,e.ApiOperationFromModel=S,e.ApiParamsFromModel=T,e.ApiProperty=v,e.Auth=U,e.BulkApiOperationFromModel=(e,r,a)=>{const s={GET:[c.BulkCrudOperationKeys.READ_ALL,o.Get],POST:[c.BulkCrudOperationKeys.CREATE_ALL,o.Post],PUT:[c.BulkCrudOperationKeys.UPDATE_ALL,o.Put],PATCH:[c.BulkCrudOperationKeys.UPDATE_ALL,o.Patch],DELETE:[c.BulkCrudOperationKeys.DELETE_ALL,o.Delete]},[i,p]=s[r];return D(e,i)?t.apply(n.ApiExcludeEndpoint()):t.apply(p(a))},e.COMMIT="30f66ed",e.CorsError=le,e.DECAF_ADAPTER_ID=F,e.DECAF_ADAPTER_OPTIONS=j,e.DECAF_CONTEXT_KEY=B,e.DECAF_HANDLERS=N,e.DECAF_MODULE_OPTIONS=q,e.DECAF_ROUTE=k,e.DECORATORS=b,e.DECORATORS_PREFIX=A,e.DecafAuthHandler=H,e.DecafBody=C,e.DecafController=W,e.DecafModelController=Z,e.DecafParams=M,e.DecafQuery=I,e.DecafRoleAuthHandler=class extends H{constructor(){super()}async authorize(e,r){const o=e.switchToHttp().getRequest(),i=this.parseRequest(o);if(!i)throw new s.AuthorizationError("Unauthenticated");const n=t.Metadata.get(a.Model.get(r),s.PersistenceKeys.AUTH_ROLE);if(!n.includes(i))throw new s.AuthorizationError("Missing role: "+i);return n}},e.DtoFor=re,e.FULL_VERSION="0.9.0-30f66ed",e.FromModelController=pe,e.HttpVerbToDecorator=$,e.NestBootstraper=class{static get logger(){return this._logger||(this._logger=new o.Logger("NestBootstrap")),this._logger}static initialize(e){return this.app=e,this}static enableLogger(e){return this._logger=e||new o.Logger("NestBootstrap"),this.app.useLogger(this._logger),this}static enableCors(e=[],t=["GET","POST","PUT","DELETE"]){const r="*"===e?"*":e.map(e=>e.trim().toLowerCase()),o={origin:(e,t)=>e?"*"===r||Array.isArray(r)&&r.includes(e.toLowerCase())?t(null,!0):void t(new le(`Origin ${e} not allowed`)):t(null,!0),credentials:!0,methods:t.join(",")};return this.app.enableCors(o),this}static useHelmet(e){try{const t=require("helmet");this.app.use(t(e)),this.logger.log("Helmet middleware enabled successfully.")}catch(e){this.logger.warn("Helmet not installed. Skipping middleware.")}return this}static setupSwagger(e){return new fe(this.app,{title:e.title,description:e.description,version:e.version,path:e.path||"api",persistAuthorization:e.persistAuthorization??!0,assetsPath:e.assetsPath,faviconFilePath:e.faviconPath,topbarIconFilePath:e.topbarIconPath,topbarBgColor:e.topbarBgColor,openApiJsonPath:e.openApiJsonPath,openApiYamlPath:e.openApiYamlPath}).setupSwagger(),this}static useGlobalPipes(...e){return e.length>0&&this.app.useGlobalPipes(...e),this}static useGlobalFilters(...t){return this.app.useGlobalFilters(...t.length>0?t:[new e.DecafExceptionFilter]),this}static useGlobalInterceptors(...e){return e.length>0&&this.app.useGlobalInterceptors(...e),this}static async start(e=Number(process.env.PORT)||3e3,t=void 0,r=!0){this.app.listen(e,t).then(async()=>{if(r){const e=await this.app.getUrl();this.logger.log("\ud83d\ude80 Application is running at: "+e)}})}},e.PACKAGE_NAME=we,e.RequestToContextTransformer=class{},e.SwaggerBuilder=fe,e.UseDecafFilter=()=>o.UseFilters(new e.DecafExceptionFilter),e.UseDecafHeaders=()=>o.UseInterceptors(e.DecafResponseInterceptor),e.VERSION=ve,e.createApiPropertyDecorator=w,e.createPropertyDecorator=R,e.getEnumType=O,e.getEnumValues=P,e.getModuleFor=de,e.isOperationBlocked=D,e.isUndefined=E,e.repoForModel=e=>{const t=a.Model.get(e);if(!t)throw new c.InternalError("Failed to find repository for "+e);return s.Repository.forModel(t)},e.requestToContextTransformer=_e,e.runMigrations=async()=>{}},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/decoration"),require("@decaf-ts/injectable-decorators"),require("@nestjs/common"),require("@decaf-ts/decorator-validation"),require("@decaf-ts/core"),require("lodash"),require("@nestjs/swagger"),require("@decaf-ts/db-decorators"),require("tslib"),require("@nestjs/core"),require("@decaf-ts/logging"),require("rxjs"),require("fs"),require("path"),require("yaml"),require("rxjs/operators")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/decoration","@decaf-ts/injectable-decorators","@nestjs/common","@decaf-ts/decorator-validation","@decaf-ts/core","lodash","@nestjs/swagger","@decaf-ts/db-decorators","tslib","@nestjs/core","@decaf-ts/logging","rxjs","fs","path","yaml","rxjs/operators"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["for-nest"]={},e.decafTsDecoration,e.decafTsInjectableDecorators,e.nestjsCommon,e.decafTsDecoratorValidation,e.decafTsCore,e.lodash,e.nestjsSwagger,e.decafTsDbDecorators,e.tslib,e.nestjsCore,e.decafTsLogging,e.rxjs,e.fs,e.path,e.yaml,e.operators);
2
2
  //# sourceMappingURL=for-nest.cjs.map