bazis 0.96.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/LICENSE +21 -0
- package/README.md +146 -0
- package/cli/build.ts +147 -0
- package/cli/codegen.ts +40 -0
- package/cli/generateModule.ts +187 -0
- package/cli/generateProject.ts +183 -0
- package/cli/main.ts +125 -0
- package/cli/moduleRegistration.ts +127 -0
- package/cli/naming.ts +124 -0
- package/cli/parseCli.ts +151 -0
- package/cli/templates/module.ts +497 -0
- package/cli/templates/pack.ts +76 -0
- package/cli/templates/passport.ts +178 -0
- package/core/agent/AgentContextBuilder.ts +567 -0
- package/core/agent/AgentDataDefinition.ts +8 -0
- package/core/agent/AgentRegistry.ts +539 -0
- package/core/agent/AgentRuntime.ts +47 -0
- package/core/agent/AgentToolExecutor.ts +2130 -0
- package/core/agent/AgentToolHooks.ts +39 -0
- package/core/agent/ModelProvider.ts +21 -0
- package/core/agent/README.md +229 -0
- package/core/agent/Tool.contract.ts +20 -0
- package/core/agent/decorators/Agent.ts +11 -0
- package/core/agent/decorators/Prompt.ts +11 -0
- package/core/agent/decorators/Task.ts +29 -0
- package/core/agent/decorators/Tool.ts +12 -0
- package/core/agent/errors.ts +43 -0
- package/core/agent/generated/catalog.ts +26 -0
- package/core/agent/index.ts +170 -0
- package/core/agent/internal/AgentExecutionDriver.ts +1497 -0
- package/core/agent/internal/AgentExecutionState.ts +775 -0
- package/core/agent/internal/AgentJsonSchema.ts +150 -0
- package/core/agent/internal/AgentModelBinding.ts +57 -0
- package/core/agent/internal/Schema.contract.ts +36 -0
- package/core/agent/internal/ToolAudit.projector.ts +163 -0
- package/core/agent/internal/ToolContract.validator.ts +102 -0
- package/core/agent/metadata.ts +398 -0
- package/core/agent/moduleContributions-v1.ts +113 -0
- package/core/agent/semantic.ts +903 -0
- package/core/agent/session/codec.ts +33 -0
- package/core/agent/session/contracts.ts +96 -0
- package/core/agent/session/entities.ts +84 -0
- package/core/agent/session/protector.ts +92 -0
- package/core/app/index.ts +5 -0
- package/core/app/runApp.ts +293 -0
- package/core/app/ui/index.ts +29 -0
- package/core/app/ui/uiProfileResolver.ts +966 -0
- package/core/app/ui/uiSurfaceHosting.ts +38 -0
- package/core/app/ui/uiSurfaceHttp.ts +476 -0
- package/core/background/BackgroundService.ts +223 -0
- package/core/background/backgroundModule.ts +42 -0
- package/core/background/decorator.ts +43 -0
- package/core/background/delay.ts +27 -0
- package/core/background/index.ts +15 -0
- package/core/cache/COMPATIBILITY.md +13 -0
- package/core/cache/ICache.ts +71 -0
- package/core/cache/MemoryCache.ts +394 -0
- package/core/cache/README.md +83 -0
- package/core/cache/SPEC.md +1355 -0
- package/core/cache/cacheModule.ts +21 -0
- package/core/cache/decorators/Cacheable.ts +38 -0
- package/core/cache/decorators/CacheableRedis.ts +39 -0
- package/core/cache/decorators/OutputCache.ts +33 -0
- package/core/cache/decorators/OutputRedisCache.ts +33 -0
- package/core/cache/decorators/cacheableMetadata.ts +78 -0
- package/core/cache/decorators/cacheableRedisMetadata.ts +81 -0
- package/core/cache/decorators/outputCacheMetadata.ts +71 -0
- package/core/cache/decorators/outputRedisCacheMetadata.ts +77 -0
- package/core/cache/di/classProviderHook.ts +26 -0
- package/core/cache/distributed/CacheCodec.ts +5 -0
- package/core/cache/distributed/DistributedCache.ts +403 -0
- package/core/cache/distributed/DistributedCacheDriver.ts +83 -0
- package/core/cache/distributed/DistributedCacheStores.ts +28 -0
- package/core/cache/distributed/IDistributedCache.ts +40 -0
- package/core/cache/distributed/NamedCacheRegistry.ts +23 -0
- package/core/cache/distributed/codecs.ts +32 -0
- package/core/cache/distributed/index.ts +19 -0
- package/core/cache/errors/CacheError.ts +16 -0
- package/core/cache/http/CachedHttpPayload.ts +213 -0
- package/core/cache/http/applyClientCacheHeaders.ts +61 -0
- package/core/cache/http/buildOutputCacheKey.ts +154 -0
- package/core/cache/http/buildRedisOutputCacheKey.ts +16 -0
- package/core/cache/http/composeOutputCache.ts +130 -0
- package/core/cache/http/outputCacheMiddleware.ts +111 -0
- package/core/cache/http/outputCacheSecurityWarning.ts +58 -0
- package/core/cache/http/outputRedisCacheMiddleware.ts +118 -0
- package/core/cache/index.ts +97 -0
- package/core/cache/internal/AutomaticCacheKey.ts +106 -0
- package/core/cache/internal/CacheKeyGuard.ts +56 -0
- package/core/cache/internal/buildCacheProviders.ts +146 -0
- package/core/cache/internal/normalizeCacheKey.ts +9 -0
- package/core/cache/internal/resolveCachePolicy.ts +32 -0
- package/core/cache/internal/resolveCacheableRedisPolicy.ts +17 -0
- package/core/cache/internal/resolveOutputRedisCachePolicy.ts +17 -0
- package/core/cache/providers/cachedProviders.ts +68 -0
- package/core/cache/services/cacheProxy.ts +243 -0
- package/core/cache/tokens/CACHE_POLICIES.ts +5 -0
- package/core/cache/tokens/DISTRIBUTED_CACHE.ts +30 -0
- package/core/cache/types/CacheEntry.ts +7 -0
- package/core/cache/types/CacheOptions.ts +60 -0
- package/core/cache/types/CachePolicy.ts +74 -0
- package/core/cache/types/CacheableRedisOptions.ts +23 -0
- package/core/cache/types/OutputRedisCacheOptions.ts +25 -0
- package/core/di/README.md +104 -0
- package/core/di/ServiceCollection.ts +185 -0
- package/core/di/ServiceProvider.ts +689 -0
- package/core/di/ServiceScope.ts +61 -0
- package/core/di/container.ts +38 -0
- package/core/di/errors/AmbiguousNamedDependencyError.ts +10 -0
- package/core/di/errors/AsyncResolutionRequiredError.ts +12 -0
- package/core/di/errors/CircularDependencyError.ts +10 -0
- package/core/di/errors/ClassDependenciesMismatchError.ts +15 -0
- package/core/di/errors/DiError.ts +6 -0
- package/core/di/errors/InvalidProviderError.ts +9 -0
- package/core/di/errors/ModuleEncapsulationError.ts +7 -0
- package/core/di/errors/ModuleOwnedProviderConflictError.ts +8 -0
- package/core/di/errors/NamedDependencyNotFoundError.ts +7 -0
- package/core/di/errors/OptionsValidationError.ts +7 -0
- package/core/di/errors/ProviderNotFoundError.ts +10 -0
- package/core/di/errors/ScopeDisposedError.ts +7 -0
- package/core/di/errors/ScopedServiceFromRootError.ts +9 -0
- package/core/di/errors/ServiceValidationError.ts +7 -0
- package/core/di/errors/index.ts +14 -0
- package/core/di/extensions/activator.ts +39 -0
- package/core/di/extensions/application.ts +117 -0
- package/core/di/extensions/hosted-service.ts +124 -0
- package/core/di/extensions/index.ts +23 -0
- package/core/di/extensions/options-reloadable.ts +137 -0
- package/core/di/extensions/options.ts +91 -0
- package/core/di/extensions/service-provider-token.ts +21 -0
- package/core/di/index.ts +97 -0
- package/core/di/internal/GraphValidator.ts +119 -0
- package/core/di/internal/HostedServicePlan.ts +158 -0
- package/core/di/internal/NamedTokenIndex.ts +55 -0
- package/core/di/internal/OpenGenericRegistration.ts +14 -0
- package/core/di/internal/ResolutionPlan.ts +18 -0
- package/core/di/internal/ResolutionScopeState.ts +19 -0
- package/core/di/internal/ResolutionTracker.ts +153 -0
- package/core/di/internal/ScopeLifecycle.ts +159 -0
- package/core/di/internal/ServiceRegistration.ts +14 -0
- package/core/di/internal/ServiceRegistry.ts +252 -0
- package/core/di/internal/classDeps.ts +38 -0
- package/core/di/internal/disposal.ts +58 -0
- package/core/di/internal/providerDeps.ts +26 -0
- package/core/di/module/DI.ts +146 -0
- package/core/di/module/Global.ts +25 -0
- package/core/di/module/Module.ts +44 -0
- package/core/di/module/ModuleRegistrar.ts +69 -0
- package/core/di/module/autoDeps.ts +39 -0
- package/core/di/module/classProviderHooks.ts +66 -0
- package/core/di/module/collectModuleConfigs.ts +57 -0
- package/core/di/module/collectModuleControllers.ts +53 -0
- package/core/di/module/collectModuleUiProfiles.ts +53 -0
- package/core/di/module/createContainer.ts +261 -0
- package/core/di/module/encapsulation.ts +416 -0
- package/core/di/module/encapsulationHooks.ts +36 -0
- package/core/di/module/generatedProviderAttachments.ts +102 -0
- package/core/di/module/index.ts +41 -0
- package/core/di/module/moduleExtensions.ts +35 -0
- package/core/di/module/moduleNameBinding.ts +136 -0
- package/core/di/module/moduleOwnedProviderContributors.ts +409 -0
- package/core/di/module/providerSelection.ts +90 -0
- package/core/di/module/shortcuts.ts +111 -0
- package/core/di/module/types/BazisModule.ts +71 -0
- package/core/di/module/types/DiRegistrar.ts +24 -0
- package/core/di/module/types/index.ts +2 -0
- package/core/di/provider/index.ts +26 -0
- package/core/di/provider/providerGuards.ts +17 -0
- package/core/di/provider/types/AsyncFactoryProvider.ts +15 -0
- package/core/di/provider/types/ClassProvider.ts +18 -0
- package/core/di/provider/types/FactoryProvider.ts +20 -0
- package/core/di/provider/types/KeyedDependency.ts +20 -0
- package/core/di/provider/types/LazyDependency.ts +31 -0
- package/core/di/provider/types/NamedDependency.ts +16 -0
- package/core/di/provider/types/Provider.ts +10 -0
- package/core/di/provider/types/ProviderDefinition.ts +11 -0
- package/core/di/provider/types/ProviderDependencyList.ts +11 -0
- package/core/di/provider/types/ProviderLifetime.ts +1 -0
- package/core/di/provider/types/ProviderOwnership.ts +7 -0
- package/core/di/provider/types/ResolvedDeps.ts +18 -0
- package/core/di/provider/types/ValueProvider.ts +6 -0
- package/core/di/provider/types/index.ts +13 -0
- package/core/di/token.ts +84 -0
- package/core/di/types/BuildServiceProviderOptions.ts +4 -0
- package/core/di/types/ServiceKey.ts +1 -0
- package/core/di/types/ServiceResolver.ts +16 -0
- package/core/di/types/index.ts +3 -0
- package/core/generatedFingerprint.ts +60 -0
- package/core/generatedRuntime.ts +187 -0
- package/core/grpc/Grpc.module.ts +23 -0
- package/core/grpc/GrpcBinding.contract.ts +35 -0
- package/core/grpc/GrpcCall.ts +73 -0
- package/core/grpc/GrpcClient.ts +172 -0
- package/core/grpc/GrpcClientCall.ts +267 -0
- package/core/grpc/GrpcError.ts +19 -0
- package/core/grpc/GrpcRequest.binding.ts +45 -0
- package/core/grpc/GrpcServer.ts +204 -0
- package/core/grpc/GrpcStatus.ts +8 -0
- package/core/grpc/GrpcTransport.ts +174 -0
- package/core/grpc/Metadata.ts +73 -0
- package/core/grpc/ProtoCodec.ts +225 -0
- package/core/grpc/ProtoParser.ts +192 -0
- package/core/grpc/ProtoReader.ts +34 -0
- package/core/grpc/ProtoSchema.ts +52 -0
- package/core/grpc/ServerCredentials.ts +30 -0
- package/core/grpc/clientContracts.ts +39 -0
- package/core/grpc/contracts.ts +45 -0
- package/core/grpc/decorators.ts +82 -0
- package/core/grpc/grpcClientProvider.ts +9 -0
- package/core/grpc/index.ts +17 -0
- package/core/grpc/moduleControllers.ts +38 -0
- package/core/grpc/protobuf.ts +80 -0
- package/core/grpc/serviceDefinition.ts +20 -0
- package/core/http/Authorization/Authorize.ts +52 -0
- package/core/http/Authorization/authorizeComposer.ts +31 -0
- package/core/http/Authorization/metadata.ts +158 -0
- package/core/http/Binding/ParameterBinder.ts +109 -0
- package/core/http/Binding/RequestModel.ts +27 -0
- package/core/http/Binding/autoBindings.ts +125 -0
- package/core/http/Binding/bindings.ts +19 -0
- package/core/http/Binding/convert.ts +48 -0
- package/core/http/Binding/generatedSpec.ts +18 -0
- package/core/http/Binding/listModelRegistry.ts +47 -0
- package/core/http/Binding/modelBinder.ts +345 -0
- package/core/http/Binding/modelValidator.ts +30 -0
- package/core/http/Binding/requestModelRegistry.ts +117 -0
- package/core/http/Decorators/attributes.ts +92 -0
- package/core/http/Decorators/controller.ts +24 -0
- package/core/http/Decorators/metadata.ts +107 -0
- package/core/http/Decorators/routes.ts +131 -0
- package/core/http/Errors/HttpError.ts +92 -0
- package/core/http/HttpContext/HttpContext.ts +148 -0
- package/core/http/HttpContext/ResponseBuilder.ts +37 -0
- package/core/http/HttpContext/inspectableRedirects.ts +47 -0
- package/core/http/HttpContext/principal.ts +24 -0
- package/core/http/HttpContext/responseLifetime.ts +45 -0
- package/core/http/HttpServer.ts +627 -0
- package/core/http/Middleware/accessLog.ts +90 -0
- package/core/http/Middleware/cors.ts +160 -0
- package/core/http/Middleware/errorHandler.ts +100 -0
- package/core/http/Middleware/pipeline.ts +21 -0
- package/core/http/Middleware/rateLimit.ts +104 -0
- package/core/http/Middleware/securityHeaders.ts +118 -0
- package/core/http/Middleware/types.ts +19 -0
- package/core/http/OpenApi/generatedOpenApiRegistry.ts +102 -0
- package/core/http/OpenApi/openApiDocs.ts +75 -0
- package/core/http/OpenApi/openApiDocument.ts +356 -0
- package/core/http/README.md +139 -0
- package/core/http/Results/HttpResult.ts +19 -0
- package/core/http/Results/normalize.ts +93 -0
- package/core/http/Results/results.ts +70 -0
- package/core/http/Routing/Router.ts +201 -0
- package/core/http/Routing/RouterBuilder.ts +184 -0
- package/core/http/Routing/template.ts +112 -0
- package/core/http/SPEC.md +981 -0
- package/core/http/Versioning/VersionReader.ts +20 -0
- package/core/http/WebSocketUpgrade.ts +29 -0
- package/core/http/composeRouteMiddlewareComposers.ts +21 -0
- package/core/http/correlation/createCorrelationIdMiddleware.ts +79 -0
- package/core/http/httpModule.ts +48 -0
- package/core/http/index.ts +140 -0
- package/core/http/middlewareTokens.ts +48 -0
- package/core/http/options.ts +134 -0
- package/core/http-client/index.ts +105 -0
- package/core/infra/Infra.ts +158 -0
- package/core/infra/InfraConnector.ts +86 -0
- package/core/infra/InfraLifecycle.ts +86 -0
- package/core/infra/cache/RedisDistributedCacheBackend.ts +88 -0
- package/core/infra/cache/RedisDistributedCacheDriver.ts +186 -0
- package/core/infra/cache/index.ts +7 -0
- package/core/infra/connectorConfig.ts +29 -0
- package/core/infra/connectorIdentity.ts +39 -0
- package/core/infra/connectors/codex/CodexAppServer.ts +146 -0
- package/core/infra/connectors/codex/CodexAppServerClient.ts +258 -0
- package/core/infra/connectors/codex/CodexPolicy.ts +114 -0
- package/core/infra/connectors/codex/CodexTurn.ts +133 -0
- package/core/infra/connectors/codex/contracts.ts +82 -0
- package/core/infra/connectors/codex.ts +26 -0
- package/core/infra/connectors/llm.ts +78 -0
- package/core/infra/connectors/llmRouter.ts +443 -0
- package/core/infra/connectors/openaiCompatible.ts +590 -0
- package/core/infra/connectors/openaiTextStream.ts +134 -0
- package/core/infra/connectors/opensearch.ts +307 -0
- package/core/infra/connectors/postgres.ts +105 -0
- package/core/infra/connectors/redis.ts +132 -0
- package/core/infra/index.ts +58 -0
- package/core/kernel/ApplicationLifetime.ts +91 -0
- package/core/kernel/Bazis.ts +73 -0
- package/core/kernel/Environment.ts +53 -0
- package/core/kernel/Kernel.ts +391 -0
- package/core/kernel/KernelBuilder.ts +172 -0
- package/core/kernel/LifecycleCoordinator.ts +204 -0
- package/core/kernel/README.md +66 -0
- package/core/kernel/SupervisedHostedService.ts +147 -0
- package/core/kernel/config/ConfigRegistry.ts +48 -0
- package/core/kernel/config/Configuration.ts +110 -0
- package/core/kernel/config/README.md +62 -0
- package/core/kernel/config/Secret.ts +29 -0
- package/core/kernel/config/addConfigOptions.ts +63 -0
- package/core/kernel/config/defineConfig.ts +211 -0
- package/core/kernel/config/sources.ts +123 -0
- package/core/kernel/correlation/requestContext.ts +57 -0
- package/core/kernel/errors/ConfigKeyMissingError.ts +7 -0
- package/core/kernel/errors/KernelError.ts +7 -0
- package/core/kernel/errors/ShutdownTimeoutError.ts +7 -0
- package/core/kernel/errors/StartupAbortedError.ts +7 -0
- package/core/kernel/errors/StartupTimeoutError.ts +7 -0
- package/core/kernel/errors/index.ts +5 -0
- package/core/kernel/events/EventBus.ts +140 -0
- package/core/kernel/events/EventToken.ts +17 -0
- package/core/kernel/events/eventSubscribers.ts +126 -0
- package/core/kernel/events/kernelEvents.ts +16 -0
- package/core/kernel/events/onEvent.ts +32 -0
- package/core/kernel/health/HealthCheckContracts.ts +42 -0
- package/core/kernel/health/HealthService.ts +93 -0
- package/core/kernel/index.ts +96 -0
- package/core/kernel/internal/awaitAbortable.ts +18 -0
- package/core/kernel/internal/awaitShutdown.ts +21 -0
- package/core/kernel/internal/reportDiagnosticFailure.ts +8 -0
- package/core/kernel/internal/validateTimeout.ts +8 -0
- package/core/kernel/lifecycleHooks.ts +18 -0
- package/core/kernel/logging/ConsoleLogger.ts +68 -0
- package/core/kernel/logging/Logger.ts +22 -0
- package/core/kernel/types/ConfigSource.ts +9 -0
- package/core/kernel/types/EnvironmentName.ts +1 -0
- package/core/kernel/types/KernelOptions.ts +23 -0
- package/core/kernel/types/LifecycleHook.ts +18 -0
- package/core/kernel/types/index.ts +4 -0
- package/core/orm/DATABASE_PROVIDER.ts +5 -0
- package/core/orm/OrmHostedPlan.validator.ts +55 -0
- package/core/orm/OrmLifecycle.ts +146 -0
- package/core/orm/OrmOwnedStoreLifecycle.ts +96 -0
- package/core/orm/buildOrmProviders.ts +152 -0
- package/core/orm/databaseConnector.ts +108 -0
- package/core/orm/encapsulationHook.ts +19 -0
- package/core/orm/index.ts +95 -0
- package/core/orm/listQuery.ts +198 -0
- package/core/orm/ormModule.ts +173 -0
- package/core/orm/ownedStoreContributions.ts +195 -0
- package/core/orm/registerRepositories.ts +27 -0
- package/core/orm/repository.ts +45 -0
- package/core/orm/strictSchemaHostedIdentity.ts +17 -0
- package/core/scripts/agent-codegen.ts +1166 -0
- package/core/scripts/di-generate-target.ts +90 -0
- package/core/scripts/di-generate.ts +1837 -0
- package/core/scripts/orm-predicate-codegen.ts +33 -0
- package/core/scripts/request-model-codegen.ts +326 -0
- package/core/websocket/DESIGN.md +297 -0
- package/core/websocket/WsRateLimiter.ts +101 -0
- package/core/websocket/adapter/adapter.interface.ts +45 -0
- package/core/websocket/adapter/in-memory.adapter.ts +190 -0
- package/core/websocket/adapter/redis-delivery-scripts.ts +135 -0
- package/core/websocket/adapter/redis-delivery-store.ts +86 -0
- package/core/websocket/adapter/redis-operations.ts +33 -0
- package/core/websocket/adapter/redis.adapter.ts +218 -0
- package/core/websocket/codec/binary.codec.ts +87 -0
- package/core/websocket/codec/json.codec.ts +34 -0
- package/core/websocket/codec/packet-codec.interface.ts +17 -0
- package/core/websocket/decorators.ts +165 -0
- package/core/websocket/explorer.ts +126 -0
- package/core/websocket/index.ts +78 -0
- package/core/websocket/middleware.ts +146 -0
- package/core/websocket/packet-codec.ts +75 -0
- package/core/websocket/reliable-delivery.ts +56 -0
- package/core/websocket/session-creation.ts +16 -0
- package/core/websocket/session-manager.ts +856 -0
- package/core/websocket/socket-wrapper.ts +314 -0
- package/core/websocket/topic-cache.ts +59 -0
- package/core/websocket/types.ts +122 -0
- package/core/websocket/websocketModule.ts +96 -0
- package/core/websocket/ws-dispatch.ts +123 -0
- package/core/websocket/ws-server.ts +1707 -0
- package/index.ts +281 -0
- package/library/boundary/diagnostics-v1.ts +136 -0
- package/library/boundary/index.ts +73 -0
- package/library/boundary/json/decodeBoundedJsonV1.ts +518 -0
- package/library/boundary/json/limits-v1.ts +46 -0
- package/library/boundary/json/normalizeBoundedJsonV1.ts +256 -0
- package/library/boundary/json/types-v1.ts +11 -0
- package/library/boundary/schema/boundarySchemaHashV1.ts +6 -0
- package/library/boundary/schema/collectBoundaryValueDiagnosticsV1.ts +325 -0
- package/library/boundary/schema/decodeBoundarySchemaV1.ts +646 -0
- package/library/boundary/schema/index.ts +8 -0
- package/library/boundary/schema/types-v1.ts +99 -0
- package/library/boundary/schema/validateBoundaryValueV1.ts +58 -0
- package/library/boundary/serialization/canonicalJsonV1.ts +66 -0
- package/library/http-client/HttpClient.ts +969 -0
- package/library/http-client/HttpClientFactory.ts +45 -0
- package/library/http-client/errors.ts +68 -0
- package/library/http-client/index.ts +43 -0
- package/library/http-client/interceptors.ts +40 -0
- package/library/http-client/progress.ts +62 -0
- package/library/http-client/redirectProtocol.ts +6 -0
- package/library/http-client/serialize.ts +133 -0
- package/library/http-client/types.ts +174 -0
- package/library/jsonapi/ListQueryError.ts +25 -0
- package/library/jsonapi/ListRequest.ts +37 -0
- package/library/jsonapi/decorators.ts +161 -0
- package/library/jsonapi/document.ts +124 -0
- package/library/jsonapi/index.ts +40 -0
- package/library/jsonapi/parseListQuery.ts +291 -0
- package/library/jsonapi/types.ts +125 -0
- package/library/jwt/JwtEncoder.ts +40 -0
- package/library/jwt/JwtKeyRing.ts +164 -0
- package/library/jwt/JwtValidator.ts +210 -0
- package/library/jwt/TokenIssuer.ts +149 -0
- package/library/jwt/TokenService.ts +51 -0
- package/library/jwt/base64url.ts +61 -0
- package/library/jwt/claims.ts +36 -0
- package/library/jwt/errors.ts +44 -0
- package/library/jwt/index.ts +59 -0
- package/library/jwt/limits.ts +8 -0
- package/library/jwt/signing/Hs256Algorithm.ts +62 -0
- package/library/jwt/signing/Rs256Algorithm.ts +133 -0
- package/library/jwt/signing/SigningAlgorithm.ts +18 -0
- package/library/jwt/signing/pem.ts +30 -0
- package/library/openapi/codegen.ts +875 -0
- package/library/openapi/document.ts +326 -0
- package/library/openapi/index.ts +13 -0
- package/library/openapi/types.ts +69 -0
- package/library/openapi/ui.ts +182 -0
- package/library/orm/DatabaseFacade.ts +209 -0
- package/library/orm/DbContext.ts +107 -0
- package/library/orm/DbContextFactory.ts +25 -0
- package/library/orm/DbContextOptions.ts +33 -0
- package/library/orm/Metadata/DynamicModelBuilder.ts +497 -0
- package/library/orm/Metadata/KeyTuple.ts +36 -0
- package/library/orm/Metadata/ModelBuilder.ts +299 -0
- package/library/orm/Metadata/OrmModel.ts +80 -0
- package/library/orm/Metadata/ValueConverter.ts +57 -0
- package/library/orm/Metadata/conventions.ts +54 -0
- package/library/orm/Metadata/decorators.ts +396 -0
- package/library/orm/Metadata/types.ts +140 -0
- package/library/orm/Providers/OwnedStoreCatalog.reader.ts +1802 -0
- package/library/orm/Providers/PostgresDialect.ts +234 -0
- package/library/orm/Providers/PostgresProvider.ts +1494 -0
- package/library/orm/Providers/PostgresSchema.decoder.ts +107 -0
- package/library/orm/Providers/limits.ts +29 -0
- package/library/orm/Providers/operationDeadline.ts +43 -0
- package/library/orm/Providers/ormOwnedStoreRuntime.ts +19 -0
- package/library/orm/Providers/ormTransactionRuntime.ts +117 -0
- package/library/orm/Providers/propertyConversion.ts +14 -0
- package/library/orm/Providers/resolvedForeignKey.ts +16 -0
- package/library/orm/Providers/transactionCallbacks.ts +45 -0
- package/library/orm/Providers/transactionOutcome.ts +82 -0
- package/library/orm/Providers/transactionScopes.ts +78 -0
- package/library/orm/Providers/types.ts +207 -0
- package/library/orm/Query/DbSet.ts +78 -0
- package/library/orm/Query/EntityQuery.ts +247 -0
- package/library/orm/Query/ImmediateMutations.ts +226 -0
- package/library/orm/Query/IncludeLoader.ts +200 -0
- package/library/orm/Query/QueryPlan.ts +55 -0
- package/library/orm/Query/SqlTranslator.ts +195 -0
- package/library/orm/Query/conditions.ts +127 -0
- package/library/orm/Query/materialize.ts +39 -0
- package/library/orm/README.md +256 -0
- package/library/orm/Repository/README.md +684 -0
- package/library/orm/Repository/Repository.ts +68 -0
- package/library/orm/Saving/CommandBuilder.ts +139 -0
- package/library/orm/Saving/ExecutionStrategy.ts +128 -0
- package/library/orm/Saving/SaveExecutor.ts +413 -0
- package/library/orm/Saving/applyConventions.ts +64 -0
- package/library/orm/Schema/CheckExpression.ts +327 -0
- package/library/orm/Schema/ExactSchemaVerifier.ts +168 -0
- package/library/orm/Schema/ExpectedSchema.ts +43 -0
- package/library/orm/Schema/MigrationRunner.ts +146 -0
- package/library/orm/Schema/Migrator.ts +73 -0
- package/library/orm/Schema/OrmOwnedStore.ts +123 -0
- package/library/orm/Schema/OwnedStoreAdmission.ts +752 -0
- package/library/orm/Schema/OwnedStoreCanonical.ts +273 -0
- package/library/orm/Schema/OwnedStoreCatalog.ts +1325 -0
- package/library/orm/Schema/SafeAdditiveSchema.ts +100 -0
- package/library/orm/Schema/SchemaAdmission.ts +62 -0
- package/library/orm/Schema/SchemaDiffer.ts +78 -0
- package/library/orm/Schema/formatSchemaDifferences.ts +62 -0
- package/library/orm/Schema/introspection.ts +52 -0
- package/library/orm/Schema/physicalColumnTypes.ts +37 -0
- package/library/orm/Schema/tableKey.ts +26 -0
- package/library/orm/Tracking/ChangeTracker.ts +448 -0
- package/library/orm/Tracking/EntityState.ts +13 -0
- package/library/orm/Transactions/OrmTransaction.ts +30 -0
- package/library/orm/Transactions/TransactionScopeCoordinator.ts +377 -0
- package/library/orm/errors.ts +190 -0
- package/library/orm/index.ts +162 -0
- package/library/orm/runtime.ts +14 -0
- package/library/redaction/index.ts +166 -0
- package/library/ui/UiProfile.ts +77 -0
- package/library/ui/compiled-v1.ts +131 -0
- package/library/ui/compiler/compileUiSurfaceV1.ts +717 -0
- package/library/ui/compiler/contracts-v1.ts +25 -0
- package/library/ui/compiler/index.ts +12 -0
- package/library/ui/compiler/openApiIndex.ts +246 -0
- package/library/ui/defineUiProfile.ts +340 -0
- package/library/ui/diagnostics-v1.ts +33 -0
- package/library/ui/index.ts +129 -0
- package/library/ui/profile-v1.ts +191 -0
- package/library/ui/serialization.ts +130 -0
- package/library/ui/uiProfileAuthoring.ts +289 -0
- package/library/ui/uiProfileAuthoringMetadata.ts +78 -0
- package/library/validation/MessageRegistry.ts +144 -0
- package/library/validation/README.md +62 -0
- package/library/validation/RuleCompiler.ts +183 -0
- package/library/validation/RuleEngine.ts +401 -0
- package/library/validation/SPEC.md +579 -0
- package/library/validation/ValidationError.ts +37 -0
- package/library/validation/ValidationResult.ts +63 -0
- package/library/validation/Validator.ts +101 -0
- package/library/validation/index.ts +16 -0
- package/library/validation/metadata.ts +69 -0
- package/library/validation/modelValidatorAdapter.ts +119 -0
- package/library/validation/types/ValidationCode.ts +69 -0
- package/library/validation/types/ValidatorOptions.ts +153 -0
- package/package.json +80 -0
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
import { ModelBuildError } from "../errors";
|
|
2
|
+
import type { PropertyModel } from "../Metadata/types";
|
|
3
|
+
export type CheckScalar = null | boolean | number | string;
|
|
4
|
+
export type CheckAst = {
|
|
5
|
+
readonly kind: "compare";
|
|
6
|
+
readonly op: "=" | "<>" | ">" | ">=" | "<" | "<=";
|
|
7
|
+
readonly left: string;
|
|
8
|
+
readonly right: string | CheckScalar;
|
|
9
|
+
} | {
|
|
10
|
+
readonly kind: "in";
|
|
11
|
+
readonly left: string;
|
|
12
|
+
readonly values: readonly CheckScalar[];
|
|
13
|
+
} | {
|
|
14
|
+
readonly kind: "null";
|
|
15
|
+
readonly left: string;
|
|
16
|
+
readonly not: boolean;
|
|
17
|
+
} | {
|
|
18
|
+
readonly kind: "and" | "or";
|
|
19
|
+
readonly left: CheckAst;
|
|
20
|
+
readonly right: CheckAst;
|
|
21
|
+
} | {
|
|
22
|
+
readonly kind: "not";
|
|
23
|
+
readonly inner: CheckAst;
|
|
24
|
+
};
|
|
25
|
+
export interface CheckExpression {
|
|
26
|
+
readonly ast: CheckAst;
|
|
27
|
+
and(other: CheckExpression): CheckExpression;
|
|
28
|
+
or(other: CheckExpression): CheckExpression;
|
|
29
|
+
not(): CheckExpression;
|
|
30
|
+
}
|
|
31
|
+
export interface CheckOperand<T = unknown> {
|
|
32
|
+
eq(value: CheckOperand<T> | T | null): CheckExpression;
|
|
33
|
+
ne(value: CheckOperand<T> | T | null): CheckExpression;
|
|
34
|
+
gt(value: CheckOperand<T> | T): CheckExpression;
|
|
35
|
+
gte(value: CheckOperand<T> | T): CheckExpression;
|
|
36
|
+
lt(value: CheckOperand<T> | T): CheckExpression;
|
|
37
|
+
lte(value: CheckOperand<T> | T): CheckExpression;
|
|
38
|
+
in(values: readonly T[]): CheckExpression;
|
|
39
|
+
isNull(): CheckExpression;
|
|
40
|
+
isNotNull(): CheckExpression;
|
|
41
|
+
}
|
|
42
|
+
export type CheckField<T extends object> = {
|
|
43
|
+
readonly [K in Extract<keyof T, string>]-?: CheckOperand<T[K]>;
|
|
44
|
+
};
|
|
45
|
+
export type CheckPredicate<T extends object> = (fields: CheckField<T>) => CheckExpression;
|
|
46
|
+
const MAX_CHECK_IN_VALUES = 100;
|
|
47
|
+
class Expr implements CheckExpression {
|
|
48
|
+
constructor(readonly ast: CheckAst) {
|
|
49
|
+
}
|
|
50
|
+
and(other: CheckExpression) {
|
|
51
|
+
return new Expr({ kind: "and", left: this.ast, right: other.ast });
|
|
52
|
+
}
|
|
53
|
+
or(other: CheckExpression) {
|
|
54
|
+
return new Expr({ kind: "or", left: this.ast, right: other.ast });
|
|
55
|
+
}
|
|
56
|
+
not() {
|
|
57
|
+
return new Expr({ kind: "not", inner: this.ast });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
class Field implements CheckOperand {
|
|
61
|
+
constructor(readonly name: string) {
|
|
62
|
+
}
|
|
63
|
+
private compare(op: "=" | "<>" | ">" | ">=" | "<" | "<=", value: unknown) {
|
|
64
|
+
return new Expr({ kind: "compare", op, left: this.name, right: operand(value) });
|
|
65
|
+
}
|
|
66
|
+
eq(value: unknown) {
|
|
67
|
+
return this.compare("=", value);
|
|
68
|
+
}
|
|
69
|
+
ne(value: unknown) {
|
|
70
|
+
return this.compare("<>", value);
|
|
71
|
+
}
|
|
72
|
+
gt(value: unknown) {
|
|
73
|
+
return this.compare(">", value);
|
|
74
|
+
}
|
|
75
|
+
gte(value: unknown) {
|
|
76
|
+
return this.compare(">=", value);
|
|
77
|
+
}
|
|
78
|
+
lt(value: unknown) {
|
|
79
|
+
return this.compare("<", value);
|
|
80
|
+
}
|
|
81
|
+
lte(value: unknown) {
|
|
82
|
+
return this.compare("<=", value);
|
|
83
|
+
}
|
|
84
|
+
in(values: readonly unknown[]) {
|
|
85
|
+
if (!values.length || values.length > MAX_CHECK_IN_VALUES)
|
|
86
|
+
throw new ModelBuildError(`CHECK IN requires between 1 and ${MAX_CHECK_IN_VALUES} literals.`);
|
|
87
|
+
return new Expr({ kind: "in", left: this.name, values: values.map(literal) });
|
|
88
|
+
}
|
|
89
|
+
isNull() {
|
|
90
|
+
return new Expr({ kind: "null", left: this.name, not: false });
|
|
91
|
+
}
|
|
92
|
+
isNotNull() {
|
|
93
|
+
return new Expr({ kind: "null", left: this.name, not: true });
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
function operand(value: unknown): string | CheckScalar {
|
|
97
|
+
return value instanceof Field ? `\u0000${value.name}` : literal(value);
|
|
98
|
+
}
|
|
99
|
+
function literal(value: unknown): CheckScalar {
|
|
100
|
+
if (value === null || typeof value === "boolean")
|
|
101
|
+
return value;
|
|
102
|
+
if (typeof value === "number" && Number.isFinite(value) && Number.isSafeInteger(value))
|
|
103
|
+
return value;
|
|
104
|
+
if (typeof value === "string" && value.length <= 1024)
|
|
105
|
+
return value;
|
|
106
|
+
throw new ModelBuildError("CHECK literal must be a bounded scalar literal.");
|
|
107
|
+
}
|
|
108
|
+
export function compileCheck<T extends object>(predicate: CheckPredicate<T>): CheckAst {
|
|
109
|
+
const proxy = new Proxy({}, { get: (_target, name) => typeof name === "string" ? new Field(name) : undefined }) as CheckField<T>;
|
|
110
|
+
return predicate(proxy).ast;
|
|
111
|
+
}
|
|
112
|
+
/** Projects a property-keyed CHECK AST into a physical identifier domain. */
|
|
113
|
+
export function projectCheckAstIdentifiers(ast: CheckAst, resolve: (propertyName: string) => string): CheckAst {
|
|
114
|
+
switch (ast.kind) {
|
|
115
|
+
case "compare": return {
|
|
116
|
+
...ast, left: resolve(ast.left), right: typeof ast.right === "string" && ast.right.startsWith("\0") ? `\0${resolve(ast.right.slice(1))}` : ast.right
|
|
117
|
+
};
|
|
118
|
+
case "in": return { ...ast, left: resolve(ast.left), values: [...ast.values] };
|
|
119
|
+
case "null": return { ...ast, left: resolve(ast.left) };
|
|
120
|
+
case "and":
|
|
121
|
+
case "or": return {
|
|
122
|
+
...ast, left: projectCheckAstIdentifiers(ast.left, resolve), right: projectCheckAstIdentifiers(ast.right, resolve)
|
|
123
|
+
};
|
|
124
|
+
case "not": return { ...ast, inner: projectCheckAstIdentifiers(ast.inner, resolve) };
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
/** Validates the complete closed AST against the compiled entity columns before DDL/snapshot rendering. */
|
|
128
|
+
export function validateCheckAst(ast: CheckAst, properties: readonly PropertyModel[]): void {
|
|
129
|
+
const byName = new Map(properties.map((property) => [property.propertyName, property]));
|
|
130
|
+
const property = (name: string): PropertyModel => {
|
|
131
|
+
const value = byName.get(name);
|
|
132
|
+
if (!value)
|
|
133
|
+
throw new ModelBuildError(`CHECK references unknown property "${name}".`);
|
|
134
|
+
return value;
|
|
135
|
+
};
|
|
136
|
+
const validateLiteral = (column: PropertyModel, value: CheckScalar): void => {
|
|
137
|
+
if (value === null)
|
|
138
|
+
throw new ModelBuildError(`CHECK comparison for "${column.propertyName}" must use isNull()/isNotNull().`);
|
|
139
|
+
const compatible = (column.type === "integer" || column.type === "real")
|
|
140
|
+
? typeof value === "number"
|
|
141
|
+
: (column.type === "text" || column.type === "datetime")
|
|
142
|
+
? typeof value === "string"
|
|
143
|
+
: column.type === "boolean"
|
|
144
|
+
? typeof value === "boolean"
|
|
145
|
+
: false;
|
|
146
|
+
if (!compatible)
|
|
147
|
+
throw new ModelBuildError(`CHECK literal is incompatible with property "${column.propertyName}".`);
|
|
148
|
+
};
|
|
149
|
+
const visit = (node: CheckAst): void => {
|
|
150
|
+
switch (node.kind) {
|
|
151
|
+
case "and":
|
|
152
|
+
case "or":
|
|
153
|
+
visit(node.left);
|
|
154
|
+
visit(node.right);
|
|
155
|
+
return;
|
|
156
|
+
case "not":
|
|
157
|
+
visit(node.inner);
|
|
158
|
+
return;
|
|
159
|
+
case "null":
|
|
160
|
+
property(node.left);
|
|
161
|
+
return;
|
|
162
|
+
case "in": {
|
|
163
|
+
const left = property(node.left);
|
|
164
|
+
if (!node.values.length || node.values.length > MAX_CHECK_IN_VALUES)
|
|
165
|
+
throw new ModelBuildError(`CHECK IN requires between 1 and ${MAX_CHECK_IN_VALUES} literals.`);
|
|
166
|
+
for (const value of node.values)
|
|
167
|
+
validateLiteral(left, value);
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
case "compare": {
|
|
171
|
+
const left = property(node.left);
|
|
172
|
+
const rightName = typeof node.right === "string" && node.right.startsWith("\0") ? node.right.slice(1) : undefined;
|
|
173
|
+
if (rightName !== undefined) {
|
|
174
|
+
const right = property(rightName);
|
|
175
|
+
if (left.type !== right.type)
|
|
176
|
+
throw new ModelBuildError(`CHECK column comparison requires identical column types ("${left.propertyName}", "${right.propertyName}").`);
|
|
177
|
+
}
|
|
178
|
+
else {
|
|
179
|
+
validateLiteral(left, node.right as CheckScalar);
|
|
180
|
+
}
|
|
181
|
+
if ([">", ">=", "<", "<="].includes(node.op) && !["integer", "real", "text", "datetime"].includes(left.type)) {
|
|
182
|
+
throw new ModelBuildError(`CHECK ordered comparison is not supported for property "${left.propertyName}".`);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
visit(ast);
|
|
188
|
+
}
|
|
189
|
+
export function renderCheck(ast: CheckAst, quote: (name: string) => string): string {
|
|
190
|
+
switch (ast.kind) {
|
|
191
|
+
case "compare": return `${quote(ast.left)} ${ast.op} ${typeof ast.right === "string" && ast.right.startsWith("\0") ? quote(ast.right.slice(1)) : sqlLiteral(ast.right as CheckScalar)}`;
|
|
192
|
+
case "in": return `${quote(ast.left)} IN (${ast.values.map(sqlLiteral).join(", ")})`;
|
|
193
|
+
case "null": return `${quote(ast.left)} IS ${ast.not ? "NOT " : ""}NULL`;
|
|
194
|
+
case "and": return `(${renderCheck(ast.left, quote)} AND ${renderCheck(ast.right, quote)})`;
|
|
195
|
+
case "or": return `(${renderCheck(ast.left, quote)} OR ${renderCheck(ast.right, quote)})`;
|
|
196
|
+
case "not": return `(NOT ${renderCheck(ast.inner, quote)})`;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
/** Closed parser for SQL emitted by `renderCheck`; unknown catalog syntax returns undefined. */
|
|
200
|
+
export function parseRenderedCheck(value: string): CheckAst | undefined {
|
|
201
|
+
const source = stripOuter(value.trim());
|
|
202
|
+
const logical = splitTopLevel(source, " AND ") ?? splitTopLevel(source, " OR ");
|
|
203
|
+
if (logical) {
|
|
204
|
+
const left = parseRenderedCheck(logical.left);
|
|
205
|
+
const right = parseRenderedCheck(logical.right);
|
|
206
|
+
return left && right ? { kind: logical.operator === " AND " ? "and" : "or", left, right } : undefined;
|
|
207
|
+
}
|
|
208
|
+
const negated = source.match(/^NOT\s+(.+)$/isu);
|
|
209
|
+
if (negated) {
|
|
210
|
+
const inner = parseRenderedCheck(negated[1]!);
|
|
211
|
+
return inner ? { kind: "not", inner } : undefined;
|
|
212
|
+
}
|
|
213
|
+
const nullable = source.match(/^(.+?)\s+IS\s+(NOT\s+)?NULL$/isu);
|
|
214
|
+
if (nullable) {
|
|
215
|
+
const left = parseIdentifier(nullable[1]!);
|
|
216
|
+
return left ? { kind: "null", left, not: Boolean(nullable[2]) } : undefined;
|
|
217
|
+
}
|
|
218
|
+
const inMatch = source.match(/^(.+?)\s+IN\s*\((.*)\)$/isu);
|
|
219
|
+
if (inMatch) {
|
|
220
|
+
const left = parseIdentifier(inMatch[1]!);
|
|
221
|
+
const values = splitLiterals(inMatch[2]!);
|
|
222
|
+
return left && values ? { kind: "in", left, values } : undefined;
|
|
223
|
+
}
|
|
224
|
+
const comparison = source.match(/^(.+?)\s*(=|<>|>=|<=|>|<)\s*(.+)$/su);
|
|
225
|
+
if (!comparison)
|
|
226
|
+
return undefined;
|
|
227
|
+
const left = parseIdentifier(comparison[1]!);
|
|
228
|
+
const right = parseOperand(comparison[3]!);
|
|
229
|
+
return left && right !== undefined ? { kind: "compare", left, op: comparison[2]! as "=" | "<>" | ">" | ">=" | "<" | "<=", right } : undefined;
|
|
230
|
+
}
|
|
231
|
+
function stripOuter(value: string): string {
|
|
232
|
+
while (value.startsWith("(") && value.endsWith(")") && balancedOuter(value))
|
|
233
|
+
value = value.slice(1, -1).trim();
|
|
234
|
+
return value;
|
|
235
|
+
}
|
|
236
|
+
function balancedOuter(value: string): boolean {
|
|
237
|
+
let depth = 0;
|
|
238
|
+
let quoted = false;
|
|
239
|
+
for (let i = 0; i < value.length; i++) {
|
|
240
|
+
const char = value[i]!;
|
|
241
|
+
if (char === "'" && value[i - 1] !== "'")
|
|
242
|
+
quoted = !quoted;
|
|
243
|
+
if (!quoted) {
|
|
244
|
+
if (char === "(")
|
|
245
|
+
depth++;
|
|
246
|
+
if (char === ")")
|
|
247
|
+
depth--;
|
|
248
|
+
if (depth === 0 && i < value.length - 1)
|
|
249
|
+
return false;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
return depth === 0 && !quoted;
|
|
253
|
+
}
|
|
254
|
+
function splitTopLevel(value: string, separator: " AND " | " OR "): {
|
|
255
|
+
left: string;
|
|
256
|
+
right: string;
|
|
257
|
+
operator: typeof separator;
|
|
258
|
+
} | undefined {
|
|
259
|
+
let depth = 0;
|
|
260
|
+
let quoted = false;
|
|
261
|
+
for (let i = 0; i <= value.length - separator.length; i++) {
|
|
262
|
+
const char = value[i]!;
|
|
263
|
+
if (char === "'" && value[i - 1] !== "'")
|
|
264
|
+
quoted = !quoted;
|
|
265
|
+
if (!quoted) {
|
|
266
|
+
if (char === "(")
|
|
267
|
+
depth++;
|
|
268
|
+
else if (char === ")")
|
|
269
|
+
depth--;
|
|
270
|
+
else if (depth === 0 && value.slice(i, i + separator.length).toUpperCase() === separator)
|
|
271
|
+
return { left: value.slice(0, i), right: value.slice(i + separator.length), operator: separator };
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
return undefined;
|
|
275
|
+
}
|
|
276
|
+
function parseIdentifier(value: string): string | undefined {
|
|
277
|
+
const identifier = value.trim();
|
|
278
|
+
const quoted = identifier.match(/^"((?:""|[^"])*)"$/u);
|
|
279
|
+
return quoted ? quoted[1]!.replaceAll('""', '"') : /^[A-Za-z_][A-Za-z0-9_]*$/u.test(identifier) ? identifier : undefined;
|
|
280
|
+
}
|
|
281
|
+
function parseOperand(value: string): string | CheckScalar | undefined {
|
|
282
|
+
const raw = value.trim();
|
|
283
|
+
if (/^(TRUE|FALSE)$/i.test(raw))
|
|
284
|
+
return /^TRUE$/i.test(raw);
|
|
285
|
+
const identifier = parseIdentifier(raw);
|
|
286
|
+
if (identifier)
|
|
287
|
+
return `\0${identifier}`;
|
|
288
|
+
return parseLiteral(raw);
|
|
289
|
+
}
|
|
290
|
+
function splitLiterals(value: string): CheckScalar[] | undefined {
|
|
291
|
+
const parts: string[] = [];
|
|
292
|
+
let start = 0;
|
|
293
|
+
let quoted = false;
|
|
294
|
+
for (let i = 0; i < value.length; i++) {
|
|
295
|
+
if (value[i] === "'" && value[i - 1] !== "'")
|
|
296
|
+
quoted = !quoted;
|
|
297
|
+
if (value[i] === "," && !quoted) {
|
|
298
|
+
parts.push(value.slice(start, i));
|
|
299
|
+
start = i + 1;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
if (quoted)
|
|
303
|
+
return undefined;
|
|
304
|
+
parts.push(value.slice(start));
|
|
305
|
+
const parsed = parts.map(parseLiteral);
|
|
306
|
+
return parsed.some((item) => item === undefined) ? undefined : parsed as CheckScalar[];
|
|
307
|
+
}
|
|
308
|
+
function parseLiteral(value: string): CheckScalar | undefined {
|
|
309
|
+
const raw = value.trim();
|
|
310
|
+
if (/^NULL$/i.test(raw))
|
|
311
|
+
return null;
|
|
312
|
+
if (/^(TRUE|FALSE)$/i.test(raw))
|
|
313
|
+
return /^TRUE$/i.test(raw);
|
|
314
|
+
if (/^-?\d+$/u.test(raw))
|
|
315
|
+
return Number(raw);
|
|
316
|
+
const quoted = raw.match(/^'((?:''|[^'])*)'$/su);
|
|
317
|
+
return quoted ? quoted[1]!.replaceAll("''", "'") : undefined;
|
|
318
|
+
}
|
|
319
|
+
function sqlLiteral(value: CheckScalar): string {
|
|
320
|
+
if (value === null)
|
|
321
|
+
return "NULL";
|
|
322
|
+
if (typeof value === "boolean")
|
|
323
|
+
return value ? "TRUE" : "FALSE";
|
|
324
|
+
if (typeof value === "number")
|
|
325
|
+
return String(value);
|
|
326
|
+
return `'${value.replaceAll("'", "''")}'`;
|
|
327
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import type { OrmExpectedSchema } from "./ExpectedSchema";
|
|
2
|
+
import type { IntrospectedSchema, IntrospectedTable } from "./introspection";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
export type SchemaDifferenceCode = "table.missing" | "column.missing" | "column.unexpected" | "column.type" | "column.nullability" | "column.default" | "column.generation" | "primaryKey.missing" | "primaryKey.unexpected" | "primaryKey.name" | "primaryKey.columns" | "index.missing" | "index.unexpected" | "index.name" | "index.columns" | "index.uniqueness" | "index.method" | "index.unsupportedShape" | "foreignKey.missing" | "foreignKey.unexpected" | "foreignKey.name" | "foreignKey.columns" | "foreignKey.target" | "foreignKey.actions" | "foreignKey.deferrable" | "foreignKey.match" | "check.missing" | "check.unexpected" | "check.name" | "check.expression" | "catalog.unsupported";
|
|
5
|
+
export interface SafeSchemaDescriptor {
|
|
6
|
+
readonly kind: "absent" | "present" | "canonicalType" | "canonicalDefault" | "canonicalGeneration" | "canonicalExpression" | "orderedColumns" | "referentialActions" | "unsupported";
|
|
7
|
+
readonly value?: string;
|
|
8
|
+
readonly values?: readonly string[];
|
|
9
|
+
readonly hash?: `sha256:${string}`;
|
|
10
|
+
}
|
|
11
|
+
export interface SchemaDifference {
|
|
12
|
+
readonly code: SchemaDifferenceCode;
|
|
13
|
+
readonly schema: string;
|
|
14
|
+
readonly table: string;
|
|
15
|
+
readonly objectName?: string;
|
|
16
|
+
readonly expected?: SafeSchemaDescriptor;
|
|
17
|
+
readonly actual?: SafeSchemaDescriptor;
|
|
18
|
+
}
|
|
19
|
+
export interface SchemaVerificationResult {
|
|
20
|
+
readonly compatible: boolean;
|
|
21
|
+
readonly differences: readonly SchemaDifference[];
|
|
22
|
+
}
|
|
23
|
+
const absent: SafeSchemaDescriptor = { kind: "absent" };
|
|
24
|
+
const present: SafeSchemaDescriptor = { kind: "present" };
|
|
25
|
+
const unsupported: SafeSchemaDescriptor = { kind: "unsupported" };
|
|
26
|
+
const value = (kind: SafeSchemaDescriptor["kind"], raw: unknown): SafeSchemaDescriptor => {
|
|
27
|
+
if (kind === "canonicalDefault" || kind === "canonicalExpression")
|
|
28
|
+
return {
|
|
29
|
+
kind, hash: `sha256:${createHash("sha256").update(`bazis.orm.schema-diagnostic/${kind}/v1\0${stable(raw)}`).digest("hex")}`
|
|
30
|
+
};
|
|
31
|
+
if (Array.isArray(raw))
|
|
32
|
+
return { kind, values: raw.map(String) };
|
|
33
|
+
return { kind, value: String(raw) };
|
|
34
|
+
};
|
|
35
|
+
/** Owner-scoped, deterministic comparison. Ordinary physical column order is deliberately ignored. */
|
|
36
|
+
export class ExactSchemaVerifier {
|
|
37
|
+
verify(expected: OrmExpectedSchema, actual: IntrospectedSchema, allowMissing = false): SchemaVerificationResult {
|
|
38
|
+
const differences: SchemaDifference[] = [];
|
|
39
|
+
const add = (code: SchemaDifferenceCode, schema: string, table: string, objectName?: string, expectedValue?: SafeSchemaDescriptor, actualValue?: SafeSchemaDescriptor) => differences.push({ code, schema, table, objectName, expected: expectedValue, actual: actualValue });
|
|
40
|
+
for (const table of expected.tables) {
|
|
41
|
+
const name = `${table.schema}.${table.table}`;
|
|
42
|
+
const found = actual.tables.get(name);
|
|
43
|
+
if (!found) {
|
|
44
|
+
if (!allowMissing)
|
|
45
|
+
add("table.missing", table.schema, table.table, name, present, absent);
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
this.table(table, found, table.table, (code, _table, objectName, expectedValue, actualValue) => add(code, table.schema, table.table, objectName, expectedValue, actualValue));
|
|
49
|
+
}
|
|
50
|
+
differences.sort((a, b) => Buffer.compare(Buffer.from(`${a.schema}\0${a.table}\0${a.code}\0${a.objectName ?? ""}`, "utf8"), Buffer.from(`${b.schema}\0${b.table}\0${b.code}\0${b.objectName ?? ""}`, "utf8")));
|
|
51
|
+
return { compatible: differences.length === 0, differences };
|
|
52
|
+
}
|
|
53
|
+
private table(expected: OrmExpectedSchema["tables"][number], actual: IntrospectedTable, table: string, add: (code: SchemaDifferenceCode, table: string, objectName?: string, expected?: SafeSchemaDescriptor, actual?: SafeSchemaDescriptor) => void): void {
|
|
54
|
+
if (actual.unsupported)
|
|
55
|
+
add("catalog.unsupported", table, table, undefined, unsupported);
|
|
56
|
+
const columns = new Map(expected.columns.map((column) => [column.column, column]));
|
|
57
|
+
for (const name of actual.columns.keys())
|
|
58
|
+
if (!columns.has(name))
|
|
59
|
+
add("column.unexpected", table, name, absent, present);
|
|
60
|
+
for (const [name, column] of columns) {
|
|
61
|
+
const found = actual.columns.get(name);
|
|
62
|
+
if (!found) {
|
|
63
|
+
add("column.missing", table, name, present, absent);
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
if (found.unsupported)
|
|
67
|
+
add("catalog.unsupported", table, name, undefined, unsupported);
|
|
68
|
+
if (found.physicalType !== column.physicalType)
|
|
69
|
+
add("column.type", table, name, value("canonicalType", column.physicalType), value("canonicalType", found.physicalType ?? "unknown"));
|
|
70
|
+
if (found.notNull === column.nullable)
|
|
71
|
+
add("column.nullability", table, name, value("present", String(!column.nullable)), value("present", String(found.notNull)));
|
|
72
|
+
if (stable(found.default) !== stable(column.default))
|
|
73
|
+
add("column.default", table, name, value("canonicalDefault", column.default), value("canonicalDefault", found.default ?? { kind: "unknown" }));
|
|
74
|
+
if (found.generation !== column.generation)
|
|
75
|
+
add("column.generation", table, name, value("canonicalGeneration", column.generation), value("canonicalGeneration", found.generation ?? "unknown"));
|
|
76
|
+
}
|
|
77
|
+
if (!actual.primaryKey)
|
|
78
|
+
add("primaryKey.missing", table, expected.primaryKey.name, present, absent);
|
|
79
|
+
else {
|
|
80
|
+
if (actual.primaryKey.name !== expected.primaryKey.name)
|
|
81
|
+
add("primaryKey.name", table, expected.primaryKey.name, value("present", expected.primaryKey.name), value("present", actual.primaryKey.name));
|
|
82
|
+
if (!same(actual.primaryKey.columns, expected.primaryKey.columns))
|
|
83
|
+
add("primaryKey.columns", table, expected.primaryKey.name, value("orderedColumns", expected.primaryKey.columns), value("orderedColumns", actual.primaryKey.columns));
|
|
84
|
+
}
|
|
85
|
+
const ordinary = actual.indexes.filter((index) => !index.backingConstraint);
|
|
86
|
+
const expectedIndexes = new Map(expected.indexes.map((index) => [index.name, index]));
|
|
87
|
+
for (const index of ordinary) {
|
|
88
|
+
if (index.unsupported || index.method !== "btree" || index.predicate || index.columns.length === 0)
|
|
89
|
+
add("index.unsupportedShape", table, index.name, undefined, unsupported);
|
|
90
|
+
else if (!expectedIndexes.has(index.name))
|
|
91
|
+
add("index.unexpected", table, index.name, absent, present);
|
|
92
|
+
}
|
|
93
|
+
for (const [name, index] of expectedIndexes) {
|
|
94
|
+
const found = ordinary.find((item) => item.name === name) ?? (ordinary.length === 1 ? ordinary[0] : undefined);
|
|
95
|
+
if (!found) {
|
|
96
|
+
add("index.missing", table, name, present, absent);
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
if (found.name !== name)
|
|
100
|
+
add("index.name", table, name, value("present", name), value("present", found.name));
|
|
101
|
+
if (found.unsupported || found.predicate || found.columns.length === 0) {
|
|
102
|
+
add("catalog.unsupported", table, name, undefined, unsupported);
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
if (found.unique !== index.unique)
|
|
106
|
+
add("index.uniqueness", table, name, value("present", String(index.unique)), value("present", String(found.unique)));
|
|
107
|
+
if (!same(found.columns, index.columns))
|
|
108
|
+
add("index.columns", table, name, value("orderedColumns", index.columns), value("orderedColumns", found.columns));
|
|
109
|
+
if (found.method !== "btree")
|
|
110
|
+
add("index.method", table, name, value("present", "btree"), value("present", found.method ?? "unknown"));
|
|
111
|
+
}
|
|
112
|
+
const foreignKeys = actual.foreignKeys ?? [];
|
|
113
|
+
const expectedForeignKeys = new Map(expected.foreignKeys.map((foreignKey) => [foreignKey.name, foreignKey]));
|
|
114
|
+
for (const foreignKey of foreignKeys)
|
|
115
|
+
if (foreignKey.unsupported)
|
|
116
|
+
add("catalog.unsupported", table, foreignKey.name, undefined, unsupported);
|
|
117
|
+
else if (foreignKey.deferrable)
|
|
118
|
+
add("foreignKey.deferrable", table, foreignKey.name, absent, present);
|
|
119
|
+
else if (!expectedForeignKeys.has(foreignKey.name))
|
|
120
|
+
add("foreignKey.unexpected", table, foreignKey.name, absent, present);
|
|
121
|
+
for (const [name, foreignKey] of expectedForeignKeys) {
|
|
122
|
+
const found = foreignKeys.find((item) => item.name === name) ?? (foreignKeys.length === 1 ? foreignKeys[0] : undefined);
|
|
123
|
+
if (!found) {
|
|
124
|
+
add("foreignKey.missing", table, name, present, absent);
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
const targetSchema = found.targetSchema ?? "public";
|
|
128
|
+
if (found.name !== name)
|
|
129
|
+
add("foreignKey.name", table, name, value("present", name), value("present", found.name));
|
|
130
|
+
if (!same(found.columns, foreignKey.columns))
|
|
131
|
+
add("foreignKey.columns", table, name, value("orderedColumns", foreignKey.columns), value("orderedColumns", found.columns));
|
|
132
|
+
if (found.targetTable !== foreignKey.target.table || targetSchema !== foreignKey.target.schema || !same(found.targetColumns, foreignKey.targetColumns))
|
|
133
|
+
add("foreignKey.target", table, name, value("orderedColumns", [foreignKey.target.schema, foreignKey.target.table, ...foreignKey.targetColumns]), value("orderedColumns", [targetSchema, found.targetTable, ...found.targetColumns]));
|
|
134
|
+
if (found.onDelete !== foreignKey.onDelete || found.onUpdate !== foreignKey.onUpdate)
|
|
135
|
+
add("foreignKey.actions", table, name, value("referentialActions", [foreignKey.onDelete, foreignKey.onUpdate]), value("referentialActions", [found.onDelete, found.onUpdate]));
|
|
136
|
+
}
|
|
137
|
+
const checks = actual.checks ?? [];
|
|
138
|
+
const expectedChecks = new Map(expected.checks.map((check) => [check.name, check]));
|
|
139
|
+
for (const check of checks)
|
|
140
|
+
if (check.unsupported)
|
|
141
|
+
add("catalog.unsupported", table, check.name, undefined, unsupported);
|
|
142
|
+
else if (!expectedChecks.has(check.name))
|
|
143
|
+
add("check.unexpected", table, check.name, absent, present);
|
|
144
|
+
for (const [name, check] of expectedChecks) {
|
|
145
|
+
const found = checks.find((item) => item.name === name) ?? (checks.length === 1 ? checks[0] : undefined);
|
|
146
|
+
if (!found)
|
|
147
|
+
add("check.missing", table, name, present, absent);
|
|
148
|
+
else {
|
|
149
|
+
if (found.name !== name)
|
|
150
|
+
add("check.name", table, name, value("present", name), value("present", found.name));
|
|
151
|
+
if (stable(found.expression) !== stable(check.expression))
|
|
152
|
+
add("check.expression", table, name, value("canonicalExpression", check.expression), value("canonicalExpression", found.expression));
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
function same<T>(a: readonly T[], b: readonly T[]): boolean {
|
|
158
|
+
return a.length === b.length && a.every((entry, index) => stable(entry) === stable(b[index]));
|
|
159
|
+
}
|
|
160
|
+
function stable(value: unknown): string {
|
|
161
|
+
if (Array.isArray(value))
|
|
162
|
+
return `[${value.map(stable).join(",")}]`;
|
|
163
|
+
if (value !== null && typeof value === "object") {
|
|
164
|
+
const object = value as Record<string, unknown>;
|
|
165
|
+
return `{${Object.keys(object).sort().map((key) => `${JSON.stringify(key)}:${stable(object[key])}`).join(",")}}`;
|
|
166
|
+
}
|
|
167
|
+
return JSON.stringify(value);
|
|
168
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { EntityModel } from "../Metadata/types";
|
|
2
|
+
import type { OrmModel } from "../Metadata/OrmModel";
|
|
3
|
+
import type { CanonicalDefault, GenerationStrategy } from "./introspection";
|
|
4
|
+
import { projectCheckAstIdentifiers } from "./CheckExpression";
|
|
5
|
+
import { physicalColumnTypes } from "./physicalColumnTypes";
|
|
6
|
+
import { physicalTableIdentity } from "./tableKey";
|
|
7
|
+
|
|
8
|
+
export interface ExpectedColumn { readonly property: string; readonly column: string; readonly physicalType: string; readonly nullable: boolean; readonly default: CanonicalDefault; readonly generation: GenerationStrategy }
|
|
9
|
+
export interface ExpectedTable { readonly schema: string; readonly table: string; readonly columns: readonly ExpectedColumn[]; readonly primaryKey: { readonly name: string; readonly columns: readonly string[] }; readonly indexes: readonly { readonly name: string; readonly columns: readonly string[]; readonly unique: boolean; readonly method: "btree" }[]; readonly foreignKeys: readonly { readonly name: string; readonly columns: readonly string[]; readonly target: { readonly schema: string; readonly table: string }; readonly targetColumns: readonly string[]; readonly onDelete: string; readonly onUpdate: string }[]; readonly checks: readonly { readonly name: string; readonly expression: unknown }[] }
|
|
10
|
+
export interface OrmExpectedSchema { readonly tables: readonly ExpectedTable[] }
|
|
11
|
+
|
|
12
|
+
const schemaOf = (model: EntityModel) => physicalTableIdentity(model).schema?.trim() || "public";
|
|
13
|
+
|
|
14
|
+
/** Pure expected physical contract compiled solely from the explicit entity unit. */
|
|
15
|
+
export function compileExpectedSchema(models: OrmModel): OrmExpectedSchema {
|
|
16
|
+
const byCtor = new Map(models.entities.map((model) => [model.ctor, model]));
|
|
17
|
+
const identities = new Set<string>();
|
|
18
|
+
const types = physicalColumnTypes(models.entities);
|
|
19
|
+
const tables = models.entities.map((model) => compileTable(model, byCtor, identities, types));
|
|
20
|
+
return { tables: Object.freeze(tables.sort((a, b) => Buffer.compare(Buffer.from(`${a.schema}\0${a.table}`, "utf8"), Buffer.from(`${b.schema}\0${b.table}`, "utf8")))) };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function compileTable(model: EntityModel, byCtor: ReadonlyMap<EntityModel["ctor"], EntityModel>, identities: Set<string>, types: ReturnType<typeof physicalColumnTypes>): ExpectedTable {
|
|
24
|
+
const schema = schemaOf(model);
|
|
25
|
+
const table = physicalTableIdentity(model).table;
|
|
26
|
+
const identity = `${schema}\0${table}`;
|
|
27
|
+
if (identities.has(identity)) throw new Error("ORM_SCHEMA_OWNERSHIP_CONFLICT");
|
|
28
|
+
identities.add(identity);
|
|
29
|
+
const columns = model.properties.map((property) => ({
|
|
30
|
+
property: property.propertyName,
|
|
31
|
+
column: property.columnName,
|
|
32
|
+
physicalType: types.get(property)!,
|
|
33
|
+
nullable: !property.required,
|
|
34
|
+
default: property.databaseDefault,
|
|
35
|
+
generation: property.generation === "identity" ? "identityByDefault" as const : property.generation === "uuid" ? "uuidDefault" as const : "none" as const,
|
|
36
|
+
}));
|
|
37
|
+
const foreignKeys = model.foreignKeys.map((foreignKey) => {
|
|
38
|
+
const target = byCtor.get(foreignKey.target());
|
|
39
|
+
if (!target) throw new Error("ORM_SCHEMA_CROSS_UNIT_FOREIGN_KEY");
|
|
40
|
+
return { name: foreignKey.name ?? `fk_${table}_${foreignKey.properties.join("_")}`, columns: foreignKey.properties.map((name) => model.propertyByName(name)!.columnName), target: { schema: schemaOf(target), table: physicalTableIdentity(target).table }, targetColumns: target.key.map((property) => property.columnName), onDelete: foreignKey.onDelete, onUpdate: foreignKey.onUpdate };
|
|
41
|
+
});
|
|
42
|
+
return Object.freeze({ schema, table, columns: Object.freeze(columns), primaryKey: Object.freeze({ name: model.keyName ?? `pk_${table}`, columns: Object.freeze(model.key.map((property) => property.columnName)) }), indexes: Object.freeze(model.indexes.map((index) => Object.freeze({ ...index, columns: Object.freeze([...index.columns]), method: "btree" as const }))), foreignKeys: Object.freeze(foreignKeys), checks: Object.freeze(model.checks.map((check) => Object.freeze({ name: check.name, expression: projectCheckAstIdentifiers(check.expression, (name) => model.propertyByName(name)!.columnName) }))) });
|
|
43
|
+
}
|