@morojs/moro 1.7.30 → 1.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +89 -46
- package/dist/core/auth/morojs-adapter.js +95 -45
- package/dist/core/auth/morojs-adapter.js.map +1 -1
- package/dist/core/config/config-manager.js.map +1 -1
- package/dist/core/config/config-sources.js +119 -48
- package/dist/core/config/config-sources.js.map +1 -1
- package/dist/core/config/config-validator.js +189 -8
- package/dist/core/config/config-validator.js.map +1 -1
- package/dist/core/config/file-loader.js.map +1 -1
- package/dist/core/config/index.js.map +1 -1
- package/dist/core/config/schema.js +35 -4
- package/dist/core/config/schema.js.map +1 -1
- package/dist/core/config/utils.js.map +1 -1
- package/dist/core/database/adapters/drizzle.js +2 -2
- package/dist/core/database/adapters/drizzle.js.map +1 -1
- package/dist/core/database/adapters/index.js.map +1 -1
- package/dist/core/database/adapters/mongodb.d.ts +1 -0
- package/dist/core/database/adapters/mongodb.js +16 -0
- package/dist/core/database/adapters/mongodb.js.map +1 -1
- package/dist/core/database/adapters/mysql.d.ts +1 -0
- package/dist/core/database/adapters/mysql.js +13 -2
- package/dist/core/database/adapters/mysql.js.map +1 -1
- package/dist/core/database/adapters/postgresql.js +2 -2
- package/dist/core/database/adapters/postgresql.js.map +1 -1
- package/dist/core/database/adapters/redis.js.map +1 -1
- package/dist/core/database/adapters/sql-safety.js +5 -4
- package/dist/core/database/adapters/sql-safety.js.map +1 -1
- package/dist/core/database/adapters/sqlite.js.map +1 -1
- package/dist/core/database/index.js.map +1 -1
- package/dist/core/docs/index.js +11 -7
- package/dist/core/docs/index.js.map +1 -1
- package/dist/core/docs/openapi-generator.js +8 -6
- package/dist/core/docs/openapi-generator.js.map +1 -1
- package/dist/core/docs/schema-to-openapi.js +3 -3
- package/dist/core/docs/schema-to-openapi.js.map +1 -1
- package/dist/core/docs/simple-docs.js.map +1 -1
- package/dist/core/docs/swagger-ui.js.map +1 -1
- package/dist/core/docs/zod-to-openapi.js +2 -2
- package/dist/core/docs/zod-to-openapi.js.map +1 -1
- package/dist/core/events/event-bus.js +14 -5
- package/dist/core/events/event-bus.js.map +1 -1
- package/dist/core/events/index.js.map +1 -1
- package/dist/core/framework.d.ts +41 -3
- package/dist/core/framework.js +342 -95
- package/dist/core/framework.js.map +1 -1
- package/dist/core/graphql/adapter.js.map +1 -1
- package/dist/core/graphql/adapters/graphql-js-adapter.js.map +1 -1
- package/dist/core/graphql/core.js.map +1 -1
- package/dist/core/graphql/index.js.map +1 -1
- package/dist/core/graphql/loader.js.map +1 -1
- package/dist/core/graphql/types.js.map +1 -1
- package/dist/core/grpc/adapters/grpc-js-adapter.js +4 -0
- package/dist/core/grpc/adapters/grpc-js-adapter.js.map +1 -1
- package/dist/core/grpc/adapters/index.js.map +1 -1
- package/dist/core/grpc/grpc-adapter.js.map +1 -1
- package/dist/core/grpc/grpc-manager.js.map +1 -1
- package/dist/core/grpc/index.js.map +1 -1
- package/dist/core/grpc/middleware/auth.js +1 -1
- package/dist/core/grpc/middleware/auth.js.map +1 -1
- package/dist/core/grpc/middleware/logging.js.map +1 -1
- package/dist/core/grpc/middleware/validation.js +1 -1
- package/dist/core/grpc/middleware/validation.js.map +1 -1
- package/dist/core/grpc/types.d.ts +7 -7
- package/dist/core/grpc/types.js.map +1 -1
- package/dist/core/http/http-server.d.ts +17 -23
- package/dist/core/http/http-server.js +109 -249
- package/dist/core/http/http-server.js.map +1 -1
- package/dist/core/http/http2-server.d.ts +6 -16
- package/dist/core/http/http2-server.js +40 -83
- package/dist/core/http/http2-server.js.map +1 -1
- package/dist/core/http/index.d.ts +1 -0
- package/dist/core/http/index.js +3 -0
- package/dist/core/http/index.js.map +1 -1
- package/dist/core/http/moro-engine-server.d.ts +263 -0
- package/dist/core/http/moro-engine-server.js +1962 -0
- package/dist/core/http/moro-engine-server.js.map +1 -0
- package/dist/core/http/utils/compression.d.ts +47 -0
- package/dist/core/http/utils/compression.js +132 -0
- package/dist/core/http/utils/compression.js.map +1 -0
- package/dist/core/http/utils/lazy-event-emitter.d.ts +11 -0
- package/dist/core/http/utils/lazy-event-emitter.js +69 -0
- package/dist/core/http/utils/lazy-event-emitter.js.map +1 -0
- package/dist/core/http/utils/multipart-parser.d.ts +32 -0
- package/dist/core/http/utils/multipart-parser.js +215 -0
- package/dist/core/http/utils/multipart-parser.js.map +1 -0
- package/dist/core/http/utils/query-parser.d.ts +1 -0
- package/dist/core/http/utils/query-parser.js +44 -0
- package/dist/core/http/utils/query-parser.js.map +1 -0
- package/dist/core/http/utils/size.d.ts +33 -0
- package/dist/core/http/utils/size.js +37 -0
- package/dist/core/http/utils/size.js.map +1 -0
- package/dist/core/http/utils/ssl-config.d.ts +69 -0
- package/dist/core/http/utils/ssl-config.js +116 -0
- package/dist/core/http/utils/ssl-config.js.map +1 -0
- package/dist/core/http/utils/uws-worker-clustering.js +45 -32
- package/dist/core/http/utils/uws-worker-clustering.js.map +1 -1
- package/dist/core/http/uws-http-server.d.ts +25 -3
- package/dist/core/http/uws-http-server.js +465 -86
- package/dist/core/http/uws-http-server.js.map +1 -1
- package/dist/core/jobs/cron-parser.js +7 -5
- package/dist/core/jobs/cron-parser.js.map +1 -1
- package/dist/core/jobs/index.js.map +1 -1
- package/dist/core/jobs/job-executor.d.ts +1 -1
- package/dist/core/jobs/job-executor.js.map +1 -1
- package/dist/core/jobs/job-scheduler.d.ts +3 -3
- package/dist/core/jobs/job-scheduler.js.map +1 -1
- package/dist/core/jobs/job-state-manager.d.ts +3 -3
- package/dist/core/jobs/job-state-manager.js +25 -4
- package/dist/core/jobs/job-state-manager.js.map +1 -1
- package/dist/core/jobs/leader-election.d.ts +15 -0
- package/dist/core/jobs/leader-election.js +158 -69
- package/dist/core/jobs/leader-election.js.map +1 -1
- package/dist/core/jobs/types.d.ts +4 -4
- package/dist/core/jobs/types.js.map +1 -1
- package/dist/core/jobs/utils.d.ts +1 -1
- package/dist/core/jobs/utils.js +7 -3
- package/dist/core/jobs/utils.js.map +1 -1
- package/dist/core/logger/filters.js +3 -2
- package/dist/core/logger/filters.js.map +1 -1
- package/dist/core/logger/index.js.map +1 -1
- package/dist/core/logger/logger.js +56 -25
- package/dist/core/logger/logger.js.map +1 -1
- package/dist/core/logger/outputs.js.map +1 -1
- package/dist/core/mail/adapters/console-adapter.js.map +1 -1
- package/dist/core/mail/adapters/index.js.map +1 -1
- package/dist/core/mail/adapters/nodemailer-adapter.js.map +1 -1
- package/dist/core/mail/adapters/resend-adapter.js.map +1 -1
- package/dist/core/mail/adapters/sendgrid-adapter.js.map +1 -1
- package/dist/core/mail/adapters/ses-adapter.js.map +1 -1
- package/dist/core/mail/index.js.map +1 -1
- package/dist/core/mail/mail-adapter.js.map +1 -1
- package/dist/core/mail/mail-manager.d.ts +10 -0
- package/dist/core/mail/mail-manager.js +21 -5
- package/dist/core/mail/mail-manager.js.map +1 -1
- package/dist/core/mail/template-engine.js.map +1 -1
- package/dist/core/mail/types.js.map +1 -1
- package/dist/core/middleware/built-in/auth/core.js +3 -3
- package/dist/core/middleware/built-in/auth/core.js.map +1 -1
- package/dist/core/middleware/built-in/auth/helpers.js +4 -4
- package/dist/core/middleware/built-in/auth/helpers.js.map +1 -1
- package/dist/core/middleware/built-in/auth/hook.js.map +1 -1
- package/dist/core/middleware/built-in/auth/index.js.map +1 -1
- package/dist/core/middleware/built-in/auth/jwt-helpers.d.ts +4 -4
- package/dist/core/middleware/built-in/auth/jwt-helpers.js.map +1 -1
- package/dist/core/middleware/built-in/auth/middleware.js.map +1 -1
- package/dist/core/middleware/built-in/auth/providers.js.map +1 -1
- package/dist/core/middleware/built-in/body-parsers/index.js.map +1 -1
- package/dist/core/middleware/built-in/body-size/core.js +2 -2
- package/dist/core/middleware/built-in/body-size/core.js.map +1 -1
- package/dist/core/middleware/built-in/body-size/hook.js.map +1 -1
- package/dist/core/middleware/built-in/body-size/index.js.map +1 -1
- package/dist/core/middleware/built-in/body-size/middleware.js.map +1 -1
- package/dist/core/middleware/built-in/cache/adapters/cache/file.js +3 -1
- package/dist/core/middleware/built-in/cache/adapters/cache/file.js.map +1 -1
- package/dist/core/middleware/built-in/cache/adapters/cache/index.js.map +1 -1
- package/dist/core/middleware/built-in/cache/adapters/cache/memory.js.map +1 -1
- package/dist/core/middleware/built-in/cache/adapters/cache/redis.js.map +1 -1
- package/dist/core/middleware/built-in/cache/adapters/index.js.map +1 -1
- package/dist/core/middleware/built-in/cache/core.js.map +1 -1
- package/dist/core/middleware/built-in/cache/hook.js +3 -3
- package/dist/core/middleware/built-in/cache/hook.js.map +1 -1
- package/dist/core/middleware/built-in/cache/index.js.map +1 -1
- package/dist/core/middleware/built-in/cache/middleware.js.map +1 -1
- package/dist/core/middleware/built-in/cdn/adapters/cdn/azure.js.map +1 -1
- package/dist/core/middleware/built-in/cdn/adapters/cdn/cloudflare.js.map +1 -1
- package/dist/core/middleware/built-in/cdn/adapters/cdn/cloudfront.js.map +1 -1
- package/dist/core/middleware/built-in/cdn/adapters/cdn/index.js.map +1 -1
- package/dist/core/middleware/built-in/cdn/adapters/index.js.map +1 -1
- package/dist/core/middleware/built-in/cdn/core.js.map +1 -1
- package/dist/core/middleware/built-in/cdn/hook.js.map +1 -1
- package/dist/core/middleware/built-in/cdn/index.js.map +1 -1
- package/dist/core/middleware/built-in/cdn/middleware.js.map +1 -1
- package/dist/core/middleware/built-in/compression/core.d.ts +3 -0
- package/dist/core/middleware/built-in/compression/core.js +28 -34
- package/dist/core/middleware/built-in/compression/core.js.map +1 -1
- package/dist/core/middleware/built-in/compression/hook.js.map +1 -1
- package/dist/core/middleware/built-in/compression/index.js.map +1 -1
- package/dist/core/middleware/built-in/compression/middleware.js.map +1 -1
- package/dist/core/middleware/built-in/cookie/core.js.map +1 -1
- package/dist/core/middleware/built-in/cookie/hook.js.map +1 -1
- package/dist/core/middleware/built-in/cookie/index.js.map +1 -1
- package/dist/core/middleware/built-in/cookie/middleware.js.map +1 -1
- package/dist/core/middleware/built-in/cors/core.js.map +1 -1
- package/dist/core/middleware/built-in/cors/hook.js.map +1 -1
- package/dist/core/middleware/built-in/cors/index.js.map +1 -1
- package/dist/core/middleware/built-in/cors/middleware.js.map +1 -1
- package/dist/core/middleware/built-in/csp/core.js.map +1 -1
- package/dist/core/middleware/built-in/csp/hook.js.map +1 -1
- package/dist/core/middleware/built-in/csp/index.js.map +1 -1
- package/dist/core/middleware/built-in/csp/middleware.js.map +1 -1
- package/dist/core/middleware/built-in/csrf/core.js +1 -1
- package/dist/core/middleware/built-in/csrf/core.js.map +1 -1
- package/dist/core/middleware/built-in/csrf/hook.js.map +1 -1
- package/dist/core/middleware/built-in/csrf/index.js.map +1 -1
- package/dist/core/middleware/built-in/csrf/middleware.js.map +1 -1
- package/dist/core/middleware/built-in/error-tracker/index.js.map +1 -1
- package/dist/core/middleware/built-in/error-tracker/middleware.js.map +1 -1
- package/dist/core/middleware/built-in/graphql/core.js.map +1 -1
- package/dist/core/middleware/built-in/graphql/helpers.js.map +1 -1
- package/dist/core/middleware/built-in/graphql/hook.js.map +1 -1
- package/dist/core/middleware/built-in/graphql/index.js.map +1 -1
- package/dist/core/middleware/built-in/graphql/middleware.js.map +1 -1
- package/dist/core/middleware/built-in/graphql/subscriptions.js.map +1 -1
- package/dist/core/middleware/built-in/helmet/core.js.map +1 -1
- package/dist/core/middleware/built-in/helmet/hook.js.map +1 -1
- package/dist/core/middleware/built-in/helmet/index.js.map +1 -1
- package/dist/core/middleware/built-in/helmet/middleware.js.map +1 -1
- package/dist/core/middleware/built-in/http2/core.js.map +1 -1
- package/dist/core/middleware/built-in/http2/hook.js.map +1 -1
- package/dist/core/middleware/built-in/http2/index.js.map +1 -1
- package/dist/core/middleware/built-in/http2/middleware.js.map +1 -1
- package/dist/core/middleware/built-in/index.js.map +1 -1
- package/dist/core/middleware/built-in/performance-monitor/index.js.map +1 -1
- package/dist/core/middleware/built-in/performance-monitor/middleware.js.map +1 -1
- package/dist/core/middleware/built-in/range/core.js +4 -1
- package/dist/core/middleware/built-in/range/core.js.map +1 -1
- package/dist/core/middleware/built-in/range/hook.js.map +1 -1
- package/dist/core/middleware/built-in/range/index.js.map +1 -1
- package/dist/core/middleware/built-in/range/middleware.js.map +1 -1
- package/dist/core/middleware/built-in/rate-limit/core.js.map +1 -1
- package/dist/core/middleware/built-in/rate-limit/hook.js.map +1 -1
- package/dist/core/middleware/built-in/rate-limit/index.js.map +1 -1
- package/dist/core/middleware/built-in/rate-limit/middleware.js.map +1 -1
- package/dist/core/middleware/built-in/request-logger/index.js.map +1 -1
- package/dist/core/middleware/built-in/request-logger/middleware.js.map +1 -1
- package/dist/core/middleware/built-in/session/core.js +4 -4
- package/dist/core/middleware/built-in/session/core.js.map +1 -1
- package/dist/core/middleware/built-in/session/hook.js.map +1 -1
- package/dist/core/middleware/built-in/session/index.js.map +1 -1
- package/dist/core/middleware/built-in/session/middleware.js.map +1 -1
- package/dist/core/middleware/built-in/sse/core.js.map +1 -1
- package/dist/core/middleware/built-in/sse/hook.js.map +1 -1
- package/dist/core/middleware/built-in/sse/index.js.map +1 -1
- package/dist/core/middleware/built-in/sse/middleware.js.map +1 -1
- package/dist/core/middleware/built-in/static/core.js.map +1 -1
- package/dist/core/middleware/built-in/static/hook.js.map +1 -1
- package/dist/core/middleware/built-in/static/index.js.map +1 -1
- package/dist/core/middleware/built-in/static/middleware.js.map +1 -1
- package/dist/core/middleware/built-in/template/core.js +1 -1
- package/dist/core/middleware/built-in/template/core.js.map +1 -1
- package/dist/core/middleware/built-in/template/hook.js.map +1 -1
- package/dist/core/middleware/built-in/template/index.js.map +1 -1
- package/dist/core/middleware/built-in/template/middleware.js.map +1 -1
- package/dist/core/middleware/built-in/upload/core.js.map +1 -1
- package/dist/core/middleware/built-in/upload/hook.js.map +1 -1
- package/dist/core/middleware/built-in/upload/index.js.map +1 -1
- package/dist/core/middleware/built-in/upload/middleware.js.map +1 -1
- package/dist/core/middleware/built-in/validation/core.js.map +1 -1
- package/dist/core/middleware/built-in/validation/hook.js.map +1 -1
- package/dist/core/middleware/built-in/validation/index.js.map +1 -1
- package/dist/core/middleware/built-in/validation/middleware.js.map +1 -1
- package/dist/core/middleware/index.js +2 -2
- package/dist/core/middleware/index.js.map +1 -1
- package/dist/core/modules/auto-discovery.js +11 -7
- package/dist/core/modules/auto-discovery.js.map +1 -1
- package/dist/core/modules/index.js.map +1 -1
- package/dist/core/modules/modules.js +18 -13
- package/dist/core/modules/modules.js.map +1 -1
- package/dist/core/networking/adapters/engine-adapter.d.ts +23 -0
- package/dist/core/networking/adapters/engine-adapter.js +365 -0
- package/dist/core/networking/adapters/engine-adapter.js.map +1 -0
- package/dist/core/networking/adapters/index.d.ts +1 -0
- package/dist/core/networking/adapters/index.js +1 -0
- package/dist/core/networking/adapters/index.js.map +1 -1
- package/dist/core/networking/adapters/socketio-adapter.d.ts +1 -0
- package/dist/core/networking/adapters/socketio-adapter.js +12 -1
- package/dist/core/networking/adapters/socketio-adapter.js.map +1 -1
- package/dist/core/networking/adapters/uws-adapter.js +27 -16
- package/dist/core/networking/adapters/uws-adapter.js.map +1 -1
- package/dist/core/networking/adapters/ws-adapter.d.ts +15 -0
- package/dist/core/networking/adapters/ws-adapter.js +120 -6
- package/dist/core/networking/adapters/ws-adapter.js.map +1 -1
- package/dist/core/networking/index.js.map +1 -1
- package/dist/core/networking/service-discovery.js +7 -5
- package/dist/core/networking/service-discovery.js.map +1 -1
- package/dist/core/networking/websocket-adapter.d.ts +22 -3
- package/dist/core/networking/websocket-adapter.js.map +1 -1
- package/dist/core/networking/websocket-manager.js +70 -67
- package/dist/core/networking/websocket-manager.js.map +1 -1
- package/dist/core/pooling/object-pool-manager.js +6 -0
- package/dist/core/pooling/object-pool-manager.js.map +1 -1
- package/dist/core/queue/adapters/bull-adapter.js.map +1 -1
- package/dist/core/queue/adapters/index.js.map +1 -1
- package/dist/core/queue/adapters/kafka-adapter.js +2 -2
- package/dist/core/queue/adapters/kafka-adapter.js.map +1 -1
- package/dist/core/queue/adapters/memory-adapter.js +6 -6
- package/dist/core/queue/adapters/memory-adapter.js.map +1 -1
- package/dist/core/queue/adapters/rabbitmq-adapter.d.ts +50 -0
- package/dist/core/queue/adapters/rabbitmq-adapter.js +176 -20
- package/dist/core/queue/adapters/rabbitmq-adapter.js.map +1 -1
- package/dist/core/queue/adapters/sqs-adapter.d.ts +12 -2
- package/dist/core/queue/adapters/sqs-adapter.js +75 -24
- package/dist/core/queue/adapters/sqs-adapter.js.map +1 -1
- package/dist/core/queue/index.js.map +1 -1
- package/dist/core/queue/middleware/index.js.map +1 -1
- package/dist/core/queue/middleware/monitoring.d.ts +1 -1
- package/dist/core/queue/middleware/monitoring.js.map +1 -1
- package/dist/core/queue/middleware/priority.js +2 -1
- package/dist/core/queue/middleware/priority.js.map +1 -1
- package/dist/core/queue/middleware/rate-limit.js.map +1 -1
- package/dist/core/queue/queue-adapter.js.map +1 -1
- package/dist/core/queue/queue-manager.js.map +1 -1
- package/dist/core/queue/types.d.ts +8 -8
- package/dist/core/queue/types.js.map +1 -1
- package/dist/core/routing/app-integration.js.map +1 -1
- package/dist/core/routing/create-router.js.map +1 -1
- package/dist/core/routing/index.js.map +1 -1
- package/dist/core/routing/path-matcher.js.map +1 -1
- package/dist/core/routing/radix-tree.js.map +1 -1
- package/dist/core/routing/router.js.map +1 -1
- package/dist/core/routing/unified-router.js +12 -4
- package/dist/core/routing/unified-router.js.map +1 -1
- package/dist/core/runtime/aws-lambda-adapter.js.map +1 -1
- package/dist/core/runtime/base-adapter.js +2 -2
- package/dist/core/runtime/base-adapter.js.map +1 -1
- package/dist/core/runtime/cloudflare-workers-adapter.js +2 -0
- package/dist/core/runtime/cloudflare-workers-adapter.js.map +1 -1
- package/dist/core/runtime/index.js.map +1 -1
- package/dist/core/runtime/node-adapter.js +19 -17
- package/dist/core/runtime/node-adapter.js.map +1 -1
- package/dist/core/runtime/vercel-edge-adapter.js +2 -0
- package/dist/core/runtime/vercel-edge-adapter.js.map +1 -1
- package/dist/core/utilities/circuit-breaker.d.ts +1 -0
- package/dist/core/utilities/circuit-breaker.js +25 -2
- package/dist/core/utilities/circuit-breaker.js.map +1 -1
- package/dist/core/utilities/container.js +9 -9
- package/dist/core/utilities/container.js.map +1 -1
- package/dist/core/utilities/hooks.js +28 -6
- package/dist/core/utilities/hooks.js.map +1 -1
- package/dist/core/utilities/index.js.map +1 -1
- package/dist/core/utilities/module-path.js.map +1 -1
- package/dist/core/utilities/package-utils.d.ts +68 -0
- package/dist/core/utilities/package-utils.js +198 -1
- package/dist/core/utilities/package-utils.js.map +1 -1
- package/dist/core/utilities/response-helpers.js +1 -1
- package/dist/core/utilities/response-helpers.js.map +1 -1
- package/dist/core/validation/adapters.js.map +1 -1
- package/dist/core/validation/error-handler.js.map +1 -1
- package/dist/core/validation/index.js.map +1 -1
- package/dist/core/validation/schema-interface.js.map +1 -1
- package/dist/core/workers/facade.js.map +1 -1
- package/dist/core/workers/index.js.map +1 -1
- package/dist/core/workers/worker-entry.d.ts +1 -0
- package/dist/core/workers/worker-entry.js +12 -0
- package/dist/core/workers/worker-entry.js.map +1 -0
- package/dist/core/workers/worker-manager.d.ts +23 -2
- package/dist/core/workers/worker-manager.js +117 -17
- package/dist/core/workers/worker-manager.js.map +1 -1
- package/dist/core/workers/worker.js +8 -6
- package/dist/core/workers/worker.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +5 -2
- package/dist/index.js.map +1 -1
- package/dist/moro.d.ts +20 -1
- package/dist/moro.js +230 -70
- package/dist/moro.js.map +1 -1
- package/dist/types/auth.d.ts +4 -4
- package/dist/types/auth.js.map +1 -1
- package/dist/types/cache.js.map +1 -1
- package/dist/types/cdn.js.map +1 -1
- package/dist/types/config.d.ts +100 -15
- package/dist/types/config.js.map +1 -1
- package/dist/types/core.js.map +1 -1
- package/dist/types/database.js.map +1 -1
- package/dist/types/discovery.js.map +1 -1
- package/dist/types/events.js.map +1 -1
- package/dist/types/hooks.js.map +1 -1
- package/dist/types/http.js.map +1 -1
- package/dist/types/logger.js.map +1 -1
- package/dist/types/module.js.map +1 -1
- package/dist/types/runtime.js.map +1 -1
- package/dist/types/session.js.map +1 -1
- package/package.json +32 -17
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
// Package and Module Resolution Utilities
|
|
2
2
|
// ESM-compatible helpers for detecting and resolving optional dependencies
|
|
3
3
|
import { createRequire } from 'module';
|
|
4
|
-
import { join } from 'path';
|
|
4
|
+
import { dirname, join } from 'path';
|
|
5
|
+
import { existsSync, realpathSync } from 'fs';
|
|
5
6
|
import { pathToFileURL } from 'url';
|
|
6
7
|
/**
|
|
7
8
|
* Check if a package is available in the user's node_modules
|
|
@@ -55,6 +56,202 @@ export function resolveUserPackage(packageName) {
|
|
|
55
56
|
export function createUserRequire() {
|
|
56
57
|
return createRequire(join(process.cwd(), 'package.json'));
|
|
57
58
|
}
|
|
59
|
+
// ---------------------------------------------------------------------------
|
|
60
|
+
// Native HTTP engine loading
|
|
61
|
+
// ---------------------------------------------------------------------------
|
|
62
|
+
/**
|
|
63
|
+
* Package names probed for the native HTTP engine, in priority order.
|
|
64
|
+
* '@morojs/engine' is Moro's own engine (installed as an optionalDependency of
|
|
65
|
+
* the framework); 'uWebSockets.js' is honored as a legacy user-installed peer.
|
|
66
|
+
*/
|
|
67
|
+
export const NATIVE_ENGINE_PACKAGES = ['@morojs/engine', 'uWebSockets.js'];
|
|
68
|
+
const FRAMEWORK_PACKAGE_NAME = '@morojs/moro';
|
|
69
|
+
const NO_CAPABILITIES = {
|
|
70
|
+
limits: false,
|
|
71
|
+
tls: false,
|
|
72
|
+
http2: false,
|
|
73
|
+
wsDeflate: false,
|
|
74
|
+
};
|
|
75
|
+
const capabilitiesCache = new WeakMap();
|
|
76
|
+
/**
|
|
77
|
+
* Feature-detect a loaded engine module. Reads probe().capabilities when the
|
|
78
|
+
* engine exposes it (>= 1.1.0); otherwise everything is false so the framework
|
|
79
|
+
* passes only the options an older engine understood. uWS-style modules (no
|
|
80
|
+
* probe/serve) report all-false — their SSL/limits go through the uWS-specific
|
|
81
|
+
* paths, not these flags.
|
|
82
|
+
*/
|
|
83
|
+
export function getEngineCapabilities(module) {
|
|
84
|
+
const surface = module?.default || module;
|
|
85
|
+
if (!surface || typeof surface !== 'object')
|
|
86
|
+
return NO_CAPABILITIES;
|
|
87
|
+
const cached = capabilitiesCache.get(surface);
|
|
88
|
+
if (cached)
|
|
89
|
+
return cached;
|
|
90
|
+
let caps = NO_CAPABILITIES;
|
|
91
|
+
try {
|
|
92
|
+
if (typeof surface.probe === 'function') {
|
|
93
|
+
const probe = surface.probe();
|
|
94
|
+
const c = probe?.capabilities;
|
|
95
|
+
if (c && typeof c === 'object') {
|
|
96
|
+
caps = {
|
|
97
|
+
limits: c.limits === true,
|
|
98
|
+
tls: c.tls === true,
|
|
99
|
+
http2: c.http2 === true,
|
|
100
|
+
wsDeflate: c.wsDeflate === true,
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
caps = NO_CAPABILITIES;
|
|
107
|
+
}
|
|
108
|
+
capabilitiesCache.set(surface, caps);
|
|
109
|
+
return caps;
|
|
110
|
+
}
|
|
111
|
+
// undefined = never attempted, null = attempted and failed
|
|
112
|
+
let cachedEngine;
|
|
113
|
+
let engineLoadErrors = [];
|
|
114
|
+
/**
|
|
115
|
+
* Locate the installed framework package directory so the engine (a dependency
|
|
116
|
+
* of moro, not of the user's app) resolves under strict layouts like pnpm's.
|
|
117
|
+
* Walks up from cwd looking for node_modules/@morojs/moro, resolving symlinks
|
|
118
|
+
* so pnpm's store-linked layout anchors requires next to moro's own deps.
|
|
119
|
+
* Inside the framework repo itself (tests, examples) cwd is the framework dir.
|
|
120
|
+
*/
|
|
121
|
+
function findFrameworkAnchor() {
|
|
122
|
+
try {
|
|
123
|
+
const cwdPackageJson = join(process.cwd(), 'package.json');
|
|
124
|
+
if (existsSync(cwdPackageJson)) {
|
|
125
|
+
const require = createRequire(cwdPackageJson);
|
|
126
|
+
const name = require(cwdPackageJson)?.name;
|
|
127
|
+
if (name === FRAMEWORK_PACKAGE_NAME) {
|
|
128
|
+
return require;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
// fall through to the node_modules walk
|
|
134
|
+
}
|
|
135
|
+
let dir = process.cwd();
|
|
136
|
+
for (;;) {
|
|
137
|
+
const packageJson = join(dir, 'node_modules', '@morojs', 'moro', 'package.json');
|
|
138
|
+
try {
|
|
139
|
+
if (existsSync(packageJson)) {
|
|
140
|
+
return createRequire(join(realpathSync(dirname(packageJson)), 'package.json'));
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
// unreadable/broken link - keep walking up
|
|
145
|
+
}
|
|
146
|
+
const parent = dirname(dir);
|
|
147
|
+
if (parent === dir)
|
|
148
|
+
return null;
|
|
149
|
+
dir = parent;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Synchronously load the native HTTP engine, trying '@morojs/engine' first and
|
|
154
|
+
* falling back to a user-installed 'uWebSockets.js'. Loading is require-based
|
|
155
|
+
* (both packages are CJS at their core - .node addon loading is require-based),
|
|
156
|
+
* so the instance is shared with any later import() via the CJS module cache.
|
|
157
|
+
*
|
|
158
|
+
* The default call is memoized: the engine either loads once per process or it
|
|
159
|
+
* doesn't. Failure details are retained for logging via
|
|
160
|
+
* getNativeEngineLoadErrors().
|
|
161
|
+
*
|
|
162
|
+
* @param options.candidates - Override the probed package names (testing).
|
|
163
|
+
* When provided, the call bypasses the cache.
|
|
164
|
+
* @returns The loaded engine and its source package, or null if none loads
|
|
165
|
+
*/
|
|
166
|
+
export function loadNativeEngine(options) {
|
|
167
|
+
const useCache = !options?.candidates;
|
|
168
|
+
if (useCache && cachedEngine !== undefined) {
|
|
169
|
+
if (options?.collectErrors && !cachedEngine) {
|
|
170
|
+
options.collectErrors.push(...engineLoadErrors);
|
|
171
|
+
}
|
|
172
|
+
return cachedEngine;
|
|
173
|
+
}
|
|
174
|
+
const candidates = options?.candidates ?? NATIVE_ENGINE_PACKAGES;
|
|
175
|
+
const errors = [];
|
|
176
|
+
let result = null;
|
|
177
|
+
const frameworkRequire = findFrameworkAnchor();
|
|
178
|
+
const userRequire = createUserRequire();
|
|
179
|
+
for (const candidate of candidates) {
|
|
180
|
+
// Moro's own engine lives in moro's dependencies (framework anchor first);
|
|
181
|
+
// the legacy uWS peer dep lives in the user's node_modules (cwd first).
|
|
182
|
+
const anchors = candidate === 'uWebSockets.js'
|
|
183
|
+
? [userRequire, frameworkRequire]
|
|
184
|
+
: [frameworkRequire, userRequire];
|
|
185
|
+
for (const anchor of anchors) {
|
|
186
|
+
if (!anchor)
|
|
187
|
+
continue;
|
|
188
|
+
try {
|
|
189
|
+
const module = anchor(candidate);
|
|
190
|
+
// Capability check: the HTTP server needs either a uWS-style App()
|
|
191
|
+
// factory or the Moro-shaped engine surface (serve()/respond()).
|
|
192
|
+
// A package that loads but can't serve (e.g. a pre-M1 @morojs/engine
|
|
193
|
+
// that only exposes probe()) must not shadow a usable alternative.
|
|
194
|
+
const surface = module?.default || module;
|
|
195
|
+
const uwsStyle = typeof surface?.App === 'function';
|
|
196
|
+
const moroStyle = !uwsStyle &&
|
|
197
|
+
typeof surface?.serve === 'function' &&
|
|
198
|
+
typeof surface?.respond === 'function';
|
|
199
|
+
if (!uwsStyle && !moroStyle) {
|
|
200
|
+
errors.push(`${candidate}: loaded but provides neither App() nor serve()/respond() - not a usable HTTP engine`);
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
let version;
|
|
204
|
+
try {
|
|
205
|
+
// May be blocked by the package's exports map - version is optional
|
|
206
|
+
version = anchor(`${candidate}/package.json`)?.version;
|
|
207
|
+
}
|
|
208
|
+
catch {
|
|
209
|
+
version = undefined;
|
|
210
|
+
}
|
|
211
|
+
result = {
|
|
212
|
+
module,
|
|
213
|
+
source: candidate,
|
|
214
|
+
...(version !== undefined ? { version } : {}),
|
|
215
|
+
capabilities: moroStyle ? getEngineCapabilities(module) : NO_CAPABILITIES,
|
|
216
|
+
};
|
|
217
|
+
break;
|
|
218
|
+
}
|
|
219
|
+
catch (error) {
|
|
220
|
+
const message = error instanceof Error ? error.message.split('\n')[0] : String(error);
|
|
221
|
+
errors.push(`${candidate}: ${message}`);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
if (result)
|
|
225
|
+
break;
|
|
226
|
+
}
|
|
227
|
+
// Candidate-override probes (e.g. the clustering worker's uWS-only check)
|
|
228
|
+
// must not clobber the diagnostics of the real default load, which
|
|
229
|
+
// framework startup logging reads via getNativeEngineLoadErrors().
|
|
230
|
+
if (useCache) {
|
|
231
|
+
engineLoadErrors = result ? [] : [...new Set(errors)];
|
|
232
|
+
cachedEngine = result;
|
|
233
|
+
}
|
|
234
|
+
// Hand this specific call's failure detail back to a caller that asked for it,
|
|
235
|
+
// regardless of caching (so 'moro'/'uws' fallback reasons are precise).
|
|
236
|
+
if (options?.collectErrors && !result) {
|
|
237
|
+
options.collectErrors.push(...new Set(errors));
|
|
238
|
+
}
|
|
239
|
+
return result;
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Failure details from the most recent unsuccessful loadNativeEngine() call,
|
|
243
|
+
* one entry per package/anchor attempt. Empty after a successful load.
|
|
244
|
+
*/
|
|
245
|
+
export function getNativeEngineLoadErrors() {
|
|
246
|
+
return engineLoadErrors;
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Clear the memoized engine load result. Testing only.
|
|
250
|
+
*/
|
|
251
|
+
export function resetNativeEngineLoaderForTesting() {
|
|
252
|
+
cachedEngine = undefined;
|
|
253
|
+
engineLoadErrors = [];
|
|
254
|
+
}
|
|
58
255
|
/**
|
|
59
256
|
* Convert a file path to a file URL for ESM dynamic imports
|
|
60
257
|
* This is required on Windows where absolute paths like C:\path\to\module
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"package-utils.js","sour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ACpD,MAAM,iBAAiB,GAAG,wBAAwB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAElE,qDAAqD;IACrD,MAAM,cAAc,GAAG,QAAQ,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;IAEhD,oDAAoD;IACpD,MAAM,YAAY,GAAG,QAAQ,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;IAEjD,sCAAsC;IACtC,IAAI,iBAAiB,IAAI,cAAc,IAAI,YAAY,EAAE,CAAC;QACxD,OAAO,aAAa,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC;IACtC,CAAC;IAED,2DAA2D;IAC3D,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["// Package and Module Resolution Utilities\n// ESM-compatible helpers for detecting and resolving optional dependencies\n\nimport { createRequire } from 'module';\nimport { dirname, join } from 'path';\nimport { existsSync, realpathSync } from 'fs';\nimport { pathToFileURL } from 'url';\n\n/**\n * Check if a package is available in the user's node_modules\n * Uses ESM-compatible module resolution from the user's working directory\n *\n * @param packageName - The name of the package to check (e.g., 'socket.io', 'zod')\n * @returns true if the package is installed, false otherwise\n *\n * @example\n * if (isPackageAvailable('socket.io')) {\n * // socket.io is installed, safe to import\n * const { Server } = await import('socket.io');\n * }\n */\nexport function isPackageAvailable(packageName: string): boolean {\n try {\n const userRequire = createRequire(join(process.cwd(), 'package.json'));\n userRequire.resolve(packageName);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Resolve a package path from the user's node_modules\n * Uses ESM-compatible module resolution from the user's working directory\n *\n * @param packageName - The name of the package to resolve\n * @returns The resolved package path\n * @throws Error if the package is not found\n *\n * @example\n * const socketIOPath = resolveUserPackage('socket.io');\n * const { Server } = await import(socketIOPath);\n */\nexport function resolveUserPackage(packageName: string): string {\n const userRequire = createRequire(join(process.cwd(), 'package.json'));\n return userRequire.resolve(packageName);\n}\n\n/**\n * Create a require function for the user's working directory\n * Useful for resolving packages installed by the user, not in Moro's dependencies\n *\n * @returns A require function scoped to the user's working directory\n *\n * @example\n * const userRequire = createUserRequire();\n * const packagePath = userRequire.resolve('some-package');\n */\nexport function createUserRequire() {\n return createRequire(join(process.cwd(), 'package.json'));\n}\n\n// ---------------------------------------------------------------------------\n// Native HTTP engine loading\n// ---------------------------------------------------------------------------\n\n/**\n * Package names probed for the native HTTP engine, in priority order.\n * '@morojs/engine' is Moro's own engine (installed as an optionalDependency of\n * the framework); 'uWebSockets.js' is honored as a legacy user-installed peer.\n */\nexport const NATIVE_ENGINE_PACKAGES = ['@morojs/engine', 'uWebSockets.js'] as const;\n\nconst FRAMEWORK_PACKAGE_NAME = '@morojs/moro';\n\n/** Feature flags the framework gates option-passing on, so it never hands a\n * serve() option to an engine build that predates it. Everything defaults\n * false, so an older engine behaves exactly as it did before these existed. */\nexport interface EngineCapabilities {\n /** The full serve() limit surface is parsed (engine >= 1.1.0). */\n limits: boolean;\n /** In-process TLS termination via options.ssl (engine >= 1.2.0). */\n tls: boolean;\n /** ALPN HTTP/2 via options.http2 (engine >= 1.4.0). */\n http2: boolean;\n /** WebSocket permessage-deflate via options.wsDeflate (engine >= 1.5.0). */\n wsDeflate: boolean;\n}\n\nexport interface NativeEngineLoadResult {\n /** The loaded engine module (CJS namespace: App, SSLApp, ...) */\n module: any;\n /** Which package satisfied the load */\n source: string;\n /** The engine package's version, when its package.json is resolvable */\n version?: string;\n /** Feature flags (Moro-shaped engine only; all-false for uWS or an\n * engine too old to advertise them). */\n capabilities?: EngineCapabilities;\n}\n\nconst NO_CAPABILITIES: EngineCapabilities = {\n limits: false,\n tls: false,\n http2: false,\n wsDeflate: false,\n};\n\nconst capabilitiesCache = new WeakMap<object, EngineCapabilities>();\n\n/**\n * Feature-detect a loaded engine module. Reads probe().capabilities when the\n * engine exposes it (>= 1.1.0); otherwise everything is false so the framework\n * passes only the options an older engine understood. uWS-style modules (no\n * probe/serve) report all-false — their SSL/limits go through the uWS-specific\n * paths, not these flags.\n */\nexport function getEngineCapabilities(module: any): EngineCapabilities {\n const surface = module?.default || module;\n if (!surface || typeof surface !== 'object') return NO_CAPABILITIES;\n const cached = capabilitiesCache.get(surface);\n if (cached) return cached;\n\n let caps: EngineCapabilities = NO_CAPABILITIES;\n try {\n if (typeof surface.probe === 'function') {\n const probe = surface.probe();\n const c = probe?.capabilities;\n if (c && typeof c === 'object') {\n caps = {\n limits: c.limits === true,\n tls: c.tls === true,\n http2: c.http2 === true,\n wsDeflate: c.wsDeflate === true,\n };\n }\n }\n } catch {\n caps = NO_CAPABILITIES;\n }\n capabilitiesCache.set(surface, caps);\n return caps;\n}\n\n// undefined = never attempted, null = attempted and failed\nlet cachedEngine: NativeEngineLoadResult | null | undefined;\nlet engineLoadErrors: string[] = [];\n\n/**\n * Locate the installed framework package directory so the engine (a dependency\n * of moro, not of the user's app) resolves under strict layouts like pnpm's.\n * Walks up from cwd looking for node_modules/@morojs/moro, resolving symlinks\n * so pnpm's store-linked layout anchors requires next to moro's own deps.\n * Inside the framework repo itself (tests, examples) cwd is the framework dir.\n */\nfunction findFrameworkAnchor(): ReturnType<typeof createRequire> | null {\n try {\n const cwdPackageJson = join(process.cwd(), 'package.json');\n if (existsSync(cwdPackageJson)) {\n const require = createRequire(cwdPackageJson);\n const name = require(cwdPackageJson)?.name;\n if (name === FRAMEWORK_PACKAGE_NAME) {\n return require;\n }\n }\n } catch {\n // fall through to the node_modules walk\n }\n\n let dir = process.cwd();\n for (;;) {\n const packageJson = join(dir, 'node_modules', '@morojs', 'moro', 'package.json');\n try {\n if (existsSync(packageJson)) {\n return createRequire(join(realpathSync(dirname(packageJson)), 'package.json'));\n }\n } catch {\n // unreadable/broken link - keep walking up\n }\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n/**\n * Synchronously load the native HTTP engine, trying '@morojs/engine' first and\n * falling back to a user-installed 'uWebSockets.js'. Loading is require-based\n * (both packages are CJS at their core - .node addon loading is require-based),\n * so the instance is shared with any later import() via the CJS module cache.\n *\n * The default call is memoized: the engine either loads once per process or it\n * doesn't. Failure details are retained for logging via\n * getNativeEngineLoadErrors().\n *\n * @param options.candidates - Override the probed package names (testing).\n * When provided, the call bypasses the cache.\n * @returns The loaded engine and its source package, or null if none loads\n */\nexport function loadNativeEngine(options?: {\n candidates?: readonly string[];\n /** When provided, every per-attempt failure message is appended here, so a\n * candidate-override caller (which bypasses the memoized diagnostics) can\n * still report exactly WHY the engine didn't load — not just \"not installed\". */\n collectErrors?: string[];\n}): NativeEngineLoadResult | null {\n const useCache = !options?.candidates;\n if (useCache && cachedEngine !== undefined) {\n if (options?.collectErrors && !cachedEngine) {\n options.collectErrors.push(...engineLoadErrors);\n }\n return cachedEngine;\n }\n\n const candidates = options?.candidates ?? NATIVE_ENGINE_PACKAGES;\n const errors: string[] = [];\n let result: NativeEngineLoadResult | null = null;\n\n const frameworkRequire = findFrameworkAnchor();\n const userRequire = createUserRequire();\n\n for (const candidate of candidates) {\n // Moro's own engine lives in moro's dependencies (framework anchor first);\n // the legacy uWS peer dep lives in the user's node_modules (cwd first).\n const anchors =\n candidate === 'uWebSockets.js'\n ? [userRequire, frameworkRequire]\n : [frameworkRequire, userRequire];\n\n for (const anchor of anchors) {\n if (!anchor) continue;\n try {\n const module = anchor(candidate);\n // Capability check: the HTTP server needs either a uWS-style App()\n // factory or the Moro-shaped engine surface (serve()/respond()).\n // A package that loads but can't serve (e.g. a pre-M1 @morojs/engine\n // that only exposes probe()) must not shadow a usable alternative.\n const surface = module?.default || module;\n const uwsStyle = typeof surface?.App === 'function';\n const moroStyle =\n !uwsStyle &&\n typeof surface?.serve === 'function' &&\n typeof surface?.respond === 'function';\n if (!uwsStyle && !moroStyle) {\n errors.push(\n `${candidate}: loaded but provides neither App() nor serve()/respond() - not a usable HTTP engine`\n );\n continue;\n }\n let version: string | undefined;\n try {\n // May be blocked by the package's exports map - version is optional\n version = anchor(`${candidate}/package.json`)?.version;\n } catch {\n version = undefined;\n }\n result = {\n module,\n source: candidate,\n ...(version !== undefined ? { version } : {}),\n capabilities: moroStyle ? getEngineCapabilities(module) : NO_CAPABILITIES,\n };\n break;\n } catch (error) {\n const message = error instanceof Error ? error.message.split('\\n')[0] : String(error);\n errors.push(`${candidate}: ${message}`);\n }\n }\n if (result) break;\n }\n\n // Candidate-override probes (e.g. the clustering worker's uWS-only check)\n // must not clobber the diagnostics of the real default load, which\n // framework startup logging reads via getNativeEngineLoadErrors().\n if (useCache) {\n engineLoadErrors = result ? [] : [...new Set(errors)];\n cachedEngine = result;\n }\n // Hand this specific call's failure detail back to a caller that asked for it,\n // regardless of caching (so 'moro'/'uws' fallback reasons are precise).\n if (options?.collectErrors && !result) {\n options.collectErrors.push(...new Set(errors));\n }\n return result;\n}\n\n/**\n * Failure details from the most recent unsuccessful loadNativeEngine() call,\n * one entry per package/anchor attempt. Empty after a successful load.\n */\nexport function getNativeEngineLoadErrors(): readonly string[] {\n return engineLoadErrors;\n}\n\n/**\n * Clear the memoized engine load result. Testing only.\n */\nexport function resetNativeEngineLoaderForTesting(): void {\n cachedEngine = undefined;\n engineLoadErrors = [];\n}\n\n/**\n * Convert a file path to a file URL for ESM dynamic imports\n * This is required on Windows where absolute paths like C:\\path\\to\\module\n * need to be converted to file:/// URLs for dynamic import() to work\n *\n * @param filePath - The file path to convert (absolute or relative)\n * @returns A proper URL string for ESM import() that works cross-platform\n *\n * @example\n * const modulePath = 'C:\\\\Users\\\\project\\\\module.js';\n * const module = await import(filePathToImportURL(modulePath));\n */\nexport function filePathToImportURL(filePath: string): string {\n if (!filePath) {\n return filePath;\n }\n\n // If it's already a URL (starts with file:// or http(s)://), return as-is\n if (\n filePath.startsWith('file://') ||\n filePath.startsWith('http://') ||\n filePath.startsWith('https://')\n ) {\n return filePath;\n }\n\n // Check if it's a Windows absolute path (C:\\ or C:/)\n const windowsAbsolutePathRegex = /^[A-Za-z]:[\\\\//]/;\n const isWindowsAbsolute = windowsAbsolutePathRegex.test(filePath);\n\n // Check if it's a Unix absolute path (starts with /)\n const isUnixAbsolute = filePath.startsWith('/');\n\n // Check if it's a Windows UNC path (\\\\server\\share)\n const isWindowsUNC = filePath.startsWith('\\\\\\\\');\n\n // Convert absolute paths to file URLs\n if (isWindowsAbsolute || isUnixAbsolute || isWindowsUNC) {\n return pathToFileURL(filePath).href;\n }\n\n // For relative paths, return as-is (they work in import())\n return filePath;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"response-helpers.js","sourceRoot":"","sources":["../../../src/core/utilities/response-helpers.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAoCH;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,UAAU,OAAO,CAAU,IAAO,EAAE,OAAgB;IACxD,MAAM,QAAQ,GAA0B;QACtC,OAAO,EAAE,IAAI;QACb,IAAI;KACL,CAAC;IAEF,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;QAC1B,QAAQ,CAAC,OAAO,GAAG,OAAO,CAAC;IAC7B,CAAC;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,KAAK,CAAC,YAAoB,EAAE,IAAa,EAAE,OAAgB;IACzE,MAAM,QAAQ,GAAqB;QACjC,OAAO,EAAE,KAAK;QACd,KAAK,EAAE,YAAY;KACpB,CAAC;IAEF,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;QACvB,QAAQ,CAAC,IAAI,GAAG,IAAI,CAAC;IACvB,CAAC;IAED,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;QAC1B,QAAQ,CAAC,OAAO,GAAG,OAAO,CAAC;IAC7B,CAAC;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,eAAe,CAC7B,OAAgC,EAChC,OAAgB;IAEhB,OAAO;QACL,OAAO,EAAE,KAAK;QACd,KAAK,EAAE,mBAAmB;QAC1B,IAAI,EAAE,kBAAkB;QACxB,OAAO,EAAE,OAAO,IAAI,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;QACjB,IAAI,CAAC,QAA6B,CAAC,OAAO,GAAG,OAAO,CAAC;QACtD,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;OAEG;IACH,IAAI,CAAC,IAAY;QACd,IAAI,CAAC,QAA6B,CAAC,IAAI,GAAG,IAAI,CAAC;QAChD,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;OAEG;IACH,KAAK;QACH,OAAO,IAAI,CAAC,QAA0B,CAAC;IACzC,CAAC;CACF"}
|
|
1
|
+
{"version":3,"file":"response-helpers.js","sourceRoot":"","sources":["../../../src/core/utilities/response-helpers.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAoCH;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,UAAU,OAAO,CAAU,IAAO,EAAE,OAAgB;IACxD,MAAM,QAAQ,GAA0B;QACtC,OAAO,EAAE,IAAI;QACb,IAAI;KACL,CAAC;IAEF,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;QAC1B,QAAQ,CAAC,OAAO,GAAG,OAAO,CAAC;IAC7B,CAAC;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,KAAK,CAAC,YAAoB,EAAE,IAAa,EAAE,OAAgB;IACzE,MAAM,QAAQ,GAAqB;QACjC,OAAO,EAAE,KAAK;QACd,KAAK,EAAE,YAAY;KACpB,CAAC;IAEF,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;QACvB,QAAQ,CAAC,IAAI,GAAG,IAAI,CAAC;IACvB,CAAC;IAED,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;QAC1B,QAAQ,CAAC,OAAO,GAAG,OAAO,CAAC;IAC7B,CAAC;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,eAAe,CAC7B,OAAgC,EAChC,OAAgB;IAEhB,OAAO;QACL,OAAO,EAAE,KAAK;QACd,KAAK,EAAE,mBA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OAEG;IACH,OAAO,CAAC,GAAW;QACjB,IAAI,CAAC,QAAQ,CAAC,OAAO,GAAG,GAAG,CAAC;QAC5B,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;OAEG;IACH,OAAO,CAAC,OAAY;QACjB,IAAI,CAAC,QAA6B,CAAC,OAAO,GAAG,OAAO,CAAC;QACtD,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;OAEG;IACH,IAAI,CAAC,IAAY;QACd,IAAI,CAAC,QAA6B,CAAC,IAAI,GAAG,IAAI,CAAC;QAChD,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;OAEG;IACH,KAAK;QACH,OAAO,IAAI,CAAC,QAA0B,CAAC;IACzC,CAAC;CACF","sourcesContent":["/**\n * Standardized API Response Helpers\n *\n * These helpers ensure consistent response formats across your API.\n * They are zero-overhead (just return plain objects) and optimized\n * for the framework's fast-path JSON serialization.\n *\n * @module ResponseHelpers\n */\n\n/**\n * Standard success response with data\n */\nexport interface ApiSuccessResponse<T = any> {\n success: true;\n data: T;\n message?: string;\n}\n\n/**\n * Standard error response\n */\nexport interface ApiErrorResponse {\n success: false;\n error: string;\n code?: string;\n message?: string;\n details?: any;\n}\n\n/**\n * Union type for all API responses\n */\nexport type ApiResponse<T = any> = ApiSuccessResponse<T> | ApiErrorResponse;\n\n/**\n * Validation error detail\n */\nexport interface ValidationErrorDetail {\n field: string;\n message: string;\n code?: string;\n}\n\n/**\n * Create a standardized success response\n *\n * @example\n * ```typescript\n * app.get('/users', async (req, res) => {\n * const users = await getUsers();\n * return success(users);\n * });\n *\n * // With message\n * app.post('/users', async (req, res) => {\n * const user = await createUser(req.body);\n * return success(user, 'User created successfully');\n * });\n * ```\n */\nexport function success<T = any>(data: T, message?: string): ApiSuccessResponse<T> {\n const response: ApiSuccessResponse<T> = {\n success: true,\n data,\n };\n\n if (message !== undefined) {\n response.message = message;\n }\n\n return response;\n}\n\n/**\n * Create a standardized error response\n *\n * @example\n * ```typescript\n * app.get('/users/:id', async (req, res) => {\n * const user = await getUser(req.params.id);\n * if (!user) {\n * return res.status(404).json(\n * error('User not found', 'USER_NOT_FOUND')\n * );\n * }\n * return success(user);\n * });\n * ```\n */\nexport function error(errorMessage: string, code?: string, message?: string): ApiErrorResponse {\n const response: ApiErrorResponse = {\n success: false,\n error: errorMessage,\n };\n\n if (code !== undefined) {\n response.code = code;\n }\n\n if (message !== undefined) {\n response.message = message;\n }\n\n return response;\n}\n\n/**\n * Create a validation error response\n *\n * @example\n * ```typescript\n * app.post('/users', async (req, res) => {\n * const validationErrors = validateUser(req.body);\n * if (validationErrors.length > 0) {\n * return res.status(400).json(\n * validationError(validationErrors)\n * );\n * }\n * // ... create user\n * });\n * ```\n */\nexport function validationError(\n details: ValidationErrorDetail[],\n message?: string\n): ApiErrorResponse {\n return {\n success: false,\n error: 'Validation failed',\n code: 'VALIDATION_ERROR',\n message: message || 'One or more fields failed validation',\n details,\n };\n}\n\n/**\n * Create an unauthorized error response\n *\n * @example\n * ```typescript\n * app.get('/admin', async (req, res) => {\n * if (!req.user) {\n * return res.status(401).json(unauthorized());\n * }\n * return success(adminData);\n * });\n * ```\n */\nexport function unauthorized(message: string = 'Authentication required'): ApiErrorResponse {\n return {\n success: false,\n error: 'Unauthorized',\n code: 'UNAUTHORIZED',\n message,\n };\n}\n\n/**\n * Create a forbidden error response\n *\n * @example\n * ```typescript\n * app.delete('/users/:id', async (req, res) => {\n * if (!req.user.roles.includes('admin')) {\n * return res.status(403).json(forbidden());\n * }\n * await deleteUser(req.params.id);\n * return success({ deleted: true });\n * });\n * ```\n */\nexport function forbidden(message: string = 'Insufficient permissions'): ApiErrorResponse {\n return {\n success: false,\n error: 'Forbidden',\n code: 'FORBIDDEN',\n message,\n };\n}\n\n/**\n * Create a not found error response\n *\n * @example\n * ```typescript\n * app.get('/users/:id', async (req, res) => {\n * const user = await getUser(req.params.id);\n * if (!user) {\n * return res.status(404).json(notFound('User'));\n * }\n * return success(user);\n * });\n * ```\n */\nexport function notFound(resource: string = 'Resource'): ApiErrorResponse {\n return {\n success: false,\n error: 'Not Found',\n code: 'NOT_FOUND',\n message: `${resource} not found`,\n };\n}\n\n/**\n * Create a conflict error response (e.g., duplicate entry)\n *\n * @example\n * ```typescript\n * app.post('/users', async (req, res) => {\n * const existing = await getUserByEmail(req.body.email);\n * if (existing) {\n * return res.status(409).json(\n * conflict('Email already in use')\n * );\n * }\n * const user = await createUser(req.body);\n * return success(user);\n * });\n * ```\n */\nexport function conflict(message: string): ApiErrorResponse {\n return {\n success: false,\n error: 'Conflict',\n code: 'CONFLICT',\n message,\n };\n}\n\n/**\n * Create a bad request error response\n *\n * @example\n * ```typescript\n * app.post('/upload', async (req, res) => {\n * if (!req.files?.file) {\n * return res.status(400).json(\n * badRequest('File is required')\n * );\n * }\n * // ... process file\n * });\n * ```\n */\nexport function badRequest(message: string = 'Invalid request'): ApiErrorResponse {\n return {\n success: false,\n error: 'Bad Request',\n code: 'BAD_REQUEST',\n message,\n };\n}\n\n/**\n * Create an internal server error response\n *\n * @example\n * ```typescript\n * app.get('/data', async (req, res) => {\n * try {\n * const data = await fetchData();\n * return success(data);\n * } catch (err) {\n * return res.status(500).json(\n * internalError('Failed to fetch data')\n * );\n * }\n * });\n * ```\n */\nexport function internalError(message: string = 'Internal server error'): ApiErrorResponse {\n return {\n success: false,\n error: 'Internal Server Error',\n code: 'INTERNAL_ERROR',\n message,\n };\n}\n\n/**\n * Create a rate limit exceeded error response\n *\n * @example\n * ```typescript\n * app.post('/api/send', async (req, res) => {\n * const limited = await checkRateLimit(req.ip);\n * if (limited) {\n * return res.status(429).json(\n * rateLimited(60) // 60 seconds retry\n * );\n * }\n * // ... process request\n * });\n * ```\n */\nexport function rateLimited(retryAfter?: number): ApiErrorResponse {\n const response: ApiErrorResponse = {\n success: false,\n error: 'Too Many Requests',\n code: 'RATE_LIMITED',\n message: 'Rate limit exceeded',\n };\n\n if (retryAfter !== undefined) {\n response.details = { retryAfter };\n }\n\n return response;\n}\n\n/**\n * Standardized response helper object for convenient imports\n *\n * @example\n * ```typescript\n * import { response } from '@morojs/moro';\n *\n * app.get('/users', async (req, res) => {\n * const users = await getUsers();\n * return response.success(users);\n * });\n *\n * app.get('/users/:id', async (req, res) => {\n * const user = await getUser(req.params.id);\n * if (!user) {\n * return res.status(404).json(response.notFound('User'));\n * }\n * return response.success(user);\n * });\n * ```\n */\nexport const response = {\n success,\n error,\n validationError,\n unauthorized,\n forbidden,\n notFound,\n conflict,\n badRequest,\n internalError,\n rateLimited,\n} as const;\n\n/**\n * Type-safe response builder for complex scenarios\n *\n * @example\n * ```typescript\n * import { ResponseBuilder } from '@morojs/moro';\n *\n * app.get('/users', async (req, res) => {\n * const users = await getUsers();\n * return ResponseBuilder.success(users)\n * .message('Successfully retrieved users')\n * .build();\n * });\n * ```\n */\nexport class ResponseBuilder<T = any> {\n private response: Partial<ApiResponse<T>> = {};\n\n private constructor() {}\n\n /**\n * Start building a success response\n */\n static success<T>(data: T): ResponseBuilder<T> {\n const builder = new ResponseBuilder<T>();\n builder.response = {\n success: true,\n data,\n };\n return builder;\n }\n\n /**\n * Start building an error response\n */\n static error(errorMessage: string, code?: string): ResponseBuilder<never> {\n const builder = new ResponseBuilder<never>();\n builder.response = {\n success: false,\n error: errorMessage,\n ...(code !== undefined ? { code } : {}),\n };\n return builder;\n }\n\n /**\n * Add a message to the response\n */\n message(msg: string): this {\n this.response.message = msg;\n return this;\n }\n\n /**\n * Add details to the response\n */\n details(details: any): this {\n (this.response as ApiErrorResponse).details = details;\n return this;\n }\n\n /**\n * Add a code to error response\n */\n code(code: string): this {\n (this.response as ApiErrorResponse).code = code;\n return this;\n }\n\n /**\n * Build and return the final response\n */\n build(): ApiResponse<T> {\n return this.response as ApiResponse<T>;\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adapters.js","sourceRoot":"","sources":["../../../src/core/validation/adapters.ts"],"names":[],"mappings":"AAAA,iDAAiD;AACjD,iFAAiF;AAEjF,O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AM,GAAG,CAAC,EAAE,CAAC;oBAChC,MAAM,IAAI,eAAe,CACvB,MAAM,CAAC,GAAG,CAAC,CAAC,KAAU,EAAE,KAAa,EAAE,EAAE,CAAC,CAAC;wBACzC,IAAI,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;wBACjD,OAAO,EAAE,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,WAAW,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,mBAAmB;wBACjF,IAAI,EAAE,iBAAiB;qBACxB,CAAC,CAAC,CACJ,CAAC;gBACJ,CAAC;YACH,CAAC;YAED,OAAO,QAAa,CAAC;QACvB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,KAAK,YAAY,eAAe;gBAAE,MAAM,KAAK,CAAC;YAClD,MAAM,wBAAwB,CAAC,KAAK,CAAC,CAAC;QACxC,CAAC;IACH,CAAC;CACF;AAED;;GAEG;AACH,MAAM,UAAU,GAAG,CAAU,SAAc;IACzC,OAAO,IAAI,UAAU,CAAI,SAAS,CAAC,CAAC;AACtC,CAAC;AAED,MAAM,UAAU,GAAG,CAAU,SAAc;IACzC,OAAO,IAAI,UAAU,CAAI,SAAS,CAAC,CAAC;AACtC,CAAC;AAED,MAAM,UAAU,EAAE,CAChB,UAA6C,EAC7C,IAAa;IAEb,OAAO,IAAI,eAAe,CAAI,UAAU,EAAE,IAAI,CAAC,CAAC;AAClD,CAAC;AAED,MAAM,UAAU,cAAc,CAC5B,SAAsB,EACtB,QAAuC;IAEvC,OAAO,IAAI,qBAAqB,CAAI,SAAS,EAAE,QAAQ,CAAC,CAAC;AAC3D,CAAC","sourcesContent":["// Validation Library Adapters for Moro Framework\n// Makes Joi, Yup, and other libraries compatible with ValidationSchema interface\n\nimport { ValidationSchema, ValidationError, normalizeValidationError } from './schema-interface.js';\n\n/**\n * Zod Compatibility Check\n * Zod ALREADY implements ValidationSchema interface natively!\n * No adapter needed - it just works.\n */\n\n/**\n * Joi Adapter - makes Joi schemas compatible with ValidationSchema\n */\nexport class JoiAdapter<T = any> implements ValidationSchema<T> {\n constructor(private joiSchema: any) {\n if (!joiSchema || typeof joiSchema.validateAsync !== 'function') {\n throw new Error('Invalid Joi schema provided to JoiAdapter');\n }\n }\n\n async parseAsync(data: unknown): Promise<T> {\n try {\n const result = await this.joiSchema.validateAsync(data, { abortEarly: false });\n return result as T;\n } catch (error) {\n throw normalizeValidationError(error);\n }\n }\n}\n\n/**\n * Yup Adapter - makes Yup schemas compatible with ValidationSchema\n */\nexport class YupAdapter<T = any> implements ValidationSchema<T> {\n constructor(private yupSchema: any) {\n if (!yupSchema || typeof yupSchema.validate !== 'function') {\n throw new Error('Invalid Yup schema provided to YupAdapter');\n }\n }\n\n async parseAsync(data: unknown): Promise<T> {\n try {\n const result = await this.yupSchema.validate(data, { abortEarly: false });\n return result as T;\n } catch (error) {\n throw normalizeValidationError(error);\n }\n }\n}\n\n/**\n * Custom Validation Function Adapter\n * Allows users to use simple validation functions\n */\nexport class FunctionAdapter<T = any> implements ValidationSchema<T> {\n constructor(\n private validateFn: (data: unknown) => T | Promise<T>,\n private name: string = 'custom'\n ) {\n if (typeof validateFn !== 'function') {\n throw new Error('Validation function is required for FunctionAdapter');\n }\n }\n\n async parseAsync(data: unknown): Promise<T> {\n try {\n return await this.validateFn(data);\n } catch (error) {\n throw new ValidationError([\n {\n path: [],\n message: error instanceof Error ? error.message : String(error),\n code: this.name,\n },\n ]);\n }\n }\n}\n\n/**\n * Class Validator Adapter (for TypeScript decorators)\n */\nexport class ClassValidatorAdapter<T extends object = any> implements ValidationSchema<T> {\n constructor(\n private ClassType: new () => T,\n private validate?: (obj: any) => Promise<any[]>\n ) {\n if (typeof ClassType !== 'function') {\n throw new Error('Class constructor is required for ClassValidatorAdapter');\n }\n }\n\n async parseAsync(data: unknown): Promise<T> {\n try {\n const instance = Object.assign(new this.ClassType(), data as Record<string, any>);\n\n if (this.validate) {\n const errors = await this.validate(instance);\n if (errors && errors.length > 0) {\n throw new ValidationError(\n errors.map((error: any, index: number) => ({\n path: error.property ? [error.property] : [index],\n message: Object.values(error.constraints || {}).join(', ') || 'Validation failed',\n code: 'class_validator',\n }))\n );\n }\n }\n\n return instance as T;\n } catch (error) {\n if (error instanceof ValidationError) throw error;\n throw normalizeValidationError(error);\n }\n }\n}\n\n/**\n * Utility functions for creating adapters\n */\nexport function joi<T = any>(joiSchema: any): ValidationSchema<T> {\n return new JoiAdapter<T>(joiSchema);\n}\n\nexport function yup<T = any>(yupSchema: any): ValidationSchema<T> {\n return new YupAdapter<T>(yupSchema);\n}\n\nexport function fn<T = any>(\n validateFn: (data: unknown) => T | Promise<T>,\n name?: string\n): ValidationSchema<T> {\n return new FunctionAdapter<T>(validateFn, name);\n}\n\nexport function classValidator<T extends object = any>(\n ClassType: new () => T,\n validate?: (obj: any) => Promise<any[]>\n): ValidationSchema<T> {\n return new ClassValidatorAdapter<T>(ClassType, validate);\n}\n\n// Type helpers\nexport type JoiSchema<T> = ValidationSchema<T>;\nexport type YupSchema<T> = ValidationSchema<T>;\nexport type CustomValidator<T> = ValidationSchema<T>;\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-handler.js","sourceRoot":"","sources":["../../../src/core/validation/error-handler.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAE5C;;;GAGG;AACH,MAAM,CAAC,MAAM,6BAA6B,GAA2B,CACnE,MAA+B,EAC/B,OAA+B,EACN,EAAE;IAC3B,MAAM,YAAY,GAAG,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY,CAAC;IAC3D,OAAO;QACL,MAAM,EAAE,GAAG;QACX,IAAI,EAAE;YACJ,OAAO,EAAE,KAAK;YACd,KAAK,EAAE,yBAAyB,OAAO,CAAC,KAAK,EAAE;YA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,MAAM,CAAC,KAAK,CAAC,mCAAmC,EAAE,iBAAiB,EAAE;YACnE,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;YAC7D,KAAK;YACL,IAAI,EAAE,GAAG,CAAC,IAAI;SACf,CAAC,CAAC;QAEH,uDAAuD;QACvD,IAAI,CAAC,GAAG,CAAC,WAAW,EAAE,CAAC;YACrB,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;gBACnB,OAAO,EAAE,KAAK;gBACd,KAAK,EAAE,gDAAgD;gBACvD,SAAS,EAAE,GAAG,CAAC,SAAS;aACzB,CAAC,CAAC;QACL,CAAC;IACH,CAAC;AACH,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,eAAe,CAAC,MAAa,EAAE,KAAa;IAC1D,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC,GAAQ,EAAE,EAAE,CAAC,CAAC;QAC/B,KAAK,EAAE,GAAG,CAAC,IAAI,IAAI,GAAG,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK;QACnE,OAAO,EAAE,GAAG,CAAC,OAAO,IAAI,mBAAmB;QAC3C,IAAI,EAAE,GAAG,CAAC,IAAI;QACd,KAAK,EAAE,GAAG,CAAC,KAAK;QAChB,IAAI,EAAE,GAAG,CAAC,IAAI,IAAI,EAAE;KACrB,CAAC,CAAC,CAAC;AACN,CAAC","sourcesContent":["// Validation Error Handler Utility\nimport type { HttpRequest, HttpResponse } from '../../types/http.js';\nimport type {\n ValidationErrorDetail,\n ValidationErrorContext,\n ValidationErrorResponse,\n ValidationErrorHandler,\n} from '../../types/config.js';\nimport { logger } from '../logger/index.js';\n\n/**\n * Default validation error handler\n * Returns a consistent error response format\n */\nexport const defaultValidationErrorHandler: ValidationErrorHandler = (\n errors: ValidationErrorDetail[],\n context: ValidationErrorContext\n): ValidationErrorResponse => {\n const isProduction = process.env.NODE_ENV === 'production';\n return {\n status: 400,\n body: {\n success: false,\n error: `Validation failed for ${context.field}`,\n ...(isProduction ? {} : { details: errors }),\n requestId: (context.request as any).requestId,\n },\n };\n};\n\n/**\n * Handle validation errors using the configured error handler\n * This is the central function that all validation error handling should go through\n */\nexport function handleValidationError(\n errors: ValidationErrorDetail[],\n field: 'body' | 'query' | 'params' | 'headers',\n req: HttpRequest,\n res: HttpResponse,\n customHandler?: ValidationErrorHandler,\n globalHandler?: ValidationErrorHandler\n): void {\n // Don't send error if headers already sent\n if (res.headersSent) {\n logger.warn('Attempted to send validation error after headers sent', 'ValidationError', {\n field,\n path: req.path,\n method: req.method,\n });\n return;\n }\n\n // Build context for error handler\n const context: ValidationErrorContext = {\n request: {\n method: req.method || 'UNKNOWN',\n path: req.path || req.url || '',\n url: req.url || '',\n headers: req.headers || {},\n },\n field,\n };\n\n // Use custom handler (route-level) > global handler > default handler\n const handler = customHandler || globalHandler || defaultValidationErrorHandler;\n\n logger.debug('Handling validation error', 'ValidationError', {\n field,\n errorCount: errors.length,\n path: req.path,\n method: req.method,\n hasCustomHandler: !!customHandler,\n hasGlobalHandler: !!globalHandler,\n });\n\n try {\n // Execute the error handler\n const errorResponse = handler(errors, context);\n\n // Apply headers if provided\n if (errorResponse.headers) {\n Object.entries(errorResponse.headers).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n }\n\n // Send the response\n res.status(errorResponse.status).json(errorResponse.body);\n } catch (error) {\n logger.error('Error in validation error handler', 'ValidationError', {\n error: error instanceof Error ? error.message : String(error),\n field,\n path: req.path,\n });\n\n // Fallback to default error response if handler throws\n if (!res.headersSent) {\n res.status(500).json({\n success: false,\n error: 'Internal error while handling validation error',\n requestId: req.requestId,\n });\n }\n }\n}\n\n/**\n * Normalize errors from different validation libraries into a consistent format\n */\nexport function normalizeErrors(errors: any[], field: string): ValidationErrorDetail[] {\n return errors.map((err: any) => ({\n field: err.path && err.path.length > 0 ? err.path.join('.') : field,\n message: err.message || 'Validation failed',\n code: err.code,\n value: err.input,\n path: err.path || [],\n }));\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/validation/index.ts"],"names":[],"mappings":"AAAA,iDAAiD;AACjD,oEAAoE;AAGpE,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AACtF,OAAO,EAAoB,wBAAwB,EAAE,MAAM,uBAAuB,CAAC;AACnF,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAGrD,MAAM,MAAM,GAAG,qBAAqB,CAAC,YAAY,CAAC,CAAC;AAEnD,2EAA2E;AAC3E,+CAA+C;AAC/C,wDAAwD;AACxD,IAAI,SAAS,GAAQ,IAAI,CAAC;AAC1B,IAAI,gBAAgB,GAAG,KAAK,CAAC;AAE7B,SAAS,WAAW;IAClB,IAAI,gBAAgB,EAAE,CAAC;QACrB,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,gBAAgB,GAAG,IAAI,CAAC;IAExB,IAAI,CAAC;QACH,IAAI,CAAC,kBAAkB,CAAC,KAAK,CAAC,EAAE,CAAC;YAC/B,SAAS,GAAG,IAAI,CAAC;YACjB,OAAO,SAAS,CAAC;QACnB,CAAC;QAED,qDAAqD;QACrD,MAAM,WAAW,GAAG,iBAAiB,EAAE,CAAC;QACxC,SAAS,GAAG,WAAW,CAAC,KAAK,CAAC,CAAC;IACjC,CAAC;IAAC,MAAM,CAAC;QACP,sCAAsC;QACtC,SAAS,GAAG,IAAI,CAAC;IACnB,CAAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,MAAM,CAAC,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AO,QAAQ,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,CAAC;IAC9C,CAAC,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,MAAM,CAAI,MAA2B;IACnD,OAAO,CAAC,OAA8E,EAAE,EAAE;QACxF,OAAO,QAAQ,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,CAAC;IAC/C,CAAC,CAAC;AACJ,CAAC;AAED,6BAA6B;AAC7B,MAAM,UAAU,cAAc,CAAC,OAAyB;IACtD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["// Universal Validation System for Moro Framework\n// Works with Zod, Joi, Yup, and any validation library via adapters\n\nimport { HttpRequest, HttpResponse } from '../http/index.js';\nimport { createFrameworkLogger } from '../logger/index.js';\nimport { createUserRequire, isPackageAvailable } from '../utilities/package-utils.js';\nimport { ValidationSchema, normalizeValidationError } from './schema-interface.js';\nimport { handleValidationError } from './error-handler.js';\nimport { getGlobalConfig } from '../config/index.js';\nimport type { ValidationErrorHandler } from '../../types/config.js';\n\nconst logger = createFrameworkLogger('Validation');\n\n// Convenience re-export of Zod (optional - only works if zod is installed)\n// Lazy-loads Zod synchronously on first access\n// If zod is not installed, z will throw a helpful error\nlet zodModule: any = null;\nlet zodLoadAttempted = false;\n\nfunction loadZodSync() {\n if (zodLoadAttempted) {\n return zodModule;\n }\n\n zodLoadAttempted = true;\n\n try {\n if (!isPackageAvailable('zod')) {\n zodModule = null;\n return zodModule;\n }\n\n // Use synchronous require for immediate availability\n const userRequire = createUserRequire();\n zodModule = userRequire('zod');\n } catch {\n // Zod not installed or failed to load\n zodModule = null;\n }\n\n return zodModule;\n}\n\nexport const z = new Proxy({} as any, {\n get(_target, prop) {\n const zod = loadZodSync();\n\n if (!zod) {\n throw new Error(\n 'Zod is not installed. Please install it with: npm install zod\\n' +\n 'Or use an alternative validation library (joi, yup, class-validator) via adapters.'\n );\n }\n\n if (!zod.z) {\n throw new Error(\n 'Zod module loaded but z export not found. This may be a version compatibility issue.'\n );\n }\n\n return zod.z[prop];\n },\n apply(_target, thisArg, args) {\n const zod = loadZodSync();\n\n if (!zod?.z) {\n throw new Error('Zod is not installed. Please install it with: npm install zod');\n }\n\n return zod.z.apply(thisArg, args);\n },\n});\n\n// Universal validation configuration interface\nexport interface ValidationConfig {\n body?: ValidationSchema;\n query?: ValidationSchema;\n params?: ValidationSchema;\n headers?: ValidationSchema;\n onValidationError?: ValidationErrorHandler;\n}\n\n// Validation result types\nexport interface ValidationResult<T = any> {\n success: boolean;\n data?: T;\n errors?: ValidationErrorDetail[];\n}\n\nexport interface ValidationErrorDetail {\n field: string;\n message: string;\n code: string;\n}\n\n// Enhanced request type with validated data\nexport interface ValidatedRequest<T = any> extends HttpRequest {\n validatedBody?: T;\n validatedQuery?: any;\n validatedParams?: any;\n validatedHeaders?: any;\n}\n\n// Main validation wrapper function\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function validate<TBody = any, TQuery = any, TParams = any>(\n config: ValidationConfig,\n handler: (req: ValidatedRequest<TBody>, res: HttpResponse) => any | Promise<any>\n) {\n return async (req: HttpRequest, res: HttpResponse): Promise<any> => {\n try {\n const validatedReq = req as ValidatedRequest<TBody>;\n\n // Get global validation config\n let globalHandler: ValidationErrorHandler | undefined;\n try {\n const globalConfig = getGlobalConfig();\n globalHandler = globalConfig.modules.validation.onError;\n } catch {\n // Config not initialized yet, use default handler\n globalHandler = undefined;\n }\n\n // Validate body\n if (config.body) {\n const result = await validateField(config.body, req.body, 'body');\n if (!result.success) {\n return handleValidationError(\n result.errors || [],\n 'body',\n req,\n res,\n config.onValidationError,\n globalHandler\n );\n }\n validatedReq.validatedBody = result.data;\n validatedReq.body = result.data; // Also update original body for compatibility\n }\n\n // Validate query parameters\n if (config.query) {\n const result = await validateField(config.query, req.query, 'query');\n if (!result.success) {\n return handleValidationError(\n result.errors || [],\n 'query',\n req,\n res,\n config.onValidationError,\n globalHandler\n );\n }\n validatedReq.validatedQuery = result.data;\n validatedReq.query = result.data; // Also update original query for compatibility\n }\n\n // Validate path parameters\n if (config.params) {\n const result = await validateField(config.params, req.params, 'params');\n if (!result.success) {\n return handleValidationError(\n result.errors || [],\n 'params',\n req,\n res,\n config.onValidationError,\n globalHandler\n );\n }\n validatedReq.validatedParams = result.data;\n validatedReq.params = result.data; // Also update original params for compatibility\n }\n\n // Validate headers\n if (config.headers) {\n const result = await validateField(config.headers, req.headers, 'headers');\n if (!result.success) {\n return handleValidationError(\n result.errors || [],\n 'headers',\n req,\n res,\n config.onValidationError,\n globalHandler\n );\n }\n validatedReq.validatedHeaders = result.data;\n }\n\n logger.debug('Request validation passed', 'ValidationSuccess', {\n path: req.path,\n method: req.method,\n validatedFields: Object.keys(config),\n });\n\n // Execute the handler with validated request\n return await handler(validatedReq, res);\n } catch (error) {\n logger.error('Validation wrapper error', 'ValidationError', {\n error: error instanceof Error ? error.message : String(error),\n path: req.path,\n method: req.method,\n });\n\n if (!res.headersSent) {\n res.status(500).json({\n success: false,\n error: 'Internal validation error',\n requestId: req.requestId,\n });\n }\n }\n };\n}\n\n// Validate individual field using universal schema interface\nasync function validateField(\n schema: ValidationSchema,\n data: any,\n fieldName: string\n): Promise<ValidationResult> {\n try {\n const validated = await schema.parseAsync(data);\n return {\n success: true,\n data: validated,\n };\n } catch (error) {\n const normalizedError = normalizeValidationError(error);\n const errors: ValidationErrorDetail[] = normalizedError.issues.map(issue => ({\n field: issue.path.length > 0 ? issue.path.join('.') : fieldName,\n message: issue.message,\n code: issue.code,\n }));\n\n logger.debug('Field validation failed', 'ValidationFailed', {\n field: fieldName,\n errors: errors.length,\n details: errors,\n });\n\n return {\n success: false,\n errors,\n };\n }\n}\n\n// Re-export common validation tools\nexport { ValidationError, normalizeValidationError } from './schema-interface.js';\nexport type { ValidationSchema, InferSchemaType } from './schema-interface.js';\nexport { joi, yup, fn as customValidator, classValidator } from './adapters.js';\nexport { handleValidationError, normalizeErrors } from './error-handler.js';\nexport type {\n ValidationErrorHandler,\n ValidationErrorContext,\n ValidationErrorResponse,\n ValidationErrorDetail as ValidationErrorDetailType,\n} from '../../types/config.js';\n\n// Convenience functions for single-field validation\nexport function body<T>(schema: ValidationSchema<T>) {\n return (handler: (req: ValidatedRequest<T>, res: HttpResponse) => any | Promise<any>) => {\n return validate({ body: schema }, handler);\n };\n}\n\nexport function query<T>(schema: ValidationSchema<T>) {\n return (handler: (req: ValidatedRequest<any>, res: HttpResponse) => any | Promise<any>) => {\n return validate({ query: schema }, handler);\n };\n}\n\nexport function params<T>(schema: ValidationSchema<T>) {\n return (handler: (req: ValidatedRequest<any>, res: HttpResponse) => any | Promise<any>) => {\n return validate({ params: schema }, handler);\n };\n}\n\n// Schema composition helpers\nexport function combineSchemas(schemas: ValidationConfig): ValidationConfig {\n return schemas;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema-interface.js","sourceRoot":"","sources":["../../../src/core/validation/schema-interface.ts"],"names":[],"mappings":"AAAA,2DAA2D;AAC3D,0EAA0E;AAW1E;;;GAGG;AACH,MAAM,OAAO,eAAgB,SAAQ,KAAK;IACxB,MAAM,CAAoB;IAE1C,YAAY,MAAyB;QACnC,MAAM,OAAO,GAAG,sBAAsB,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QAC9E,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;QAC9B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;CACF;AAcD;;GAEG;AACH,MAAM,UAAU,kBAAkB,CAAC,GAAQ;IACzC,OAAO,GAAG,IAAI,OAAO,GAAG,CAAC,UAAU,KAAK,UAAU,CAAC;AACrD,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,wBAAwB,CAAC,KAAU;IACjD,qBAAqB;IACrB,I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,CAAC,CAAC,KAAK,CAAC;YACzC,OAAO,EAAE,GAAG;YACZ,IAAI,EAAE,KAAK,CAAC,IAAI,IAAI,SAAS;SAC9B,CAAC,CAAC,CACJ,CAAC;IACJ,CAAC;IAED,gBAAgB;IAChB,OAAO,IAAI,eAAe,CAAC;QACzB;YACE,IAAI,EAAE,EAAE;YACR,OAAO,EAAE,KAAK,CAAC,OAAO,IAAI,MAAM,CAAC,KAAK,CAAC;YACvC,IAAI,EAAE,SAAS;SAChB;KACF,CAAC,CAAC;AACL,CAAC"}
|
|
1
|
+
{"version":3,"file":"schema-interface.js","sourceRoot":"","sources":["../../../src/core/validation/schema-interface.ts"],"names":[],"mappings":"AAAA,2DAA2D;AAC3D,0EAA0E;AAW1E;;;GAGG;AACH,MAAM,OAAO,eAAgB,SAAQ,KAAK;IACxB,MAAM,CAAoB;IAE1C,YAAY,MAAyB;QACnC,MAAM,OAAO,GAAG,sBAAsB,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QAC9E,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;QAC9B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;CACF;AAcD;;GAEG;AACH,MAAM,UAAU,kBAAkB,CAAC,GAAQ;IACzC,OAAO,GAAG,IAAI,OAAO,GAAG,CAAC,UAAU,KAAK,UAAU,CAAC;AACrD,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,wBAAwB,CAAC,KAAU;IACjD,qBAAqB;IACrB,IAAI,KAAK,YAAY,eAAe,EAAE,CAAC;QACrC,OAAO,KAAK,CAAC;IACf,CAAC;IAED,mBAAmB;IACnB,IAAI,KAAK,IAAI,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC;QACzD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AAI,EAAE,EAAE;YACR,OAAO,EAAE,KAAK,CAAC,OAAO,IAAI,MAAM,CAAC,KAAK,CAAC;YACvC,IAAI,EAAE,SAAS;SAChB;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Universal Validation Schema Interface for Moro Framework\n// Allows Zod, Joi, Yup, and other validation libraries to work seamlessly\n\n/**\n * Standard validation error structure\n */\nexport interface ValidationIssue {\n path: (string | number)[];\n message: string;\n code: string;\n}\n\n/**\n * Standard validation error class\n * Compatible with ZodError structure\n */\nexport class ValidationError extends Error {\n public readonly issues: ValidationIssue[];\n\n constructor(issues: ValidationIssue[]) {\n const message = `Validation failed: ${issues.map(i => i.message).join(', ')}`;\n super(message);\n this.name = 'ValidationError';\n this.issues = issues;\n }\n}\n\n/**\n * Universal validation schema interface\n * This is what Zod naturally implements! No breaking changes needed.\n */\nexport interface ValidationSchema<T = any> {\n /**\n * Parse data asynchronously and return validated result\n * Throws ValidationError on validation failure\n */\n parseAsync(data: unknown): Promise<T>;\n}\n\n/**\n * Check if an object implements the ValidationSchema interface\n */\nexport function isValidationSchema(obj: any): obj is ValidationSchema {\n return obj && typeof obj.parseAsync === 'function';\n}\n\n/**\n * Convert various error formats to our standard ValidationError\n */\nexport function normalizeValidationError(error: any): ValidationError {\n // Already our format\n if (error instanceof ValidationError) {\n return error;\n }\n\n // Zod error format\n if (error && error.issues && Array.isArray(error.issues)) {\n return new ValidationError(\n error.issues.map((issue: any) => ({\n path: issue.path || [],\n message: issue.message || 'Validation failed',\n code: issue.code || 'invalid',\n }))\n );\n }\n\n // Joi error format\n if (error && error.details && Array.isArray(error.details)) {\n return new ValidationError(\n error.details.map((detail: any) => ({\n path: detail.path || [],\n message: detail.message || 'Validation failed',\n code: detail.type || 'invalid',\n }))\n );\n }\n\n // Yup error format\n if (error && error.errors && Array.isArray(error.errors)) {\n return new ValidationError(\n error.errors.map((msg: string, index: number) => ({\n path: error.path ? [error.path] : [index],\n message: msg,\n code: error.type || 'invalid',\n }))\n );\n }\n\n // Generic error\n return new ValidationError([\n {\n path: [],\n message: error.message || String(error),\n code: 'unknown',\n },\n ]);\n}\n\n// Type helper for inferring types from validation schemas\nexport type InferSchemaType<T> = T extends ValidationSchema<infer U> ? U : never;\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"facade.js","sourceRoot":"","sources":["../../../src/core/workers/facade.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,oFAAoF;AA+BpF;;GAEG;AACH,MAAM,OAAO,mBAAmB;IACtB,aAAa,GAAqB,IAAI,CAAC;IACvC,WAAW,GAAyB,IAAI,CAAC;IACzC,eAAe,GAAgD,IAAI,CAAC;IACpE,WAAW,GAAG,KAAK,CAAC;IAE5B;;OAEG;IACH,KAAK,CAAC,iBAAiB;QACrB,IAAI,IAAI,CAAC,WAAW;YAAE,OAAO;QAE7B,IAAI,CAAC;YACH,MAAM,OAAO,GAAG,MAAM,MAAM,CAAC,YAAY,CAAC,CAAC;YAC3C,IAAI,CAAC,aAAa,GAAG,OAAO,CAAC,gBAAgB,EAAE,CAAC;YAChD,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC;YACvC,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC;QACjD,CAAC;QAAC,MAAM,CAAC;YACP,+CAA+C;YAC/C,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;YAC1B,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;YACxB,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC;QAC9B,CAAC;QAED,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;IAC1B,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,WAAW,CAAU,IAAgB;QACzC,MAAM,IAAI,CAAC,iBAAiB,EAAE,CAAC;QAE/B,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC;YACxB,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;QAC1E,CAAC;QAED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AC,WAAW;YAAE,OAAO,IAAI,CAAC;QAEnC,OAAO;YACL,KAAK,EAAE,IAAI,CAAC,WAAW,CAAC,gBAAgB,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC;YAC/D,aAAa,EAAE,IAAI,CAAC,WAAW,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC;SACrE,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,WAAW;QACf,MAAM,IAAI,CAAC,iBAAiB,EAAE,CAAC;QAC/B,OAAO,IAAI,CAAC,aAAa,KAAK,IAAI,CAAC;IACrC,CAAC;CACF","sourcesContent":["// Worker Threads Facade - Clean API for optional worker thread functionality\n// Provides a clean interface that gracefully degrades when workers aren't available\n\nexport interface WorkerTask {\n id: string;\n type: string;\n data: any;\n priority?: 'low' | 'normal' | 'high';\n timeout?: number;\n}\n\nexport interface WorkerStats {\n workerCount: number;\n activeTasks: number;\n queuedTasks: number;\n isShuttingDown: boolean;\n}\n\nexport interface WorkerAPI {\n executeTask<T = any>(task: WorkerTask): Promise<T>;\n getStats(): WorkerStats;\n shutdown(): Promise<void>;\n}\n\nexport interface WorkerHelpers {\n verifyJWT(token: string, secret: string, options?: any): Promise<any>;\n signJWT(payload: any, secret: string, options?: any): Promise<string>;\n hash(data: string, algorithm?: string): Promise<string>;\n heavyComputation(data: any): Promise<any>;\n transformJSON(data: any, transformer: (data: any) => any): Promise<any>;\n}\n\n/**\n * Worker Threads Facade - Provides clean access to optional worker functionality\n */\nexport class WorkerThreadsFacade {\n private workerManager: WorkerAPI | null = null;\n private workerTasks: WorkerHelpers | null = null;\n private executeOnWorker: ((task: WorkerTask) => Promise<any>) | null = null;\n private initialized = false;\n\n /**\n * Lazy initialize worker threads\n */\n async ensureInitialized(): Promise<void> {\n if (this.initialized) return;\n\n try {\n const workers = await import('./index.js');\n this.workerManager = workers.getWorkerManager();\n this.workerTasks = workers.workerTasks;\n this.executeOnWorker = workers.executeOnWorker;\n } catch {\n // Workers not available - graceful degradation\n this.workerManager = null;\n this.workerTasks = null;\n this.executeOnWorker = null;\n }\n\n this.initialized = true;\n }\n\n /**\n * Execute a task on worker threads\n */\n async executeTask<T = any>(task: WorkerTask): Promise<T> {\n await this.ensureInitialized();\n\n if (!this.workerManager) {\n throw new Error('Worker threads are not available in this environment');\n }\n\n return this.workerManager.executeTask<T>(task);\n }\n\n /**\n * Get worker thread statistics\n */\n async getStats(): Promise<WorkerStats | null> {\n await this.ensureInitialized();\n return this.workerManager?.getStats() || null;\n }\n\n /**\n * Shutdown worker threads\n */\n async shutdown(): Promise<void> {\n await this.ensureInitialized();\n await this.workerManager?.shutdown();\n }\n\n /**\n * JWT operations using worker threads\n */\n async getJwtWorker(): Promise<{\n verify: WorkerHelpers['verifyJWT'];\n sign: WorkerHelpers['signJWT'];\n } | null> {\n await this.ensureInitialized();\n\n if (!this.workerTasks) return null;\n\n return {\n verify: this.workerTasks.verifyJWT.bind(this.workerTasks),\n sign: this.workerTasks.signJWT.bind(this.workerTasks),\n };\n }\n\n /**\n * Crypto operations using worker threads\n */\n async getCryptoWorker(): Promise<{ hash: WorkerHelpers['hash'] } | null> {\n await this.ensureInitialized();\n\n if (!this.workerTasks) return null;\n\n return {\n hash: this.workerTasks.hash.bind(this.workerTasks),\n };\n }\n\n /**\n * Heavy computation operations using worker threads\n */\n async getComputeWorker(): Promise<{\n heavy: WorkerHelpers['heavyComputation'];\n transformJSON: WorkerHelpers['transformJSON'];\n } | null> {\n await this.ensureInitialized();\n\n if (!this.workerTasks) return null;\n\n return {\n heavy: this.workerTasks.heavyComputation.bind(this.workerTasks),\n transformJSON: this.workerTasks.transformJSON.bind(this.workerTasks),\n };\n }\n\n /**\n * Check if worker threads are available\n */\n async isAvailable(): Promise<boolean> {\n await this.ensureInitialized();\n return this.workerManager !== null;\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/workers/index.ts"],"names":[],"mappings":"AAAA,uDAAuD;AACvD,yDAAyD;AAEzD,OAAO,EACL,aAAa,EACb,gBAAgB,EAChB,eAAe,EACf,WAAW,EAGX,YAAY,GACb,MAAM,qBAAqB,CAAC;AAE7B,mBAAmB;AACnB,OAAO,EACL,mBAAmB,GAIpB,MAAM,aAAa,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/workers/index.ts"],"names":[],"mappings":"AAAA,uDAAuD;AACvD,yDAAyD;AAEzD,OAAO,EACL,aAAa,EACb,gBAAgB,EAChB,eAAe,EACf,WAAW,EAGX,YAAY,GACb,MAAM,qBAAqB,CAAC;AAE7B,mBAAmB;AACnB,OAAO,EACL,mBAAmB,GAIpB,MAAM,aAAa,CAAC","sourcesContent":["// Worker Threads - CPU-intensive operations offloading\n// Massive performance gains: 50-200% for CPU-bound tasks\n\nexport {\n WorkerManager,\n getWorkerManager,\n executeOnWorker,\n workerTasks,\n type WorkerTask,\n type WorkerResult,\n WORKER_TASKS,\n} from './worker-manager.js';\n\n// Clean facade API\nexport {\n WorkerThreadsFacade,\n type WorkerStats,\n type WorkerAPI,\n type WorkerHelpers,\n} from './facade.js';\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const WORKER_ENTRY: string;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// Resolves the compiled worker entry (worker.js, this module's sibling in
|
|
2
|
+
// dist/**) relative to THIS module, so it works for any consumer of the
|
|
3
|
+
// published package - never a cwd-relative path (the package ships only dist/**
|
|
4
|
+
// and worker_threads cannot execute a .ts file).
|
|
5
|
+
//
|
|
6
|
+
// This file exists solely to isolate the ESM-only `import.meta` token. ts-jest
|
|
7
|
+
// transpiles the framework to CommonJS for the test runner, where a literal
|
|
8
|
+
// import.meta is a load-time SyntaxError; jest.config maps this module to a stub
|
|
9
|
+
// so WorkerManager can be imported in tests without spawning real threads.
|
|
10
|
+
import { fileURLToPath } from 'url';
|
|
11
|
+
export const WORKER_ENTRY = fileURLToPath(new URL('./worker.js', import.meta.url));
|
|
12
|
+
//# sourceMappingURL=worker-entry.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"worker-entry.js","sourceRoot":"","sources":["../../../src/core/workers/worker-entry.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,wEAAwE;AACxE,gFAAgF;AAChF,iDAAiD;AACjD,EAAE;AACF,+EAA+E;AAC/E,4EAA4E;AAC5E,iFAAiF;AACjF,2EAA2E;AAC3E,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AAEpC,MAAM,CAAC,MAAM,YAAY,GAAW,aAAa,CAAC,IAAI,GAAG,CAAC,aAAa,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC","sourcesContent":["// Resolves the compiled worker entry (worker.js, this module's sibling in\n// dist/**) relative to THIS module, so it works for any consumer of the\n// published package - never a cwd-relative path (the package ships only dist/**\n// and worker_threads cannot execute a .ts file).\n//\n// This file exists solely to isolate the ESM-only `import.meta` token. ts-jest\n// transpiles the framework to CommonJS for the test runner, where a literal\n// import.meta is a load-time SyntaxError; jest.config maps this module to a stub\n// so WorkerManager can be imported in tests without spawning real threads.\nimport { fileURLToPath } from 'url';\n\nexport const WORKER_ENTRY: string = fileURLToPath(new URL('./worker.js', import.meta.url));\n"]}
|
|
@@ -44,9 +44,17 @@ export declare class WorkerManager {
|
|
|
44
44
|
private workerCount;
|
|
45
45
|
private maxQueueSize;
|
|
46
46
|
private isShuttingDown;
|
|
47
|
+
private maxRestartAttempts;
|
|
48
|
+
private restartBackoffMs;
|
|
49
|
+
private restartAttempts;
|
|
50
|
+
private restartTimers;
|
|
51
|
+
private handledFailures;
|
|
52
|
+
private poolFailed;
|
|
47
53
|
constructor(options?: {
|
|
48
54
|
workerCount?: number;
|
|
49
55
|
maxQueueSize?: number;
|
|
56
|
+
maxRestartAttempts?: number;
|
|
57
|
+
restartBackoffMs?: number;
|
|
50
58
|
});
|
|
51
59
|
/**
|
|
52
60
|
* Initialize worker threads
|
|
@@ -57,9 +65,22 @@ export declare class WorkerManager {
|
|
|
57
65
|
*/
|
|
58
66
|
private createWorker;
|
|
59
67
|
/**
|
|
60
|
-
*
|
|
68
|
+
* Handle a crashed worker: reject only the tasks that were assigned to it and
|
|
69
|
+
* schedule a backed-off restart. A failed worker emits both 'error' and 'exit',
|
|
70
|
+
* so this is guarded to run at most once per worker.
|
|
61
71
|
*/
|
|
62
|
-
private
|
|
72
|
+
private handleWorkerFailure;
|
|
73
|
+
/**
|
|
74
|
+
* Schedule a replacement worker with exponential backoff, capping the number of
|
|
75
|
+
* consecutive restart attempts so a persistently broken worker entry can never
|
|
76
|
+
* spin into an unbounded restart loop.
|
|
77
|
+
*/
|
|
78
|
+
private scheduleRestart;
|
|
79
|
+
/**
|
|
80
|
+
* Give up after too many failed restarts: fail every outstanding task cleanly
|
|
81
|
+
* (rejecting their promises) instead of looping forever.
|
|
82
|
+
*/
|
|
83
|
+
private failPool;
|
|
63
84
|
/**
|
|
64
85
|
* Execute a task on a worker thread
|
|
65
86
|
*/
|