@alneas/eaos-server 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +41 -0
- package/LICENSE +21 -0
- package/README.ja.md +49 -0
- package/README.md +46 -2
- package/dist/agentic/agent-jobs.d.ts +333 -0
- package/dist/agentic/agent-jobs.js +15 -0
- package/dist/agentic/agent-jobs.js.map +1 -0
- package/dist/agentic/agent-node.d.ts +40 -0
- package/dist/agentic/agent-node.js +7 -0
- package/dist/agentic/agent-node.js.map +1 -0
- package/dist/agentic/agent-runner.d.ts +33 -0
- package/dist/agentic/agent-runner.js +7 -0
- package/dist/agentic/agent-runner.js.map +1 -0
- package/dist/agentic/ai-broker.d.ts +169 -0
- package/dist/agentic/ai-broker.js +8 -0
- package/dist/agentic/ai-broker.js.map +1 -0
- package/dist/agentic/atomic-checkpointer.d.ts +137 -0
- package/dist/agentic/atomic-checkpointer.js +9 -0
- package/dist/agentic/atomic-checkpointer.js.map +1 -0
- package/dist/agentic/autonomous-worker.d.ts +122 -0
- package/dist/agentic/autonomous-worker.js +10 -0
- package/dist/agentic/autonomous-worker.js.map +1 -0
- package/dist/agentic/event-bridge.d.ts +350 -0
- package/dist/agentic/event-bridge.js +9 -0
- package/dist/agentic/event-bridge.js.map +1 -0
- package/dist/agentic/executor.d.ts +91 -0
- package/dist/agentic/executor.js +12 -0
- package/dist/agentic/executor.js.map +1 -0
- package/dist/agentic/graph-projection.d.ts +119 -0
- package/dist/agentic/graph-projection.js +7 -0
- package/dist/agentic/graph-projection.js.map +1 -0
- package/dist/agentic/graph.d.ts +524 -0
- package/dist/agentic/graph.js +7 -0
- package/dist/agentic/graph.js.map +1 -0
- package/dist/agentic/index.d.ts +28 -0
- package/dist/agentic/index.js +87 -0
- package/dist/agentic/index.js.map +1 -0
- package/dist/agentic/local-runner.d.ts +106 -0
- package/dist/agentic/local-runner.js +7 -0
- package/dist/agentic/local-runner.js.map +1 -0
- package/dist/agentic/remote-executor.d.ts +67 -0
- package/dist/agentic/remote-executor.js +8 -0
- package/dist/agentic/remote-executor.js.map +1 -0
- package/dist/agentic/types.d.ts +157 -0
- package/dist/agentic/types.js +7 -0
- package/dist/agentic/types.js.map +1 -0
- package/dist/agentic/workflow-catalog.d.ts +152 -0
- package/dist/agentic/workflow-catalog.js +7 -0
- package/dist/agentic/workflow-catalog.js.map +1 -0
- package/dist/agentic/workflow-compiler.d.ts +44 -0
- package/dist/agentic/workflow-compiler.js +8 -0
- package/dist/agentic/workflow-compiler.js.map +1 -0
- package/dist/agentic/workflow-coordinator.d.ts +170 -0
- package/dist/agentic/workflow-coordinator.js +8 -0
- package/dist/agentic/workflow-coordinator.js.map +1 -0
- package/dist/agentic/workflow-manager.d.ts +91 -0
- package/dist/agentic/workflow-manager.js +7 -0
- package/dist/agentic/workflow-manager.js.map +1 -0
- package/dist/agentic/workflow-registry.d.ts +334 -0
- package/dist/agentic/workflow-registry.js +7 -0
- package/dist/agentic/workflow-registry.js.map +1 -0
- package/dist/artifacts-CteHmCMI.d.ts +614 -0
- package/dist/auth-hooks/api-key.d.ts +75 -0
- package/dist/auth-hooks/api-key.js +7 -0
- package/dist/auth-hooks/api-key.js.map +1 -0
- package/dist/auth-hooks/index.d.ts +80 -0
- package/dist/auth-hooks/index.js +28 -0
- package/dist/auth-hooks/index.js.map +1 -0
- package/dist/browser-auth/account-memberships.d.ts +213 -0
- package/dist/browser-auth/account-memberships.js +13 -0
- package/dist/browser-auth/account-memberships.js.map +1 -0
- package/dist/browser-auth/index.d.ts +8 -0
- package/dist/browser-auth/index.js +59 -0
- package/dist/browser-auth/index.js.map +1 -0
- package/dist/browser-auth/kratos-session.d.ts +37 -0
- package/dist/browser-auth/kratos-session.js +7 -0
- package/dist/browser-auth/kratos-session.js.map +1 -0
- package/dist/browser-auth/platform-session.d.ts +120 -0
- package/dist/browser-auth/platform-session.js +7 -0
- package/dist/browser-auth/platform-session.js.map +1 -0
- package/dist/browser-auth/public-memberships.d.ts +22 -0
- package/dist/browser-auth/public-memberships.js +7 -0
- package/dist/browser-auth/public-memberships.js.map +1 -0
- package/dist/cache/index.d.ts +181 -0
- package/dist/cache/index.js +197 -0
- package/dist/cache/index.js.map +1 -0
- package/dist/chunk-32746UQZ.js +131 -0
- package/dist/chunk-32746UQZ.js.map +1 -0
- package/dist/chunk-3NLSWP2Y.js +223 -0
- package/dist/chunk-3NLSWP2Y.js.map +1 -0
- package/dist/chunk-3P4XTTQH.js +346 -0
- package/dist/chunk-3P4XTTQH.js.map +1 -0
- package/dist/chunk-3VITSHN3.js +15 -0
- package/dist/chunk-3VITSHN3.js.map +1 -0
- package/dist/chunk-46UWPEW2.js +226 -0
- package/dist/chunk-46UWPEW2.js.map +1 -0
- package/dist/chunk-4BARRLJR.js +180 -0
- package/dist/chunk-4BARRLJR.js.map +1 -0
- package/dist/chunk-4VORUFKR.js +45 -0
- package/dist/chunk-4VORUFKR.js.map +1 -0
- package/dist/chunk-55D4ERWO.js +1 -0
- package/dist/chunk-55D4ERWO.js.map +1 -0
- package/dist/chunk-5TBBZIND.js +18 -0
- package/dist/chunk-5TBBZIND.js.map +1 -0
- package/dist/chunk-5WOZWPZA.js +211 -0
- package/dist/chunk-5WOZWPZA.js.map +1 -0
- package/dist/chunk-6CBVZ6CT.js +168 -0
- package/dist/chunk-6CBVZ6CT.js.map +1 -0
- package/dist/chunk-6XZXYNJR.js +74 -0
- package/dist/chunk-6XZXYNJR.js.map +1 -0
- package/dist/chunk-753HWDSC.js +222 -0
- package/dist/chunk-753HWDSC.js.map +1 -0
- package/dist/chunk-7AHSS7SO.js +81 -0
- package/dist/chunk-7AHSS7SO.js.map +1 -0
- package/dist/chunk-7FTJN4SA.js +1 -0
- package/dist/chunk-7FTJN4SA.js.map +1 -0
- package/dist/chunk-AVDMLTPF.js +24 -0
- package/dist/chunk-AVDMLTPF.js.map +1 -0
- package/dist/chunk-BKAHUEIT.js +95 -0
- package/dist/chunk-BKAHUEIT.js.map +1 -0
- package/dist/chunk-CJ7OFEF7.js +134 -0
- package/dist/chunk-CJ7OFEF7.js.map +1 -0
- package/dist/chunk-EJKWDZIU.js +111 -0
- package/dist/chunk-EJKWDZIU.js.map +1 -0
- package/dist/chunk-F2J6IQ6I.js +247 -0
- package/dist/chunk-F2J6IQ6I.js.map +1 -0
- package/dist/chunk-F3O7CELI.js +23 -0
- package/dist/chunk-F3O7CELI.js.map +1 -0
- package/dist/chunk-F4IITPGX.js +221 -0
- package/dist/chunk-F4IITPGX.js.map +1 -0
- package/dist/chunk-FD6VC2NA.js +66 -0
- package/dist/chunk-FD6VC2NA.js.map +1 -0
- package/dist/chunk-FRRRWAHO.js +14 -0
- package/dist/chunk-FRRRWAHO.js.map +1 -0
- package/dist/chunk-HCKAGLLB.js +17 -0
- package/dist/chunk-HCKAGLLB.js.map +1 -0
- package/dist/chunk-HVC7FG6B.js +191 -0
- package/dist/chunk-HVC7FG6B.js.map +1 -0
- package/dist/chunk-HXFVOR7Z.js +496 -0
- package/dist/chunk-HXFVOR7Z.js.map +1 -0
- package/dist/chunk-IJWYS2PF.js +122 -0
- package/dist/chunk-IJWYS2PF.js.map +1 -0
- package/dist/chunk-INCHXAFK.js +1395 -0
- package/dist/chunk-INCHXAFK.js.map +1 -0
- package/dist/chunk-JT6BRGQM.js +1 -0
- package/dist/chunk-JT6BRGQM.js.map +1 -0
- package/dist/chunk-L6PMAEMB.js +115 -0
- package/dist/chunk-L6PMAEMB.js.map +1 -0
- package/dist/chunk-LOUGW6MU.js +126 -0
- package/dist/chunk-LOUGW6MU.js.map +1 -0
- package/dist/chunk-LYPZPE53.js +129 -0
- package/dist/chunk-LYPZPE53.js.map +1 -0
- package/dist/chunk-NNCCN7JP.js +186 -0
- package/dist/chunk-NNCCN7JP.js.map +1 -0
- package/dist/chunk-PBC3MZUL.js +212 -0
- package/dist/chunk-PBC3MZUL.js.map +1 -0
- package/dist/chunk-R4ADP2DC.js +20 -0
- package/dist/chunk-R4ADP2DC.js.map +1 -0
- package/dist/chunk-RHN4Y6VS.js +44 -0
- package/dist/chunk-RHN4Y6VS.js.map +1 -0
- package/dist/chunk-SDJNYPYK.js +770 -0
- package/dist/chunk-SDJNYPYK.js.map +1 -0
- package/dist/chunk-UGNTCOVR.js +28 -0
- package/dist/chunk-UGNTCOVR.js.map +1 -0
- package/dist/chunk-VC2PCK2S.js +31 -0
- package/dist/chunk-VC2PCK2S.js.map +1 -0
- package/dist/chunk-VF5YDZJC.js +305 -0
- package/dist/chunk-VF5YDZJC.js.map +1 -0
- package/dist/chunk-VISRDVTK.js +675 -0
- package/dist/chunk-VISRDVTK.js.map +1 -0
- package/dist/chunk-W6O3LVBY.js +102 -0
- package/dist/chunk-W6O3LVBY.js.map +1 -0
- package/dist/chunk-WFEAKJLR.js +47 -0
- package/dist/chunk-WFEAKJLR.js.map +1 -0
- package/dist/chunk-XIEY2OF4.js +67 -0
- package/dist/chunk-XIEY2OF4.js.map +1 -0
- package/dist/chunk-XITLHDG3.js +37 -0
- package/dist/chunk-XITLHDG3.js.map +1 -0
- package/dist/chunk-XMWPYZWZ.js +61 -0
- package/dist/chunk-XMWPYZWZ.js.map +1 -0
- package/dist/chunk-XUP6CNOM.js +34 -0
- package/dist/chunk-XUP6CNOM.js.map +1 -0
- package/dist/chunk-YABTQZDJ.js +25 -0
- package/dist/chunk-YABTQZDJ.js.map +1 -0
- package/dist/chunk-YMHVRBUU.js +199 -0
- package/dist/chunk-YMHVRBUU.js.map +1 -0
- package/dist/chunk-YMJ7BRKU.js +510 -0
- package/dist/chunk-YMJ7BRKU.js.map +1 -0
- package/dist/chunk-ZC3XWU7B.js +28 -0
- package/dist/chunk-ZC3XWU7B.js.map +1 -0
- package/dist/chunk-ZHMTD5KV.js +90 -0
- package/dist/chunk-ZHMTD5KV.js.map +1 -0
- package/dist/chunk-ZWZDLOE7.js +160 -0
- package/dist/chunk-ZWZDLOE7.js.map +1 -0
- package/dist/db-package/db/local-first-sqlite-adapter.d.ts +432 -0
- package/dist/db-package/db/local-first-sqlite-adapter.js +7 -0
- package/dist/db-package/db/local-first-sqlite-adapter.js.map +1 -0
- package/dist/db-package/index.d.ts +7 -0
- package/dist/db-package/index.js +16 -0
- package/dist/db-package/index.js.map +1 -0
- package/dist/db-package/migration/aggregator.d.ts +86 -0
- package/dist/db-package/migration/aggregator.js +7 -0
- package/dist/db-package/migration/aggregator.js.map +1 -0
- package/dist/db-package/migration/index.d.ts +3 -0
- package/dist/db-package/migration/index.js +8 -0
- package/dist/db-package/migration/index.js.map +1 -0
- package/dist/engine.d.ts +205 -0
- package/dist/engine.js +20 -0
- package/dist/engine.js.map +1 -0
- package/dist/entitlements/index.d.ts +313 -0
- package/dist/entitlements/index.js +23 -0
- package/dist/entitlements/index.js.map +1 -0
- package/dist/execution/chat.d.ts +7 -0
- package/dist/execution/chat.js +7 -0
- package/dist/execution/chat.js.map +1 -0
- package/dist/execution/index.d.ts +342 -0
- package/dist/execution/index.js +66 -0
- package/dist/execution/index.js.map +1 -0
- package/dist/execution/tool-agent.d.ts +7 -0
- package/dist/execution/tool-agent.js +8 -0
- package/dist/execution/tool-agent.js.map +1 -0
- package/dist/extensions/index.d.ts +172 -0
- package/dist/extensions/index.js +95 -0
- package/dist/extensions/index.js.map +1 -0
- package/dist/health/index.d.ts +35 -0
- package/dist/health/index.js +7 -0
- package/dist/health/index.js.map +1 -0
- package/dist/index.d.ts +43 -0
- package/dist/index.js +161 -0
- package/dist/index.js.map +1 -0
- package/dist/lifecycle/index.d.ts +133 -0
- package/dist/lifecycle/index.js +13 -0
- package/dist/lifecycle/index.js.map +1 -0
- package/dist/lifecycle-engine/backend-migration.d.ts +2 -0
- package/dist/lifecycle-engine/backend-migration.js +11 -0
- package/dist/lifecycle-engine/backend-migration.js.map +1 -0
- package/dist/lifecycle-engine/baseline.d.ts +2 -0
- package/dist/lifecycle-engine/baseline.js +9 -0
- package/dist/lifecycle-engine/baseline.js.map +1 -0
- package/dist/lifecycle-engine/index.d.ts +1497 -0
- package/dist/lifecycle-engine/index.js +41 -0
- package/dist/lifecycle-engine/index.js.map +1 -0
- package/dist/lifecycle-engine/platform/artifacts.d.ts +4 -0
- package/dist/lifecycle-engine/platform/artifacts.js +7 -0
- package/dist/lifecycle-engine/platform/artifacts.js.map +1 -0
- package/dist/lifecycle-engine/platform/control-plane.d.ts +12 -0
- package/dist/lifecycle-engine/platform/control-plane.js +2 -0
- package/dist/lifecycle-engine/platform/control-plane.js.map +1 -0
- package/dist/lifecycle-engine/platform/database-router.d.ts +118 -0
- package/dist/lifecycle-engine/platform/database-router.js +7 -0
- package/dist/lifecycle-engine/platform/database-router.js.map +1 -0
- package/dist/lifecycle-engine/platform/deployment-placements.d.ts +464 -0
- package/dist/lifecycle-engine/platform/deployment-placements.js +16 -0
- package/dist/lifecycle-engine/platform/deployment-placements.js.map +1 -0
- package/dist/lifecycle-engine/platform/deployment.d.ts +4 -0
- package/dist/lifecycle-engine/platform/deployment.js +17 -0
- package/dist/lifecycle-engine/platform/deployment.js.map +1 -0
- package/dist/lifecycle-engine/platform/index.d.ts +737 -0
- package/dist/lifecycle-engine/platform/index.js +60 -0
- package/dist/lifecycle-engine/platform/index.js.map +1 -0
- package/dist/lifecycle-engine/platform/runtime.d.ts +80 -0
- package/dist/lifecycle-engine/platform/runtime.js +11 -0
- package/dist/lifecycle-engine/platform/runtime.js.map +1 -0
- package/dist/lifecycle-engine/platform/site-publication.d.ts +102 -0
- package/dist/lifecycle-engine/platform/site-publication.js +7 -0
- package/dist/lifecycle-engine/platform/site-publication.js.map +1 -0
- package/dist/lifecycle-engine/platform/user-directory.d.ts +139 -0
- package/dist/lifecycle-engine/platform/user-directory.js +13 -0
- package/dist/lifecycle-engine/platform/user-directory.js.map +1 -0
- package/dist/mcp.d.ts +92 -0
- package/dist/mcp.js +10 -0
- package/dist/mcp.js.map +1 -0
- package/dist/middleware/auth.d.ts +118 -0
- package/dist/middleware/auth.js +7 -0
- package/dist/middleware/auth.js.map +1 -0
- package/dist/middleware/error-handler.d.ts +35 -0
- package/dist/middleware/error-handler.js +7 -0
- package/dist/middleware/error-handler.js.map +1 -0
- package/dist/middleware/module-guard.d.ts +33 -0
- package/dist/middleware/module-guard.js +7 -0
- package/dist/middleware/module-guard.js.map +1 -0
- package/dist/platform-admin/index.d.ts +37 -0
- package/dist/platform-admin/index.js +11 -0
- package/dist/platform-admin/index.js.map +1 -0
- package/dist/platform-admin/store.d.ts +346 -0
- package/dist/platform-admin/store.js +7 -0
- package/dist/platform-admin/store.js.map +1 -0
- package/dist/plugin-data/annotations.d.ts +6 -0
- package/dist/plugin-data/annotations.js +12 -0
- package/dist/plugin-data/annotations.js.map +1 -0
- package/dist/plugin-data/atomic-context.d.ts +41 -0
- package/dist/plugin-data/atomic-context.js +9 -0
- package/dist/plugin-data/atomic-context.js.map +1 -0
- package/dist/plugin-data/atomic.d.ts +6 -0
- package/dist/plugin-data/atomic.js +26 -0
- package/dist/plugin-data/atomic.js.map +1 -0
- package/dist/plugin-data/audit.d.ts +6 -0
- package/dist/plugin-data/audit.js +12 -0
- package/dist/plugin-data/audit.js.map +1 -0
- package/dist/plugin-data/commands.d.ts +6 -0
- package/dist/plugin-data/commands.js +8 -0
- package/dist/plugin-data/commands.js.map +1 -0
- package/dist/plugin-data/composite.d.ts +6 -0
- package/dist/plugin-data/composite.js +8 -0
- package/dist/plugin-data/composite.js.map +1 -0
- package/dist/plugin-data/delivery.d.ts +6 -0
- package/dist/plugin-data/delivery.js +16 -0
- package/dist/plugin-data/delivery.js.map +1 -0
- package/dist/plugin-data/index.d.ts +2798 -0
- package/dist/plugin-data/index.js +102 -0
- package/dist/plugin-data/index.js.map +1 -0
- package/dist/plugin-data/json-documents.d.ts +6 -0
- package/dist/plugin-data/json-documents.js +16 -0
- package/dist/plugin-data/json-documents.js.map +1 -0
- package/dist/plugin-data/outbox.d.ts +6 -0
- package/dist/plugin-data/outbox.js +16 -0
- package/dist/plugin-data/outbox.js.map +1 -0
- package/dist/plugin-data/scoped-records.d.ts +6 -0
- package/dist/plugin-data/scoped-records.js +10 -0
- package/dist/plugin-data/scoped-records.js.map +1 -0
- package/dist/plugin-sdk.d.ts +41 -0
- package/dist/plugin-sdk.js +10 -0
- package/dist/plugin-sdk.js.map +1 -0
- package/dist/sql-lifecycle/index.d.ts +138 -0
- package/dist/sql-lifecycle/index.js +167 -0
- package/dist/sql-lifecycle/index.js.map +1 -0
- package/dist/storage/index.d.ts +2 -0
- package/dist/storage/index.js +13 -0
- package/dist/storage/index.js.map +1 -0
- package/dist/storage/s3-compatible.d.ts +139 -0
- package/dist/storage/s3-compatible.js +11 -0
- package/dist/storage/s3-compatible.js.map +1 -0
- package/dist/tenant.d.ts +108 -0
- package/dist/tenant.js +9 -0
- package/dist/tenant.js.map +1 -0
- package/dist/workspace-context.d.ts +119 -0
- package/dist/workspace-context.js +9 -0
- package/dist/workspace-context.js.map +1 -0
- package/docs/api.md +30560 -0
- package/docs/db/README.md +49 -0
- package/docs/db/docs/api.md +1613 -0
- package/docs/db/docs/guide.md +47 -0
- package/docs/entitlements.md +60 -0
- package/docs/guide.md +92 -0
- package/docs/index.md +57 -0
- package/docs/ja/db/README.md +46 -0
- package/docs/ja/db/docs/guide.md +53 -0
- package/docs/ja/guide.md +46 -0
- package/docs/ja/lifecycle/README.md +46 -0
- package/docs/ja/lifecycle/docs/guide.md +45 -0
- package/docs/ja/storage/README.md +46 -0
- package/docs/ja/storage/docs/guide.md +43 -0
- package/docs/lifecycle/README.md +49 -0
- package/docs/lifecycle/docs/api.md +3770 -0
- package/docs/lifecycle/docs/baseline.md +50 -0
- package/docs/lifecycle/docs/guide.md +47 -0
- package/docs/storage/README.md +49 -0
- package/docs/storage/docs/api.md +470 -0
- package/docs/storage/docs/guide.md +47 -0
- package/package.json +354 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/plugin-data/json-documents.ts","../src/plugin-data/index.ts","../src/plugin-data/commands.ts","../src/plugin-data/audit.ts","../src/plugin-data/atomic.ts","../src/plugin-data/outbox.ts","../src/plugin-data/scoped-records.ts","../src/plugin-data/composite.ts","../src/plugin-data/annotations.ts","../src/plugin-data/delivery.ts"],"sourcesContent":["import { inheritAtomicSqlSession } from './atomic-context'\nimport { assertBusinessId } from '@alneas/eaos-core/plugin-sdk'\nimport { assertDataContractBinding, createJsonDocumentAssertion, type DataContractCatalog, type DataContractBinding, type JsonDocumentContract } from '@alneas/eaos-server/lifecycle-engine'\nimport { assertPrincipal, PluginError, type PluginPrincipal, type PluginRecord, type PluginRecordStore } from './index'\nimport type { AtomicRepository, AtomicSession } from './atomic'\n\n/**\n * Apply canonical document validation to every existing host persistence path while retaining other host methods.\n * @param host - Host with optional record store, repository and/or transaction callback.\n * @param documents - Trusted canonical JSON document definitions.\n * @typeParam T - Stored JSON payload shape.\n * @typeParam H - Concrete host shape whose existing methods and persistence capabilities are retained.\n * @returns A proxy with wrapped persistence capabilities and other functions bound to the original host.\n * @throws Invalid document contracts throw during wrapper creation; subsequent validation and underlying host failures propagate.\n * @remarks Does not replace transaction ownership or live authorization. Inputs are copied for validation; unrelated host methods keep their original receiver.\n * @example\n * import { createValidatedRecordHost } from '@alneas/eaos-server/plugin-data'\n * export function validated<T>(host: Parameters<typeof createValidatedRecordHost<T, { store?: import('@alneas/eaos-server/plugin-data').PluginRecordStore<T> }>>[0], documents: Parameters<typeof createValidatedRecordHost>[1]) { return createValidatedRecordHost(host, documents) }\n */\nexport function createValidatedRecordHost<T, H extends {\n \n /**\n * Optional existing tenant/CAS store wrapped with canonical payload checks.\n */\n store?: PluginRecordStore<T>\n \n /**\n * Optional existing atomic repository wrapped without adding a second transaction.\n */\n repository?: AtomicRepository\n \n /**\n * Optional real aggregate transaction; its callback receives a validated connection-bound store.\n \n * @param principal - Verified current principal.\n * @param work - Async service work on the validated connection-bound store.\n * @typeParam R - Callback result resolved by the host transaction.\n * @returns The callback result after host commit; underlying transaction/rejection semantics are preserved.\n * @throws Callback failures propagate to the owning operation; transactional writes roll back when the host boundary rejects.\n */\n transaction?: <R>(principal: PluginPrincipal, work: (store: PluginRecordStore<T>) => Promise<R>) => Promise<R>\n}>(host: H, documents: readonly JsonDocumentContract[]): H {\n const copy = { ...host }\n if (host.store) copy.store = createValidatedRecordStore(host.store, documents)\n if (host.repository) copy.repository = createValidatedAtomicRepository(host.repository, documents)\n if (host.transaction) {\n const transaction = host.transaction.bind(host)\n copy.transaction = (principal, work) => transaction(principal, store => work(createValidatedRecordStore(store, documents)))\n }\n return new Proxy(copy, { get(target, key, receiver) {\n if (key === 'store' || key === 'repository' || key === 'transaction') return Reflect.get(target, key, receiver)\n const value = Reflect.get(host, key, host)\n return typeof value === 'function' ? value.bind(host) : value\n } })\n}\n\n/**\n * Resolve canonical payload document contracts for one verified Data Contract table/namespace binding.\n * @param catalog - Trusted resolved Data Contract catalog.\n * @param binding - Contract identity, table, namespace and optional declared document IDs.\n * @returns All matching payload document contracts for the bound table/namespace, possibly empty.\n * @throws Rejects missing/mismatched bindings, a table without id/revision/payload envelope fields or unavailable/duplicate requested document IDs.\n * @remarks Validates requested document selection but returns every matching namespace document, not only the requested-ID subset.\n * @example\n * import { recordDocuments } from '@alneas/eaos-server/plugin-data'\n * export function documents(catalog: Parameters<typeof recordDocuments>[0], binding: Parameters<typeof recordDocuments>[1]) { return recordDocuments(catalog, binding) }\n */\nexport function recordDocuments(catalog: DataContractCatalog, binding: DataContractBinding & {\n /**\n * Optional explicit nonempty unique document IDs to verify against the bound namespace; all matching namespace documents are returned.\n */\n jsonDocuments?: readonly string[]}): JsonDocumentContract[] {\n assertDataContractBinding(catalog, binding)\n const columns = catalog.tables.find(t => t.name === binding.table)!.schema.properties as Record<string, unknown>\n if (!columns.id || !columns.revision || !columns.payload) throw Error('Record stores require an envelope table with id, revision and payload')\n const documents = catalog.contracts.find(c => c.id === binding.contractId)!.jsonDocuments?.filter(d => d.table === binding.table && d.column === 'payload' && d.namespace === binding.namespace) ?? []\n if (binding.jsonDocuments !== undefined && (!binding.jsonDocuments.length || new Set(binding.jsonDocuments).size !== binding.jsonDocuments.length || binding.jsonDocuments.some(id => !documents.some(d => d.id === id)))) throw Error('Declared JSON document contract is unavailable for this storage binding')\n return documents\n}\n\n/**\n * Compile closed payload schemas and route records by longest canonical prefix without coercion or remote loading.\n * @param documents - Nonempty trusted document list; each binds column payload to a closed object schema.\n * @returns A synchronous (tenantId, record) assertion that accepts only matching identity, revision, immutability and schema.\n * @throws Rejects absent/open/ambiguous contracts at construction; assertions reject invalid IDs/revisions, unmatched routes, immutable replacements, schema or embedded-tenant mismatch.\n * @remarks Does not write records or prove live authorization; document definitions are cloned before compilation.\n * @example\n * import { createRecordDocumentValidator } from '@alneas/eaos-server/plugin-data'\n * export function validator(documents: Parameters<typeof createRecordDocumentValidator>[0]) { return createRecordDocumentValidator(documents) }\n */\nexport function createRecordDocumentValidator(documents: readonly JsonDocumentContract[]) {\n if (!documents.length) throw Error('Record document contracts are required')\n const routes = documents.map(document => {\n const copy = structuredClone(document)\n if (copy.column !== 'payload' || copy.schema.type !== 'object' || copy.schema.additionalProperties !== false) throw Error('Closed payload document contract required')\n return { document: copy, validate: createJsonDocumentAssertion(copy) }\n }).sort((a, b) => (b.document.recordPrefix ?? '').length - (a.document.recordPrefix ?? '').length)\n const prefixes = new Set<string>()\n for (const route of routes) { const prefix = route.document.recordPrefix ?? ''; if (prefixes.has(prefix)) throw Error('Ambiguous record document route'); prefixes.add(prefix) }\n return (tenantId: string, record: PluginRecord<unknown>): void => {\n assertBusinessId(tenantId); assertBusinessId(record.id)\n if (!Number.isSafeInteger(record.revision) || record.revision < 1) throw new PluginError(409, 'Invalid record revision')\n const route = routes.find(r => record.id.startsWith(r.document.recordPrefix ?? ''))\n if (!route) throw new PluginError(409, 'Record document contract unavailable')\n if (route.document.immutable && record.revision !== 1) throw new PluginError(409, 'Immutable document cannot be replaced')\n try { route.validate(record.value) } catch { throw new PluginError(409, `Record differs from JSON contract ${route.document.id}@${route.document.version}`) }\n const value = record.value as Record<string, unknown>\n if (Object.hasOwn(value, 'tenantId') && value.tenantId !== tenantId) throw new PluginError(409, 'JSON document tenant differs')\n }\n}\n\n/**\n * Validate canonical documents on host-store reads and writes while retaining its transaction semantics.\n * @param store - Existing host record store with real tenant/CAS behavior.\n * @param documents - Trusted canonical payload contracts to clone and enforce.\n * @typeParam T - JSON payload shape retained by the wrapped store.\n * @returns A wrapped store retaining optional listPage/delete capabilities when supplied.\n * @throws Invalid contracts throw at creation; operations reject mismatched IDs, invalid revision transitions/payloads and immutable deletion, with underlying errors propagated.\n * @remarks Does not add a transaction or independent authorization. Host returned list rows must still be correctly tenant-scoped.\n * @example\n * import { createValidatedRecordStore } from '@alneas/eaos-server/plugin-data'\n * export function store<T>(store: Parameters<typeof createValidatedRecordStore<T>>[0], documents: Parameters<typeof createValidatedRecordStore>[1]) { return createValidatedRecordStore(store, documents) }\n */\nexport function createValidatedRecordStore<T>(store: PluginRecordStore<T>, documents: readonly JsonDocumentContract[]): PluginRecordStore<T> {\n const ownedDocuments = structuredClone(documents)\n const validate = createRecordDocumentValidator(ownedDocuments)\n const check = (tenant: string, row: PluginRecord<T>) => { validate(tenant, row); return row }\n return {\n async read(tenant, id) { const row = await store.read(tenant, id); if (row && row.id !== id) throw new PluginError(409, 'Record identity differs'); return row && check(tenant, row) },\n async list(tenant, limit) { return (await store.list(tenant, limit)).map(row => check(tenant, row)) },\n ...(store.listPage ? { async listPage(tenant: string, limit: number, after?: string) { return (await store.listPage!(tenant, limit, after)).map(row => check(tenant, row)) } } : {}),\n async create(tenant, row) { if (row.revision !== 1) throw new PluginError(409, 'New record revision must be 1'); validate(tenant, row); await store.create(tenant, row) },\n async replace(tenant, row, expected) { if (!Number.isSafeInteger(expected) || expected < 1 || row.revision !== expected + 1) throw new PluginError(409, 'Invalid revision transition'); validate(tenant, row); return store.replace(tenant, row, expected) },\n ...(store.delete ? { delete: async (tenant: string, id: string, expected?: number) => { const immutable = [...ownedDocuments].sort((a,b) => (b.recordPrefix ?? '').length - (a.recordPrefix ?? '').length).find(d => id.startsWith(d.recordPrefix ?? ''))?.immutable; if (immutable) throw new PluginError(409, 'Immutable document cannot be deleted'); return store.delete!(tenant, id, expected) } } : {}),\n }\n}\n\n/**\n * Validate canonical document payloads inside the host repository's existing commit boundary.\n * @param repository - Real tenant-scoped atomic repository.\n * @param documents - Trusted canonical payload contracts copied for validation.\n * @returns A repository with validating, expiring sessions and retained joined-SQL capability bindings.\n * @throws Invalid contracts throw; work rejects wrong IDs/revisions/scopes, invalid batch order/length, expired sessions or payload/underlying repository failures.\n * @remarks Does not open a second transaction or authorize operations. Wrapper capabilities expire after the work callback and are removed in finally.\n * @example\n * import { createValidatedAtomicRepository } from '@alneas/eaos-server/plugin-data'\n * export function repository(repository: Parameters<typeof createValidatedAtomicRepository>[0], documents: Parameters<typeof createValidatedAtomicRepository>[1]) { return createValidatedAtomicRepository(repository, documents) }\n */\nexport function createValidatedAtomicRepository(repository: AtomicRepository, documents: readonly JsonDocumentContract[]): AtomicRepository {\n const validate = createRecordDocumentValidator(structuredClone(documents))\n return { async run(principal, work) {\n assertPrincipal(principal)\n const p = structuredClone(principal)\n return repository.run(p, async source => {\n let active=true\n const check=()=>{if(!active)throw Error('Transaction session expired')}\n const read=<T>(row: PluginRecord<T> | null, id?:string) => {\n check()\n if(row){if(id!==undefined && row.id!==id)throw Error('Record identity differs');validate(p.tenantId,row)}\n return row\n }\n const preflight=<T>(id:string,value:T,expected:number) => {\n check()\n if(!Number.isSafeInteger(expected)||expected<0||expected>=Number.MAX_SAFE_INTEGER)throw Error('Invalid expected revision')\n const row={id,value:structuredClone(value),revision:expected+1}\n validate(p.tenantId,row)\n return row\n }\n const session:AtomicSession={\n async get<T>(id:string){check();return read(await source.get<T>(id),id)},\n async list<T>(prefix:string,after?:string,limit?:number){check();const rows=await source.list<T>(prefix,after,limit);return rows.map(row=>{if(!row.id.startsWith(prefix))throw Error('Record list scope differs');return read(row)!})},\n async put<T>(id:string,value:T,expected:number){const row=preflight(id,value,expected);const saved=read(await source.put(id,row.value,expected),id)!;if(saved.revision!==row.revision)throw Error('Saved revision differs');return saved},\n ...(source.getMany?{async getMany<T>(ids:string[]){check();const rows=await source.getMany!<T>(ids);if(rows.length!==ids.length)throw Error('Batch read length differs');return rows.map((row,i)=>read(row,ids[i]))}}:{}),\n ...(source.putMany?{async putMany<T>(changes:{id:string;value:T;expected:number}[]){\n check();if(new Set(changes.map(c=>c.id)).size!==changes.length)throw Error('Duplicate batch record key')\n const rows=changes.map(c=>preflight(c.id,c.value,c.expected))\n const saved=await source.putMany!(changes.map((c,i)=>({...c,value:rows[i].value})))\n if(saved.length!==rows.length)throw Error('Batch write length differs')\n return saved.map((row,i)=>{const result=read(row,rows[i].id)!;if(result.revision!==rows[i].revision)throw Error('Saved revision differs');return result})\n }}:{}),\n }\n const release=inheritAtomicSqlSession(source,session)\n try{return await work(session)}finally{active=false;release()}\n })\n } }\n}\n","import { Hono, type Context } from 'hono'\nimport { bodyLimit } from 'hono/body-limit'\nimport type { DataContractCatalog, JsonDocumentContract } from '@alneas/eaos-server/lifecycle-engine'\nimport { createRecordDocumentValidator, recordDocuments } from './json-documents'\nimport { assertPayloadWithinPolicy, resolvePluginStoragePolicy, type McpToolDefinition, type PluginManifest, type PluginStoragePolicy } from '@alneas/eaos-core/plugin-sdk'\nexport { RecordCommandService, type CommandHost, type CommandState, type CommandContext, type CommandResponse } from './commands'\nexport * from './atomic'\nexport * from './audit'\nexport * from './outbox'\nexport * from './scoped-records'\nexport * from './composite'\nexport * from './json-documents'\n/**\n * Bind a service under the trusted context symbol for copied static MCP tool definitions.\n * @param service - Host-created service instance used by each copied tool handler.\n * @param tools - Static tool definitions whose handlers consume the service context symbol.\n * @param key - Trusted symbol agreed by the binder and operation handler.\n * @typeParam TService - Concrete host-created service type retained in the symbol binding.\n * @returns New tool objects with wrappers that preserve other context fields and override the service symbol.\n * @remarks Does not resolve identity or grant permission. Tool execution still requires verified principal context and live host admission.\n * @example\n * import { createMcpToolBinder } from '@alneas/eaos-server/plugin-data'\n * export function bindTools<T>(service: T, tools: Parameters<typeof createMcpToolBinder>[1], key: symbol) { return createMcpToolBinder(service, tools, key) }\n */\nexport function createMcpToolBinder<TService>(service: TService, tools: readonly import('@alneas/eaos-core/plugin-sdk').McpToolDefinition[], key: symbol): import('@alneas/eaos-core/plugin-sdk').McpToolDefinition[] {\n return tools.map(tool => ({ ...tool, handler: (args, context) => tool.handler(args, { ...context, [key]: service }) }))\n}\n/**\n * Create a static operation handler that dispatches through a host-bound service instance.\n * @param operation - Trusted operation name selected by the manifest author.\n * @param key - Service-binding symbol used by createMcpToolBinder.\n * @typeParam TService - Host service exposing the principal-aware execute contract.\n * @returns An async handler accepting tool arguments and trusted principal/service context.\n * @throws The returned handler rejects when the service is absent or has no execute method; service failures propagate.\n * @remarks The incoming context must already contain a verified PluginPrincipal. This helper neither authenticates a request nor verifies live resource access.\n * @example\n * import { createMcpOperationHandler } from '@alneas/eaos-server/plugin-data'\n * const key = Symbol('service')\n * const handler = createMcpOperationHandler('list', key)\n */\nexport function createMcpOperationHandler<TService extends { \n /**\n * Service operation dispatch contract; callers must supply host-verified principal context and perform live admission.\n * @param principal - Verified current tenant/user principal.\n * @param operation - Declared operation name.\n * @param input - Operation input to validate and authorize at the owning service boundary.\n * @returns The service operation result; authorization and validation stay owner-controlled.\n * @throws Rejects underlying service, authorization or persistence failures.\n */\n execute(principal: PluginPrincipal, operation: string, input: unknown): Promise<unknown> }>(operation: string, key: symbol) {\n return async (args: unknown, context?: Record<PropertyKey, unknown>) => { const service = context?.[key] as TService | undefined; if (!service || typeof service.execute !== 'function') throw new Error('Use createPlugin with verified principal'); return service.execute((context ?? {}) as unknown as PluginPrincipal, operation, args) }\n}\n/**\n * Structurally verified tenant/user identity supplied by a trusted host authentication boundary.\n * \n * @see createPluginRouter for canonical host integration.\n */\nexport interface PluginPrincipal {\n /**\n * Tenant identity bound by the trusted principal; never selected as an authorization grant from request data.\n */\n tenantId: string;\n /**\n * Authenticated actor identity supplied by the host.\n */\n userId: string;\n /**\n * Current host-verified role names; structural validation alone does not grant permission.\n */\n roles: readonly string[] }\n/**\n * Logical record identity, CAS revision and JSON payload envelope.\n * @typeParam T - Stored JSON payload shape; compile-time typing does not itself validate data.\n * \n * @see createSqlRecordStore for canonical host integration.\n */\nexport interface PluginRecord<T> {\n /**\n * Logical tenant/namespace-scoped record identity.\n */\n id: string;\n /**\n * CAS revision for the stored envelope; persisted records start at 1 unless a documented host projection uses 0.\n */\n revision: number;\n /**\n * Stored JSON payload whose runtime validation depends on the configured document contracts.\n */\n value: T }\n/**\n * Host record persistence contract requiring tenant predicates and atomic revision-predicated writes.\n * \n * Providers must enforce tenant keys and atomic compare-and-swap, never read/update without the revision predicate.\n * @typeParam T - Stored payload shape shared by all scoped persistence operations.\n * \n * @see createSqlRecordStore for canonical host integration.\n */\nexport interface PluginRecordStore<T> {\n /**\n * Reads one record within the exact tenant and logical namespace.\n * @param tenantId - Verified tenant ID supplied by the host.\n * @param id - Logical record ID within this store.\n * @returns The matching envelope or null when absent.\n * @throws Rejects propagated host persistence, validation or callback failures.\n \n * @example\n * ```typescript\n * import type { PluginRecordStore, PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export async function readTitle(store: PluginRecordStore<{ title: string }>, principal: PluginPrincipal, id: string) {\n * const record = await store.read(principal.tenantId, id);\n * return record?.value.title ?? null;\n * }\n * ```\n */\n read(tenantId: string, id: string): Promise<PluginRecord<T> | null>\n /**\n * Reads a bounded set of envelopes from one tenant and namespace.\n * @param tenantId - Verified tenant ID.\n * @param limit - Required provider-supported maximum row count; canonical SQL stores accept integers 1–100.\n * @returns Scoped envelopes, possibly empty; filtering this bounded set does not prove completeness.\n * @throws Rejects propagated host persistence, validation or callback failures.\n \n * @example\n * ```typescript\n * import type { PluginRecordStore, PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export async function firstPage(store: PluginRecordStore<{ title: string }>, principal: PluginPrincipal) {\n * return store.list(principal.tenantId, 20);\n * }\n * ```\n */\n list(tenantId: string, limit: number): Promise<PluginRecord<T>[]>\n /**\n * Reads a stable ID-ordered page after an optional exclusive logical record ID.\n * \n * Optional stable ID keyset paging; after is an exclusive logical record ID.\n * @param tenantId - Verified tenant ID.\n * @param limit - Required bounded page size; canonical SQL stores accept 1–100.\n * @param after - Optional exclusive logical record ID; omitted starts the page.\n * @returns Scoped envelopes in increasing logical-ID order; fewer than limit indicates the end.\n * @throws Rejects propagated host persistence, validation or callback failures.\n \n * @example\n * ```typescript\n * import type { PluginRecordStore, PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export async function nextPage(store: PluginRecordStore<{ title: string }>, principal: PluginPrincipal, after: string) {\n * if (!store.listPage) throw new Error(\"Keyset paging not supported\");\n * return store.listPage(principal.tenantId, 20, after);\n * }\n * ```\n */\n listPage?(tenantId: string, limit: number, after?: string): Promise<PluginRecord<T>[]>\n /**\n * Creates a previously absent tenant record with its initial stored revision.\n * @param tenantId - Verified tenant ID owning the new record.\n * @param record - New logical envelope; canonical validated/atomic stores require revision 1.\n * @returns Resolves without a value after durable creation.\n * @throws Rejects duplicate identity, invalid document/payload/revision or persistence failure.\n \n * @example\n * ```typescript\n * import type { PluginRecordStore, PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export async function createTitle(store: PluginRecordStore<{ title: string }>, principal: PluginPrincipal, id: string, title: string) {\n * // Live create permission must be checked before persistence.\n * await store.create(principal.tenantId, { id, revision: 1, value: { title } });\n * }\n * ```\n */\n create(tenantId: string, record: PluginRecord<T>): Promise<void>\n /**\n * Replaces a tenant record only when its stored revision matches the expected value.\n * @param tenantId - Verified tenant ID.\n * @param record - Next envelope whose revision must be expectedRevision+1.\n * @param expectedRevision - Positive previously observed CAS revision.\n * @returns True when one row is replaced; false for stale rows in plain SQL stores. Atomic adapters reject CAS conflicts instead of returning false.\n * @throws Rejects invalid revision/document/payload or provider failure; atomic adapters also reject stale CAS.\n \n * @example\n * ```typescript\n * import type { PluginRecordStore, PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export async function replaceTitle(store: PluginRecordStore<{ title: string }>, principal: PluginPrincipal, id: string, expectedRevision: number, title: string) {\n * return store.replace(principal.tenantId, { id, revision: expectedRevision + 1, value: { title } }, expectedRevision);\n * }\n * ```\n */\n replace(tenantId: string, record: PluginRecord<T>, expectedRevision: number): Promise<boolean>\n /**\n * Optionally deletes one scoped envelope with an optional revision predicate.\n * @param tenantId - Verified tenant ID.\n * @param id - Logical record ID.\n * @param expectedRevision - Optional expected CAS revision; omit only when unconditional scoped deletion is intended.\n * @returns Whether a row was deleted; immutable document wrappers reject instead.\n * @throws Rejects immutable document deletion or host persistence failure.\n \n * @example\n * ```typescript\n * import type { PluginRecordStore, PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export async function deleteReviewed(store: PluginRecordStore<{ title: string }>, principal: PluginPrincipal, id: string, expectedRevision: number) {\n * if (!store.delete) throw new Error(\"Deletion not supported\");\n * return store.delete(principal.tenantId, id, expectedRevision);\n * }\n * ```\n */\n delete?(tenantId: string, id: string, expectedRevision?: number): Promise<boolean>\n}\n/**\n * Carries an intentional sanitized plugin HTTP error status while preserving the caller-provided message.\n * \n * @remarks\n * createPluginRouter returns this message/status to HTTP callers; exclude secrets, provider details and business payloads from messages.\n * \n * @example\n * ```typescript\n * import { PluginError } from '@alneas/eaos-server/plugin-data';\n * const unavailable = new PluginError(404, 'Record unavailable');\n * ```\n */\nexport class PluginError extends Error {\n /**\n * Creates an intentional plugin failure with one supported client-facing HTTP status.\n * @param status - Supported bad-input/authentication/permission/missing/conflict/gone HTTP status.\n * @param message - Safe public error description exposed by createPluginRouter.\n * \n * @example\n * ```typescript\n * import { PluginError } from '@alneas/eaos-server/plugin-data';\n * const denied = new PluginError(403, 'Record access denied');\n * ```\n */\n constructor(readonly status: 400 | 401 | 403 | 404 | 409 | 410, message: string) { super(message) }\n}\nfunction storagePayload(policy: PluginStoragePolicy, value: unknown): string {\n try { return assertPayloadWithinPolicy(policy, value) } catch (error) {\n if (error instanceof Error && error.message === 'Storage policy payload limit exceeded') throw new PluginError(409, error.message)\n throw error\n }\n}\n/**\n * Check the structural presence of a nonblank tenant/user identity and string role list.\n * @param p - Principal from a trusted authentication resolver.\n * @returns No value; normal completion means the principal has the required shape.\n * @throws Throws PluginError 401 for malformed principal fields.\n * @remarks Shape validation is not authentication, membership verification or resource authorization.\n * @example\n * import { assertPrincipal } from '@alneas/eaos-server/plugin-data'\n * assertPrincipal({ tenantId: 'example-tenant', userId: 'example-user', roles: [] })\n */\nexport function assertPrincipal(p: PluginPrincipal): void {\n if (!p || typeof p.tenantId !== 'string' || !p.tenantId.trim() || typeof p.userId !== 'string' || !p.userId.trim() || !Array.isArray(p.roles) || p.roles.some(r => typeof r !== 'string')) throw new PluginError(401, 'Authenticated principal required')\n}\n/**\n * Hono variables carrying the principal resolved by the trusted plugin router.\n * \n * @see createPluginRouter for canonical host integration.\n */\nexport type PluginHttpEnv = { \n /**\n * Hono variables populated by the trusted principal resolver before operation routes run.\n */\n Variables: { \n /**\n * Verified principal resolved for this request; still subject to current service authorization.\n */\n principal: PluginPrincipal } }\n/**\n * Host-owned request-body bound for the shared authenticated plugin router.\n * \n * @see createPluginRouter for canonical host integration.\n */\nexport interface PluginRouterOptions {\n /**\n * Request body size in bytes; defaults to 131072 and must be an integer from 1024 to 8388608.\n * \n * Trusted host bound, never request-controlled. Default 128KiB.\n */ maxBodyBytes?:number }\n/**\n * Create a bounded Hono router that resolves a verified principal for every request.\n * @param resolvePrincipal - Async host callback returning the authenticated principal or null; host owns current session validation.\n * @param options - Trusted body bound, default 128 KiB; accepted integer range is 1024 bytes through 8 MiB.\n * @returns A Hono router with body limits, scoped principal context and sanitized generic failure responses.\n * @throws Invalid body limits throw at construction. Request-time missing/malformed principals produce 401; unexpected failures become sanitized 500 responses.\n * @remarks Does not supply CSRF/Origin protection or per-resource authorization; compose those at the host/service boundary.\n * @example\n * import { createPluginRouter } from '@alneas/eaos-server/plugin-data'\n * export function routes(resolvePrincipal: Parameters<typeof createPluginRouter>[0]) { return createPluginRouter(resolvePrincipal) }\n */\nexport function createPluginRouter(resolvePrincipal: (c: Context) => Promise<PluginPrincipal | null>, options:PluginRouterOptions={}) {\n const maxSize=options.maxBodyBytes??128*1024\n if(!Number.isSafeInteger(maxSize)||maxSize<1024||maxSize>8*1024*1024)throw Error('Invalid plugin request body bound')\n const app = new Hono<PluginHttpEnv>()\n app.use('*', bodyLimit({ maxSize, onError: c => c.json({ error: 'Request body too large' }, 413) }))\n app.use('*', async (c, next) => { const p = await resolvePrincipal(c); if (!p) throw new PluginError(401, 'Unauthorized'); assertPrincipal(p); c.set('principal', p); await next() })\n app.onError((e, c) => c.json({ error: e instanceof PluginError ? e.message : 'Plugin operation failed' }, e instanceof PluginError ? e.status : 500))\n return app\n}\ntype StandardPluginService = { \n /**\n * Principal-aware operation dispatcher shared by HTTP and MCP; the concrete service owns schema checks and current resource permission.\n * @param principal - Verified current tenant/user principal.\n * @param operation - Declared operation name.\n * @param input - Operation input to validate and authorize at the owning service boundary.\n * @returns The service operation result; authorization and validation stay owner-controlled.\n * @throws Rejects underlying service, authorization or persistence failures.\n */\n execute(principal: PluginPrincipal, operation: string, input: Record<string, any>): Promise<unknown> }\n/**\n * Compose a service-backed authenticated operation router and bound static MCP tools.\n * @param manifest - Plugin metadata whose capabilities remain subject to host admission.\n * @param ServiceClass - Trusted service constructor invoked once with options.\n * @param bindTools - Synchronous tool binder invoked with that same service instance.\n * @param options - Real store, authorization and other service configuration.\n * @param resolvePrincipal - Async trusted request-to-principal resolver; required.\n * @param configureRoutes - Optional synchronous callback adding routes using the same service instance.\n * @param routerOptions - Optional host-owned request body bound.\n * @typeParam TOptions - Host service configuration passed unchanged to the constructor.\n * @typeParam TService - Principal-aware service implementation shared by HTTP and MCP.\n * @returns Manifest fields plus createRoutes() and bound MCP definitions.\n * @throws Missing principal resolver or constructor/router/binder/configuration failures propagate.\n * @remarks Mounting the server does not activate tenants. HTTP and MCP hosts must enforce their current lifecycle/resource admission; static tool binding alone does not do that.\n * @example\n * import { createStandardPluginServer } from '@alneas/eaos-server/plugin-data'\n * export function bindServer(...args: Parameters<typeof createStandardPluginServer>) { return createStandardPluginServer(...args) }\n */\nexport function createStandardPluginServer<TOptions, TService extends StandardPluginService>(\n manifest: PluginManifest,\n ServiceClass: new (options: TOptions) => TService,\n bindTools: (service: TService) => McpToolDefinition[],\n options: TOptions,\n resolvePrincipal: (c: Context) => Promise<PluginPrincipal | null>,\n configureRoutes?: (routes: ReturnType<typeof createPluginRouter>, service: TService) => void,\n routerOptions?:PluginRouterOptions,\n) {\n if (typeof resolvePrincipal !== 'function') throw new Error('Verified principal resolver required')\n const service = new ServiceClass(options), routes = createPluginRouter(resolvePrincipal,routerOptions)\n configureRoutes?.(routes, service)\n routes.post('/:operation', async c => c.json(await service.execute(c.get('principal'), c.req.param('operation'), await jsonBody(c))))\n return { ...manifest, createRoutes: () => routes, mcp: { tools: bindTools(service) } }\n}\n/**\n * Read a JSON object request body with explicit content-type and shape checks.\n * @param c - Hono request context, normally protected by the plugin router body limit.\n * @returns Parsed nonnull object payload; arrays and primitives are rejected.\n * @throws Rejects non-JSON content types and malformed/nonobject JSON with PluginError 400.\n * @remarks This helper does not enforce a body-size bound, tenant identity or operation schema on its own.\n * @example\n * import { jsonBody } from '@alneas/eaos-server/plugin-data'\n * export async function readRequest(c: Parameters<typeof jsonBody>[0]) { return jsonBody(c) }\n */\nexport async function jsonBody(c: Context): Promise<Record<string, any>> {\n if (!/^application\\/json(?:;|$)/i.test(c.req.header('Content-Type') ?? '')) throw new PluginError(400, 'JSON body required')\n const value = await c.req.json().catch(() => null)\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new PluginError(400, 'JSON object required')\n return value\n}\n/**\n * Reject top-level object keys not present in an explicit operation allowlist.\n * @param value - Object whose own enumerable string keys are inspected.\n * @param keys - Trusted allowed top-level key names.\n * @returns No value when all existing keys are allowed.\n * @throws Throws PluginError 400 when an unknown key is present.\n * @remarks Does not require listed keys to exist or validate nested fields.\n * @example\n * import { exactKeys } from '@alneas/eaos-server/plugin-data'\n * exactKeys({ title: 'Example' }, ['title'])\n */\nexport function exactKeys(value: object, keys: string[]): void { if (Object.keys(value).some(k => !keys.includes(k))) throw new PluginError(400, 'Unknown input field') }\n/**\n * Validate bounded nonblank string input while preserving the original whitespace.\n * @param value - Untrusted value to validate.\n * @param name - Trusted field label used in the failure message.\n * @param max - Maximum JavaScript string length; defaults to 256.\n * @returns The original string without trimming.\n * @throws Throws PluginError 400 if input is not a string, trims to empty or exceeds max.\n * @example\n * import { textInput } from '@alneas/eaos-server/plugin-data'\n * const title = textInput('Example', 'title', 80)\n */\nexport function textInput(value: unknown, name: string, max = 256): string { if (typeof value !== 'string' || !value.trim() || value.length > max) throw new PluginError(400, `Invalid ${name}`); return value }\n/**\n * Require a positive safe-integer revision without coercing string inputs.\n * @param value - Untrusted revision value.\n * @returns The positive safe-integer revision.\n * @throws Throws PluginError 400 for nonintegers, numeric strings, zero, negatives or unsafe integers.\n * @example\n * import { revisionInput } from '@alneas/eaos-server/plugin-data'\n * const revision = revisionInput(1)\n */\nexport function revisionInput(value: unknown): number { if (!Number.isSafeInteger(value) || Number(value) < 1) throw new PluginError(400, 'Revision required'); return Number(value) }\n/**\n * Parameterized SQL transport whose host owns tenant session, transaction and provider binding behavior.\n * \n * @see createSqlRecordStore for canonical host integration.\n */\nexport interface RecordSqlDriver {\n /**\n * SQL placeholder/driver dialect selected by trusted host configuration.\n */\n dialect: 'sqlite' | 'postgres' | 'oracle'\n /**\n * Executes trusted parameterized SQL through the host-selected tenant session or transport.\n * \n * Bind arrays are positional. Host owns transaction/commit, Oracle CLOB bindings and authenticated tenant session.\n * @param tenantId - Verified tenant context for host routing/session setup; it is not an independent permission proof.\n * @param sql - Trusted SQL containing explicit tenant predicates; never untrusted SQL text.\n * @param bindings - Positional binds in SQL placeholder order; host handles Oracle CLOB/session details.\n * @returns Optional row data and affected-row count; CAS callers require accurate affectedRows.\n * @throws Rejects propagated host persistence, validation or callback failures.\n \n * @example\n * ```typescript\n * import type { RecordSqlDriver, PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export async function queryTenant(driver: RecordSqlDriver, principal: PluginPrincipal, trustedSql: string, bindings: unknown[]) {\n * // The host supplies dialect-correct SQL with explicit tenant predicates.\n * const result = await driver.execute(principal.tenantId, trustedSql, bindings);\n * return result.rows ?? [];\n * }\n * ```\n */\n execute(tenantId: string, sql: string, bindings: unknown[]): Promise<{ \n /**\n * Optional SQL result rows using host provider object-column names.\n */\n rows?: Record<string, unknown>[]; \n /**\n * Accurate DML row count; required by revision-predicated replace.\n */\n affectedRows?: number }>\n}\n/**\n * Manifest namespace, payload limits and optional canonical JSON document validation for SQL records.\n * \n * @see createSqlRecordStore for canonical host integration.\n */\nexport interface SqlRecordStoreOptions {\n /**\n * Optional trusted logical namespace encoded into physical IDs for a shared table.\n * \n * Logical namespace encoded into the trusted physical id for a shared foundation table.\n */\n namespace?: string\n /**\n * Declared payload/object/history limits; does not configure or authorize a provider.\n * \n * Payload/object/history policy declared by the plugin manifest.\n */\n storagePolicy?: PluginStoragePolicy\n /**\n * Canonical closed payload contracts copied and enforced by the wrapper.\n */\n documents?: readonly JsonDocumentContract[]\n}\nfunction validateNamespace(namespace: string): string {\n if (!/^[a-z][a-z0-9_]{0,62}$/.test(namespace)) throw new Error('Invalid plugin storage namespace')\n return `${namespace}:`\n}\n/**\n * Bind JSON record persistence to a trusted table, namespace and host SQL driver.\n * @param table - Trusted lowercase table identifier, never a request-selected name.\n * @param driver - Tenant-aware SQL transport; host owns transactions, Oracle binding/session cleanup and current authorization.\n * @param options - Optional namespace, payload policy and canonical JSON document contracts.\n * @typeParam T - Stored JSON payload type; runtime shape is enforced only when canonical document contracts are supplied.\n * @returns A record store with tenant predicates, keyset reads and revision-predicated replace/delete operations.\n * @throws Rejects invalid table/namespace/document bindings. Operations propagate provider errors, reject invalid limits/revisions/payloads and map duplicate keys to PluginError 409.\n * @remarks Does not create/migrate tables or add a shared transaction around separate calls. Driver affected-row reporting is required for CAS correctness; hosts enforce live authorization.\n * @example\n * import { createSqlRecordStore } from '@alneas/eaos-server/plugin-data'\n * export function records(driver: Parameters<typeof createSqlRecordStore>[1]) { return createSqlRecordStore<{ title: string }>('example_records', driver) }\n */\nexport function createSqlRecordStore<T>(table: string, driver: RecordSqlDriver, options: SqlRecordStoreOptions = {}): PluginRecordStore<T> {\n if (!/^[a-z][a-z0-9_]{0,62}$/.test(table)) throw new Error('Invalid plugin table')\n const prefix = options.namespace ? validateNamespace(options.namespace) : ''\n const storagePolicy = resolvePluginStoragePolicy(options.storagePolicy)\n const documents = options.documents && structuredClone(options.documents)\n if (documents?.some(d => d.table !== table || d.namespace !== options.namespace)) throw Error('JSON document storage binding differs')\n const validateDocument = documents && createRecordDocumentValidator(documents)\n const physicalId = (id: string) => {\n if (prefix && id.length + prefix.length > 256) throw new PluginError(400, 'Record id is too long for the shared plugin table')\n return `${prefix}${id}`\n }\n const logicalId = (id: string) => prefix ? (id.startsWith(prefix) ? id.slice(prefix.length) : null) : id\n const bind = (i: number) => driver.dialect === 'postgres' ? `$${i}` : driver.dialect === 'oracle' ? `:${i}` : '?'\n const decode = (tenant: string, row: Record<string, unknown>): PluginRecord<T> => {\n const id = logicalId(String(row.id ?? row.ID))\n if (id === null || !id) throw new Error('Record belongs to another plugin storage namespace')\n const record = { id, revision: Number(row.revision ?? row.REVISION), value: JSON.parse(String(row.payload ?? row.PAYLOAD)) }\n validateDocument?.(tenant, record)\n return record\n }\n const listPage = async (tenant: string, limit: number, after = '') => {\n if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw new PluginError(400, 'Limit must be between 1 and 100')\n if (after && (typeof after !== 'string' || !/^[A-Za-z0-9_.:/-]{1,240}$/.test(after))) throw new PluginError(400, 'Invalid page position')\n const bindings: unknown[] = [tenant], filters = [`tenant_id = ${bind(1)}`]\n if (prefix) { bindings.push(prefix, prefix.slice(0,-1)+';'); filters.push(`id >= ${bind(bindings.length-1)} AND id < ${bind(bindings.length)}`) }\n if (after) { bindings.push(physicalId(after)); filters.push(`id > ${bind(bindings.length)}`) }\n const tail = driver.dialect === 'oracle' ? `FETCH FIRST ${limit} ROWS ONLY` : `LIMIT ${limit}`\n return (await driver.execute(tenant, `SELECT id, revision, payload FROM ${table} WHERE ${filters.join(' AND ')} ORDER BY id ${tail}`, bindings)).rows?.map(row => decode(tenant, row)) ?? []\n }\n return {\n async read(tenant, id) { const result = await driver.execute(tenant, `SELECT id, revision, payload FROM ${table} WHERE tenant_id = ${bind(1)} AND id = ${bind(2)}`, [tenant, physicalId(id)]); return result.rows?.[0] ? decode(tenant, result.rows[0]) : null },\n list: (tenant,limit) => listPage(tenant,limit),\n listPage,\n async create(tenant, record) { if (validateDocument && record.revision !== 1) throw new PluginError(409, 'New record revision must be 1'); validateDocument?.(tenant, record); const payload = storagePayload(storagePolicy, record.value); try { await driver.execute(tenant, `INSERT INTO ${table} (tenant_id, id, revision, payload) VALUES (${bind(1)}, ${bind(2)}, ${bind(3)}, ${bind(4)})`, [tenant, physicalId(record.id), record.revision, payload]) } catch (error: any) { if (['SQLITE_CONSTRAINT_PRIMARYKEY', 'SQLITE_CONSTRAINT_UNIQUE', '23505', 'ORA-00001'].includes(error?.code) || error?.errorNum === 1) throw new PluginError(409, 'Record already exists'); throw error } },\n async replace(tenant, record, expected) {\n if (!Number.isSafeInteger(expected) || expected < 1 || record.revision !== expected + 1) throw new Error('Invalid revision transition')\n validateDocument?.(tenant, record)\n const result = await driver.execute(tenant, `UPDATE ${table} SET revision = ${bind(1)}, payload = ${bind(2)} WHERE tenant_id = ${bind(3)} AND id = ${bind(4)} AND revision = ${bind(5)}`, [record.revision, storagePayload(storagePolicy, record.value), tenant, physicalId(record.id), expected])\n if (typeof result.affectedRows !== 'number') throw new Error('Record driver must report affectedRows')\n return result.affectedRows === 1\n },\n async delete(tenant, id, expected) {\n if (documents?.filter(d => id.startsWith(d.recordPrefix ?? '')).sort((a,b) => (b.recordPrefix ?? '').length - (a.recordPrefix ?? '').length)[0]?.immutable) throw new PluginError(409, 'Immutable document cannot be deleted')\n const hasRevision = typeof expected === 'number'\n const sql = hasRevision\n ? `DELETE FROM ${table} WHERE tenant_id = ${bind(1)} AND id = ${bind(2)} AND revision = ${bind(3)}`\n : `DELETE FROM ${table} WHERE tenant_id = ${bind(1)} AND id = ${bind(2)}`\n const bindings = hasRevision ? [tenant, physicalId(id), expected] : [tenant, physicalId(id)]\n const result = await driver.execute(tenant, sql, bindings)\n return (result.affectedRows ?? 0) >= 1\n },\n }\n}\n\n/**\n * Structural subset of the D1 prepared-statement API used by the record adapter.\n * \n * @see createCloudflareD1Driver for canonical host integration.\n */\nexport interface CloudflareD1PreparedStatement {\n /**\n * Binds positional query values to a prepared Worker D1 statement.\n * @param values - Positional values in SQL placeholder order.\n * @returns The bound prepared statement used for all/run.\n * @throws Provider binding errors throw synchronously.\n \n * @example\n * ```typescript\n * import type { CloudflareD1Binding } from '@alneas/eaos-server/plugin-data';\n * export async function readProjection(db: CloudflareD1Binding, tenantId: string) {\n * const statement = db.prepare(\"SELECT ? AS tenant_id\").bind(tenantId);\n * return (await statement.all<{ tenant_id: string }>()).results ?? [];\n * }\n * ```\n */\n bind(...values: unknown[]): CloudflareD1PreparedStatement\n /**\n * Executes a prepared D1 read and resolves its structural query result.\n * @typeParam T - Returned query row shape; defaults to a string-keyed unknown-value record.\n * @returns Optional typed results and provider change metadata.\n * @throws Rejects provider query failures.\n \n * @example\n * ```typescript\n * import type { CloudflareD1Binding } from '@alneas/eaos-server/plugin-data';\n * export async function projection(db: CloudflareD1Binding, tenantId: string) {\n * const result = await db.prepare(\"SELECT ? AS tenant_id\").bind(tenantId).all<{ tenant_id: string }>();\n * return result.results ?? [];\n * }\n * ```\n */\n all<T = Record<string, unknown>>(): Promise<{ \n /**\n * Optional query rows with the caller-selected row shape.\n */\n results?: T[]; \n /**\n * Optional provider execution metadata.\n */\n meta?: { \n /**\n * Optional provider affected-row count; record driver normalizes absence to 0.\n */\n changes?: number } }>\n /**\n * Executes a prepared D1 write and resolves provider change metadata.\n * @returns Optional meta.changes affected-row metadata.\n * @throws Rejects provider execution failures.\n \n * @example\n * ```typescript\n * import type { CloudflareD1Binding } from '@alneas/eaos-server/plugin-data';\n * export async function executeReviewed(db: CloudflareD1Binding, trustedTenantDml: string, bindings: unknown[]) {\n * // Supply parameterized DML whose bindings include the authorized tenant.\n * const result = await db.prepare(trustedTenantDml).bind(...bindings).run();\n * return result.meta?.changes ?? 0;\n * }\n * ```\n */\n run(): Promise<{ \n /**\n * Optional provider execution metadata.\n */\n meta?: { \n /**\n * Optional provider affected-row count; record driver normalizes absence to 0.\n */\n changes?: number } }>\n}\n\n/**\n * Trusted Worker D1 binding supplied by the host runtime.\n * \n * @see createCloudflareD1Driver for canonical host integration.\n */\nexport interface CloudflareD1Binding {\n /**\n * Prepares trusted parameterized SQL on the installed Worker D1 binding.\n * @param query - Trusted SQL text; caller must bind tenant predicates.\n * @returns A statement exposing bind/all/run.\n * @throws Provider preparation errors throw synchronously.\n \n * @example\n * ```typescript\n * import type { CloudflareD1Binding } from '@alneas/eaos-server/plugin-data';\n * export async function tenantProjection(db: CloudflareD1Binding, tenantId: string) {\n * const statement = db.prepare(\"SELECT ? AS tenant_id\");\n * return (await statement.bind(tenantId).all()).results ?? [];\n * }\n * ```\n */\n prepare(query: string): CloudflareD1PreparedStatement\n}\n\n/**\n * Explicit Worker or HTTP transport configuration for the server-side D1 record driver.\n * \n * @see createCloudflareD1Driver for canonical host integration.\n */\nexport interface CloudflareD1DriverOptions {\n /**\n * Optional trusted Worker D1 binding; takes precedence over HTTP credentials when valid.\n * \n * Direct Cloudflare Workers D1 binding (`env.DB`), when running inside a Worker.\n */\n binding?: CloudflareD1Binding\n /**\n * Cloudflare account identity required by HTTP mode.\n * \n * Cloudflare Account ID for remote D1 HTTP API access (e.g. from OCI server or CLI).\n */\n accountId?: string\n /**\n * Cloudflare D1 database identity required by HTTP mode.\n * \n * Cloudflare D1 Database UUID for remote D1 HTTP API access.\n */\n databaseId?: string\n /**\n * Sensitive host API token required by HTTP mode; never expose to browser entries or docs examples.\n * \n * Cloudflare API Token with D1:Edit permission for remote D1 HTTP API access.\n */\n apiToken?: string\n /**\n * Optional trusted fetch implementation; defaults to globalThis.fetch.\n * \n * Optional custom fetch implementation for D1 HTTP API calls.\n */\n fetch?: typeof globalThis.fetch\n /**\n * Trusted HTTP API base; defaults to https://api.cloudflare.com/client/v4.\n * \n * Optional Cloudflare API base URL override (defaults to `https://api.cloudflare.com/client/v4`).\n */\n apiBaseUrl?: string\n /**\n * Optional trusted table name; when supplied the first query runs CREATE TABLE IF NOT EXISTS. Omit when schema lifecycle is independently managed.\n * \n * Optional table name (e.g. `'eaos_customer_records'`) to auto-create via `CREATE TABLE IF NOT EXISTS` on first query.\n */\n autoBootstrapTable?: string\n}\n\nfunction normalizeD1ConstraintError(error: unknown): never {\n const message = error instanceof Error ? error.message : String(error)\n if (/UNIQUE constraint failed|PRIMARY KEY constraint failed|SQLITE_CONSTRAINT/i.test(message)) {\n const constraintErr = new Error(message) as Error & { code: string }\n constraintErr.code = 'SQLITE_CONSTRAINT_PRIMARYKEY'\n throw constraintErr\n }\n throw error instanceof Error ? error : new Error(message)\n}\n\n/**\n * Create a SQLite-dialect record driver using a Worker D1 binding or the explicit Cloudflare HTTP query endpoint.\n * @param options - Trusted binding or complete account/database/token credentials; an available binding takes precedence over HTTP configuration.\n * @returns A RecordSqlDriver whose execute method uses the selected D1 transport.\n * @throws Rejects absent transport or invalid bootstrap table name; query/HTTP failures propagate and duplicate-key failures are normalized.\n * @remarks The execute tenantId is not an independent authorization boundary; SQL callers must bind tenant predicates. autoBootstrapTable optionally executes CREATE TABLE on the first query; omit it when schemas are managed separately. Credentials and custom fetch/base URL are trusted server configuration.\n * @example\n * import { createCloudflareD1Driver } from '@alneas/eaos-server/plugin-data'\n * export function d1(options: Parameters<typeof createCloudflareD1Driver>[0]) { return createCloudflareD1Driver(options) }\n */\nexport function createCloudflareD1Driver(options: CloudflareD1DriverOptions): RecordSqlDriver {\n const hasBinding = Boolean(options.binding && typeof options.binding.prepare === 'function')\n const hasHttp = Boolean(options.accountId?.trim() && options.databaseId?.trim() && options.apiToken?.trim())\n if (!hasBinding && !hasHttp) {\n throw new Error('Cloudflare D1 driver requires either a Worker D1 binding or accountId, databaseId, and apiToken')\n }\n const bootstrapTable = options.autoBootstrapTable\n if (bootstrapTable && !/^[a-z][a-z0-9_]{0,62}$/.test(bootstrapTable)) {\n throw new Error('Invalid D1 bootstrap table name')\n }\n const fetcher = options.fetch ?? globalThis.fetch\n const apiBase = (options.apiBaseUrl ?? 'https://api.cloudflare.com/client/v4').replace(/\\/$/, '')\n let bootstrapped = !bootstrapTable\n\n const runRaw = async (sql: string, bindings: unknown[]): Promise<{ rows?: Record<string, unknown>[]; affectedRows?: number }> => {\n const isSelect = /^\\s*SELECT\\b/i.test(sql)\n try {\n if (hasBinding && options.binding) {\n const stmt = options.binding.prepare(sql).bind(...bindings)\n if (isSelect) {\n const res = await stmt.all<Record<string, unknown>>()\n return { rows: res.results ?? [], affectedRows: res.meta?.changes ?? 0 }\n }\n const res = await stmt.run()\n return { rows: [], affectedRows: res.meta?.changes ?? 0 }\n }\n const url = `${apiBase}/accounts/${encodeURIComponent(options.accountId!)}/d1/database/${encodeURIComponent(options.databaseId!)}/query`\n const response = await fetcher(url, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${options.apiToken!}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ sql, params: bindings }),\n })\n const body = (await response.json().catch(() => null)) as {\n success?: boolean\n errors?: Array<{ message?: string }>\n result?: Array<{ results?: Record<string, unknown>[]; meta?: { changes?: number } }>\n } | null\n if (!response.ok || !body?.success) {\n const errMsg = body?.errors?.map(e => e.message).filter(Boolean).join('; ') || `D1 HTTP query failed (${response.status})`\n return normalizeD1ConstraintError(new Error(errMsg))\n }\n const first = body.result?.[0]\n return {\n rows: first?.results ?? [],\n affectedRows: typeof first?.meta?.changes === 'number' ? first.meta.changes : 0,\n }\n } catch (error) {\n return normalizeD1ConstraintError(error)\n }\n }\n\n return {\n dialect: 'sqlite',\n async execute(_tenantId, sql, bindings) {\n if (!bootstrapped && bootstrapTable) {\n await runRaw(\n `CREATE TABLE IF NOT EXISTS ${bootstrapTable} (tenant_id TEXT NOT NULL, id TEXT NOT NULL, revision INTEGER NOT NULL, payload TEXT NOT NULL, PRIMARY KEY (tenant_id, id))`,\n [],\n )\n bootstrapped = true\n }\n return runRaw(sql, bindings)\n },\n }\n}\n\n/**\n * Resolve a manifest-owned storage table and optional canonical namespace/document bindings.\n * @param manifest - Trusted plugin schema with one owned table or an explicit shared-storage binding.\n * @param driver - Host SQL transport used by the resulting store.\n * @param catalog - Required trusted Data Contract catalog for shared-storage bindings.\n * @typeParam T - Stored payload shape retained by the record store.\n * @returns The tenant-predicated record store for the declared table/namespace.\n * @throws Rejects absent catalog, invalid storage binding or a legacy declaration without exactly one owned table; store validation failures propagate.\n * @remarks Does not install schemas or activate a feature; migration and live authorization remain host responsibilities.\n * @example\n * import { createPluginRecordStore } from '@alneas/eaos-server/plugin-data'\n * export function pluginRecords(manifest: Parameters<typeof createPluginRecordStore>[0], driver: Parameters<typeof createPluginRecordStore>[1], catalog: Parameters<typeof createPluginRecordStore>[2]) { return createPluginRecordStore(manifest, driver, catalog) }\n */\nexport function createPluginRecordStore<T>(manifest: Pick<PluginManifest, 'schema'>, driver: RecordSqlDriver, catalog?: DataContractCatalog): PluginRecordStore<T> {\n const storage = manifest.schema.storage\n if (storage) { if (!catalog) throw Error('Contract-backed record storage requires a trusted schema catalog'); const documents = recordDocuments(catalog, storage); return createSqlRecordStore<T>(storage.table, driver, { namespace: storage.namespace, storagePolicy: manifest.schema.storagePolicy, ...(documents?.length ? { documents } : {}) }) }\n if (manifest.schema.ownedTables.length !== 1) throw new Error('Plugin manifest must declare one storage table or shared storage metadata')\n return createSqlRecordStore<T>(manifest.schema.ownedTables[0]!, driver, { storagePolicy: manifest.schema.storagePolicy })\n}\n\nexport * from './annotations'\n\nexport { ArtifactDeliveryService, deliveryOperations, enqueueDeliverySchema, deliveryJobSchema, recoverDeliverySchema, type DeliveryPorts, type DeliveryJob, type DeliveryRequest, type DeliveryArtifact } from './delivery'\n","import Ajv from 'ajv'\nimport addFormats from 'ajv-formats'\nimport { assertPrincipal, PluginError, type PluginPrincipal, type PluginRecordStore } from './index'\n/**\n * Minimum tenant-owned aggregate state with an append-only in-record operation history.\n * \n * @see RecordCommandService for canonical host integration.\n */\nexport interface CommandState {\n /**\n * Tenant identity bound by the trusted principal; never selected as an authorization grant from request data.\n */\n tenantId: string;\n /**\n * In-record operation/actor/ISO-time history appended for accepted writes; maximum history length is enforced by the service.\n */\n history: { \n /**\n * Declared accepted write operation appended by RecordCommandService.\n */\n operation: string; \n /**\n * Verified user ID whose accepted write created this history entry.\n */\n actorId: string; \n /**\n * Trusted UTC ISO operation timestamp.\n */\n at: string }[] }\n/**\n * Tenant/record/revision envelope returned after an admitted aggregate operation.\n * @typeParam T - Cloned reducer response data or resulting state payload.\n * \n * @see RecordCommandService for canonical host integration.\n */\nexport interface CommandResponse<T> {\n /**\n * Tenant identity bound by the trusted principal; never selected as an authorization grant from request data.\n */\n tenantId: string;\n /**\n * Logical aggregate ID selected by the trusted definition.\n */\n recordId: string;\n /**\n * Observed aggregate revision; new or unstored reads may use 0, while accepted writes advance it by one.\n */\n revision: number;\n /**\n * Cloned reducer result, or the resulting aggregate state when the reducer returns undefined.\n */\n data: T }\n/**\n * Host persistence, transaction and live authorization ports for aggregate command execution.\n * @typeParam T - Tenant-owned aggregate state required by the store and reducer transaction.\n * \n * @see RecordCommandService for canonical host integration.\n */\nexport interface CommandHost<T extends CommandState> {\n /**\n * Optional durable tenant record store; used when transaction is absent.\n */\n store?: PluginRecordStore<T>\n /**\n * Runs aggregate reads, CAS and final permission checks through one real connection-bound transaction.\n * \n * Trusted connection-bound store; all reads, CAS and final authorization share one transaction.\n * May expose an unstored projection at revision 0; the first write creates revision 1.\n * @param principal - Verified current principal owning the transaction.\n * @param work - Async service work receiving the joined record store; do not retain that store after completion.\n * @typeParam R - Value resolved by the transaction/connection callback.\n * @returns The callback result after commit; rejection rolls back joined writes.\n * @throws Rejects propagated host persistence, validation or callback failures.\n \n * @example\n * ```typescript\n * import type { CommandHost, CommandState, PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export async function readAggregate(host: CommandHost<CommandState>, principal: PluginPrincipal, recordId: string) {\n * if (!host.transaction) throw new Error(\"Joined transaction port required\");\n * return host.transaction(principal, store => store.read(principal.tenantId, recordId));\n * }\n * ```\n */\n transaction?<R>(principal:PluginPrincipal,work:(store:PluginRecordStore<T>)=>Promise<R>):Promise<R>\n /**\n * Checks current lifecycle and permission for the operation and complete returned aggregate.\n * \n * Must check live activation and access to the entire returned aggregate, including referenced resources.\n * @param p - Verified principal copied for this check.\n * @param operation - Declared operation name.\n * @param input - Schema input (initial admission occurs before schema validation).\n * @param current - Optional copied current aggregate including all referenced-resource access.\n * @returns Exactly true to admit; false denies with PluginError 403.\n * @throws Rejects propagated host persistence, validation or callback failures.\n \n * @example\n * ```typescript\n * import type { CommandHost, CommandState, PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export async function canOperate(host: CommandHost<CommandState>, principal: PluginPrincipal, operation: string, input: unknown, current: Readonly<CommandState>) {\n * return await host.authorize(principal, operation, input, current) === true;\n * }\n * ```\n */\n authorize(p: PluginPrincipal, operation: string, input: unknown, current?: Readonly<T>): Promise<boolean>\n /**\n * Optional trusted clock used for operation history timestamps; defaults to new Date().\n \n * @returns A valid Date whose toISOString value becomes the operation timestamp.\n * @throws Callback failures propagate to the owning operation; transactional writes roll back when the host boundary rejects.\n */\n now?: () => Date\n}\n/**\n * Private mutable reducer context supplied after command and resource validation.\n * @typeParam T - Private mutable aggregate state supplied to the reducer.\n * \n * @see RecordCommandService for canonical host integration.\n */\nexport interface CommandContext<T> {\n /**\n * Cloned verified principal for this admitted reducer invocation.\n */\n principal: PluginPrincipal;\n /**\n * Declared operation being executed.\n */\n operation: string;\n /**\n * Cloned schema-validated operation input.\n */\n args: Record<string, any>;\n /**\n * Private mutable aggregate snapshot; persist through the owning service rather than writing the store directly.\n */\n state: T;\n /**\n * Trusted UTC ISO operation timestamp.\n */\n at: string;\n /**\n * Logical aggregate ID resolved for this command.\n */\n recordId: string }\n/**\n * Executes schema-validated aggregate reducers through tenant isolation, live admission and revision-predicated persistence.\n * \n * Plugin-owned reducers may change their private snapshot only; irreversible external effects must be queued durably.\n * @typeParam T - Tenant-owned aggregate state with tenantId and appendable operation history.\n * \n * @remarks\n * Requires server Ajv/formats and a real host store or connection-bound transaction. Reducers mutate only their private cloned snapshot; queue irreversible external effects durably. Transactional hosts keep reads, write/CAS and final admission in one commit boundary; plain stores do not add a transaction. No command deduplication or automatic retry is added.\n * \n * @example\n * ```typescript\n * import { RecordCommandService, type CommandState, type CommandHost } from '@alneas/eaos-server/plugin-data';\n * export function connectAggregate<T extends CommandState>(host: CommandHost<T>, definition: ConstructorParameters<typeof RecordCommandService<T>>[1]) { return new RecordCommandService(host, definition); }\n * ```\n */\nexport class RecordCommandService<T extends CommandState> {\n private readonly validators\n /**\n * Compiles the declared operation schemas and binds real host persistence/admission capabilities.\n * @param host - Live authorization and durable store or transaction; transaction takes precedence when provided.\n * @param definition - Plugin schemas, write-operation allowlist, record-ID resolver, initial-state factory, reducer and invariant validator.\n * @throws Throws for absent durable store/transaction or live authorization and for invalid strict Ajv schemas.\n * \n * @example\n * ```typescript\n * import { RecordCommandService, type CommandState, type CommandHost } from '@alneas/eaos-server/plugin-data';\n * export function connectAggregate<T extends CommandState>(host: CommandHost<T>, definition: ConstructorParameters<typeof RecordCommandService<T>>[1]) { return new RecordCommandService(host, definition); }\n * ```\n */\n constructor(private readonly host: CommandHost<T>, private readonly definition: {\n \n /**\n * Strict noncoercing JSON Schemas indexed by accepted operation names.\n */\n schemas: Record<string, object>; \n /**\n * Explicit operation names that persist state, require matching revision and append history.\n */\n writes: readonly string[]; \n /**\n * Optional pure resolver from admitted input to a nonblank record scope up to 256 characters; omitted uses state.\n \n * @param input - Cloned schema-admitted input.\n * @returns Nonblank logical record ID up to 256 characters; omitted resolver defaults to state.\n * @throws Callback failures propagate to the owning operation; transactional writes roll back when the host boundary rejects.\n */\n recordId?: (input: Record<string, any>) => string\n \n /**\n * Create a tenant/record-bound unstored aggregate snapshot when no row exists.\n \n * @param tenantId - Verified tenant ID owning the aggregate.\n * @param recordId - Resolved logical record ID.\n * @returns A new private unstored tenant-owned state with initialized history.\n * @throws Callback failures propagate to the owning operation; transactional writes roll back when the host boundary rejects.\n */\n initial: (tenantId: string, recordId: string) => T\n \n /**\n * Async plugin reducer receiving private state/input and verified context; mutate only that snapshot and queue external effects durably.\n \n * @param context - Private mutable state, cloned principal/input and trusted operation time.\n * @returns Optional domain response data; undefined selects the resulting state for response data.\n * @throws Callback failures propagate to the owning operation; transactional writes roll back when the host boundary rejects.\n */\n reduce: (context: CommandContext<T>) => Promise<unknown>\n \n /**\n * Synchronous aggregate invariant assertion before/after writes; throw to reject invalid state.\n \n * @param state - Private aggregate state whose tenant/history/domain invariants must hold.\n * @returns Completes without a value when invariants pass; throw to reject before persistence.\n * @throws Callback failures propagate to the owning operation; transactional writes roll back when the host boundary rejects.\n */\n validate: (state: T) => void\n }) {\n if ((!host?.store && typeof host?.transaction !== 'function') || typeof host.authorize !== 'function') throw new Error('Durable store and live authorization required')\n const ajv = new Ajv({ strict: true, coerceTypes: false }); addFormats(ajv)\n this.validators = new Map(Object.entries(definition.schemas).map(([key, schema]) => [key, ajv.compile(schema)]))\n }\n /**\n * Validates and admits one aggregate operation, running a reducer against a private current snapshot.\n * @param principal - Host-authenticated current tenant/user context; structural validation alone proves no membership.\n * @param operation - Declared schema key; membership in definition.writes selects persistence.\n * @param input - Operation-schema input; writes require a safe integer revision matching the current snapshot, including 0 for a new/unstored aggregate.\n * @returns A tenant/record/revision envelope with cloned reducer data, or resulting state when the reducer returns undefined; read-only reducers do not persist mutations.\n * @throws Rejects malformed principal (401), denied live admission (403), schema/scope errors (400), stale revision/capacity/CAS conflict (409), invalid foreign records/reducer scope, and propagated reducer/invariant/clock/store/transaction failures.\n * \n * @remarks\n * Record ID defaults to state and must be nonblank/up to 256 characters. Writes append actor/UTC history and reject over 5000 entries or 8 MiB JSON state. Host transaction projections may start at revision 0. Rejections can follow partial plain-store/adapter effects; callers must reload before retrying uncertain outcomes.\n * \n * @example\n * ```typescript\n * import { RecordCommandService, type CommandState, type PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export function executeAggregate<T extends CommandState>(service: RecordCommandService<T>, principal: PluginPrincipal, operation: string, input: unknown) { return service.execute(principal, operation, input); }\n * ```\n */\n async execute(principal: PluginPrincipal, operation: string, input: unknown): Promise<CommandResponse<any>> {\n assertPrincipal(principal)\n const p = structuredClone(principal), args = structuredClone(input) as Record<string, any>\n const allow = async (state?: T) => { if (await this.host.authorize(structuredClone(p), operation, structuredClone(args), state && structuredClone(state)) !== true) throw new PluginError(403, 'Plugin access denied') }\n await allow()\n if (!this.validators.get(operation)?.(args)) throw new PluginError(400, 'Invalid command')\n const id = this.definition.recordId?.(args) ?? 'state'\n if (typeof id !== 'string' || !id.trim() || id.length > 256) throw new PluginError(400, 'Invalid record scope')\n const run = async (store:PluginRecordStore<T>) => {\n const record = await store.read(p.tenantId, id)\n if (record && (record.id !== id || record.value.tenantId !== p.tenantId || !Number.isSafeInteger(record.revision) || record.revision < (this.host.transaction ? 0 : 1))) throw new Error('Foreign or invalid plugin record')\n const state = structuredClone(record?.value ?? this.definition.initial(p.tenantId, id)), current = structuredClone(state), revision = record?.revision ?? 0\n this.definition.validate(state); await allow(current)\n const write = this.definition.writes.includes(operation)\n if (write && (!Number.isSafeInteger(args.revision) || args.revision !== revision)) throw new PluginError(409, 'Plugin revision changed')\n const at = (this.host.now?.() ?? new Date()).toISOString()\n const result = await this.definition.reduce({ principal: structuredClone(p), operation, args, state, at, recordId: id })\n if (write) {\n if (state.tenantId !== p.tenantId) throw new Error('Reducer changed tenant')\n state.history.push({ operation, actorId: p.userId, at }); this.definition.validate(state)\n if (state.history.length > 5000 || Buffer.byteLength(JSON.stringify(state)) > 8 * 1024 * 1024) throw new PluginError(409, 'Plugin aggregate capacity reached')\n await allow(current)\n const next = { id, revision: revision + 1, value: state }\n if (!record || revision===0) await store.create(p.tenantId, next)\n else if (!await store.replace(p.tenantId, next, revision)) throw new PluginError(409, 'Plugin revision changed')\n } else await allow(current)\n if(this.host.transaction)await allow(current)\n return { tenantId: p.tenantId, recordId: id, revision: revision + (write ? 1 : 0), data: structuredClone(result === undefined ? state : result) }\n }\n return this.host.transaction ? this.host.transaction(p,run) : run(this.host.store!)\n }\n}\n","import {assertPrincipal,PluginError,type PluginPrincipal} from './index'\nimport {atomicHash,type AtomicSession} from './atomic'\n/**\n * Version-1 hash-linked journal event storing payload hashes and optional command receipt identity.\n * \n * @see appendAtomicAudit for canonical host integration.\n */\nexport interface AtomicAuditEvent {\n /**\n * Persisted journal schema version; must be 1.\n */\n version:1;\n /**\n * Tenant identity bound by the trusted principal; never selected as an authorization grant from request data.\n */\n tenantId:string;\n /**\n * Positive monotonically increasing journal position within the tenant/namespace.\n */\n sequence:number;\n /**\n * Trusted operation label recorded for this admitted command.\n */\n operation:string;\n /**\n * Verified actor identity at append time.\n */\n actorId:string;\n /**\n * UTC ISO append timestamp.\n */\n at:string;\n /**\n * Hash of JSON-normalized command input; no input payload bytes are stored here.\n */\n inputHash:string;\n /**\n * Hash of JSON-normalized command result; undefined is normalized to null.\n */\n resultHash:string;\n /**\n * Optional immutable command receipt key, otherwise null.\n */\n commandKey:string|null;\n /**\n * Previous journal event hash, or null for the first event.\n */\n previousHash:string|null;\n /**\n * Canonical hash of the other event fields; not an external signature.\n */\n hash:string}\ninterface Head {version:1;tenantId:string;sequence:number;hash:string}\nconst eventKey=(sequence:number)=>'audit/event/'+String(sequence).padStart(16,'0')\nconst jsonHash=(value:unknown)=>atomicHash(value===undefined?null:JSON.parse(JSON.stringify(value)))\n/**\n * Append a hash-linked immutable audit event and CAS-update its head in the current transaction.\n * @param tx - Live atomic session shared with the domain command.\n * @param p - Verified tenant/user principal.\n * @param operation - Trusted nonempty operation label of at most 240 characters.\n * @param input - Input whose JSON-normalized hash is recorded; payload bytes are not stored in the audit event.\n * @param result - Result whose JSON-normalized hash is recorded; undefined is normalized to null.\n * @param commandKey - Optional command/ receipt key linking command input/result evidence; defaults to null.\n * @returns The appended version-1 event with sequence and integrity hash.\n * @throws Rejects invalid principals/labels/receipt keys, corrupt head/previous event, sequence capacity or transaction failures.\n * @remarks Requires the caller's existing transaction and current authorization. Hash continuity is not an external trust anchor; real business payloads remain outside audit events.\n * @example\n * import { appendAtomicAudit } from '@alneas/eaos-server/plugin-data'\n * export function audit(tx: Parameters<typeof appendAtomicAudit>[0], p: Parameters<typeof appendAtomicAudit>[1], input: unknown, result: unknown) { return appendAtomicAudit(tx, p, 'example-operation', input, result) }\n */\nexport async function appendAtomicAudit(tx:AtomicSession,p:PluginPrincipal,operation:string,input:unknown,result:unknown,commandKey:string|null=null){assertPrincipal(p);if(!operation||operation.length>240||commandKey!==null&&!commandKey.startsWith('command/'))throw new PluginError(400,'Invalid trusted audit operation');const head=await tx.get<Head>('audit/head');if(head&&(head.value.version!==1||head.value.tenantId!==p.tenantId||!Number.isSafeInteger(head.value.sequence)||head.value.sequence<1||!/^[a-f0-9]{64}$/.test(head.value.hash)))throw new PluginError(409,'Audit head differs');if(head){const previous=await tx.get<AtomicAuditEvent>(eventKey(head.value.sequence));if(!previous||previous.value.hash!==head.value.hash)throw new PluginError(409,'Previous audit event unavailable');const {hash,...v}=previous.value;if(hash!==atomicHash(v))throw new PluginError(409,'Previous audit integrity differs')}const sequence=(head?.value.sequence??0)+1;if(!Number.isSafeInteger(sequence)||sequence>1e12)throw new PluginError(409,'Audit sequence at capacity');const value:Omit<AtomicAuditEvent,'hash'>={version:1,tenantId:p.tenantId,sequence,operation,actorId:p.userId,at:new Date().toISOString(),inputHash:jsonHash(input),resultHash:jsonHash(result),commandKey,previousHash:head?.value.hash??null},event={...value,hash:atomicHash(value)};await tx.put(eventKey(sequence),event,0);await tx.put('audit/head',{version:1,tenantId:p.tenantId,sequence,hash:event.hash},head?.revision??0);return event}\n/**\n * Read and verify one bounded page of immutable tenant audit events.\n * @param tx - Live tenant-scoped atomic session.\n * @param p - Verified principal whose tenant must match each event.\n * @param afterSequence - Exclusive nonnegative sequence; defaults to 0.\n * @param limit - Integer page size from 1 to 100; defaults to 50.\n * @returns Verified events and a continuation sequence or null when no further row was observed.\n * @throws Rejects invalid pagination, event identity/version/revision/hash mismatches or store failures.\n * @remarks Caller enforces current resource permission before and after reading. One page does not verify full chain continuity or an external trust anchor.\n * @example\n * import { readAtomicAudit } from '@alneas/eaos-server/plugin-data'\n * export function auditPage(tx: Parameters<typeof readAtomicAudit>[0], p: Parameters<typeof readAtomicAudit>[1]) { return readAtomicAudit(tx, p, 0, 50) }\n */\nexport async function readAtomicAudit(tx:AtomicSession,p:PluginPrincipal,afterSequence=0,limit=50){assertPrincipal(p);if(!Number.isSafeInteger(afterSequence)||afterSequence<0||!Number.isSafeInteger(limit)||limit<1||limit>100)throw new PluginError(400,'Invalid audit page');const rows=await tx.list<AtomicAuditEvent>('audit/event/',afterSequence?eventKey(afterSequence):'',limit+1);const events:AtomicAuditEvent[]=[];for(const row of rows.slice(0,limit)){const {hash,...v}=row.value;if(v.tenantId!==p.tenantId||v.version!==1||!Number.isSafeInteger(v.sequence)||v.sequence<1||row.id!==eventKey(v.sequence)||row.revision!==1||hash!==atomicHash(v))throw new PluginError(409,'Audit event integrity differs');events.push(row.value)}return{events,nextSequence:rows.length>limit?events.at(-1)!.sequence:null}}\n/**\n * Verify a bounded audit chain, its head and linked command receipts within the current tenant transaction.\n * @param tx - Live atomic session containing the journal and receipts.\n * @param p - Verified tenant/user principal with host-admitted audit access.\n * @returns Tenant identity, verified event count/head hash and explicit externalTrustAnchor=false.\n * @throws Rejects more than 10000 events, discontinuous sequence/hash links, receipt mismatches, corrupt head/tail or store failures.\n * @remarks Integrity verification cannot prove an external actor has not rewritten the entire journal. Larger histories need the host's reviewed archival verifier.\n * @example\n * import { verifyAtomicAudit } from '@alneas/eaos-server/plugin-data'\n * export function verifyJournal(tx: Parameters<typeof verifyAtomicAudit>[0], p: Parameters<typeof verifyAtomicAudit>[1]) { return verifyAtomicAudit(tx, p) }\n */\nexport async function verifyAtomicAudit(tx:AtomicSession,p:PluginPrincipal){assertPrincipal(p);const head=await tx.get<Head>('audit/head');let after=0,count=0,previousHash:string|null=null;for(;;){const page=await readAtomicAudit(tx,p,after,100);for(const event of page.events){if(++count>10000)throw new PluginError(409,'Audit verification exceeds 10000 events; host archival verifier required');if(event.sequence!==count||event.previousHash!==previousHash)throw new PluginError(409,'Audit sequence or previous hash differs');if(event.commandKey){const receipt=await tx.get<{hash:string;result:unknown}>(event.commandKey);if(!receipt||receipt.revision!==1||receipt.value.hash!==event.inputHash||jsonHash(receipt.value.result)!==event.resultHash)throw new PluginError(409,'Audit command receipt differs')}previousHash=event.hash;after=event.sequence}if(page.nextSequence===null)break}if(count===0&&head||count>0&&(!head||head.value.version!==1||head.value.tenantId!==p.tenantId||head.value.sequence!==count||head.value.hash!==previousHash))throw new PluginError(409,'Audit head or event tail differs');return{tenantId:p.tenantId,status:'verified' as const,count,headHash:previousHash,coverage:'atomic-journal-v1' as const,externalTrustAnchor:false as const}}\n","import { atomicSqlBindings as joinedConnections } from './atomic-context'\nimport {appendAtomicAudit} from './audit'\nimport { assertPrincipal, PluginError, type PluginPrincipal } from './index'\nimport type { PluginRecordStore } from './index'\nimport type { DataContractCatalog, JsonDocumentContract } from '@alneas/eaos-server/lifecycle-engine'\nimport { createRecordDocumentValidator, recordDocuments } from './json-documents'\nimport { canonicalJsonHash } from '@alneas/eaos-core/serialization'\nimport { assertPayloadWithinPolicy, resolvePluginStoragePolicy, type PluginManifest, type PluginStoragePolicy } from '@alneas/eaos-core/plugin-sdk'\n\nfunction storagePayload(policy: PluginStoragePolicy, value: unknown): string {\n try { return assertPayloadWithinPolicy(policy, value) } catch (error) {\n if (error instanceof Error && error.message === 'Storage policy payload limit exceeded') throw new PluginError(409, error.message)\n throw error\n }\n}\n\n/**\n * Tenant-scoped logical row and its CAS revision at the time of reading/writing.\n * @typeParam T - JSON row payload shape; defaults to unknown.\n * \n * @see createAtomicRepository for canonical host integration.\n */\nexport interface AtomicRow<T = unknown> {\n /**\n * Logical tenant/namespace-scoped record identity.\n */\n id: string;\n /**\n * CAS revision for the stored envelope; persisted records start at 1 unless a documented host projection uses 0.\n */\n revision: number;\n /**\n * Stored JSON payload whose runtime validation depends on the configured document contracts.\n */\n value: T }\n/**\n * Temporary tenant/namespace-bound session valid only inside its repository work callback.\n * \n * @see createAtomicRepository for canonical host integration.\n */\nexport interface AtomicSession {\n /**\n * Performs one scoped read inside the active repository transaction.\n * @param id - Logical row ID; 1–240 supported record-key characters.\n * @typeParam T - JSON payload type read or persisted by this session operation.\n * @returns The scoped envelope or null when absent.\n * @throws Rejects expired session, invalid IDs/revisions/limits, document/payload errors, duplicate/create or CAS conflict and provider failures as applicable.\n \n * @example\n * ```typescript\n * import type { AtomicRepository, PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export async function readTitle(repository: AtomicRepository, principal: PluginPrincipal, id: string) {\n * return repository.run(principal, async session => {\n * const row = await session.get<{ title: string }>(id);\n * return row?.value.title ?? null;\n * });\n * }\n * ```\n */\n get<T>(id: string): Promise<AtomicRow<T> | null>\n /**\n * Performs ordered batch reads inside the active repository transaction.\n * \n * Batch reads preserve tenant scope and input order; missing rows are null.\n * @param ids - Logical IDs in desired output order; duplicates retain their positions.\n * @typeParam T - JSON payload type read or persisted by this session operation.\n * @returns One envelope or null per input ID in the same order.\n * @throws Rejects expired session, invalid IDs/revisions/limits, document/payload errors, duplicate/create or CAS conflict and provider failures as applicable.\n \n * @example\n * ```typescript\n * import type { AtomicRepository, PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export async function readTitles(repository: AtomicRepository, principal: PluginPrincipal, ids: string[]) {\n * return repository.run(principal, async session => {\n * if (!session.getMany) throw new Error(\"Batch reads not supported\");\n * return session.getMany<{ title: string }>(ids);\n * });\n * }\n * ```\n */\n getMany?<T>(ids: string[]): Promise<(AtomicRow<T> | null)[]>\n /**\n * Performs transactional batch CAS writes inside the active repository transaction.\n * \n * Every item uses CAS in the enclosing transaction; any failure rolls back all items.\n * @param changes - Unique logical-ID/value/expected changes; expected=0 creates and positive expected performs exact CAS.\n * @typeParam T - JSON payload type read or persisted by this session operation.\n * @returns Next-revision envelopes in input order; any failure must reject the enclosing transaction.\n * @throws Rejects expired session, invalid IDs/revisions/limits, document/payload errors, duplicate/create or CAS conflict and provider failures as applicable.\n \n * @example\n * ```typescript\n * import type { AtomicRepository, PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export async function createPair(repository: AtomicRepository, principal: PluginPrincipal) {\n * return repository.run(principal, async session => {\n * if (!session.putMany) throw new Error(\"Batch writes not supported\");\n * return session.putMany([{ id: \"examples/first\", value: { title: \"First\" }, expected: 0 }, { id: \"examples/second\", value: { title: \"Second\" }, expected: 0 }]);\n * });\n * }\n * ```\n */\n putMany?<T>(changes: { \n /**\n * Unique logical record key within this batch and tenant namespace.\n */\n id: string; \n /**\n * JSON payload to validate against configured policy/document contracts.\n */\n value: T; \n /**\n * Expected safe CAS revision; 0 creates, positive values replace exactly that revision.\n */\n expected: number }[]): Promise<AtomicRow<T>[]>\n /**\n * Performs a bounded scoped keyset read inside the active repository transaction.\n * \n * Empty prefix reads the repository's own tenant/namespace, never another tenant.\n * @param prefix - Logical prefix; empty stays within this repository tenant/namespace.\n * @param after - Optional exclusive logical ID; defaults to the start of the prefix range.\n * @param limit - Integer page size 1–101; defaults to 100.\n * @typeParam T - JSON payload type read or persisted by this session operation.\n * @returns Envelopes in stable logical-ID order within the prefix.\n * @throws Rejects expired session, invalid IDs/revisions/limits, document/payload errors, duplicate/create or CAS conflict and provider failures as applicable.\n \n * @example\n * ```typescript\n * import type { AtomicRepository, PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export async function firstPage(repository: AtomicRepository, principal: PluginPrincipal) {\n * return repository.run(principal, session => session.list<{ title: string }>(\"examples/\", \"\", 20));\n * }\n * ```\n */\n list<T>(prefix: string, after?: string, limit?: number): Promise<AtomicRow<T>[]>\n /**\n * Performs one create-or-CAS write inside the active repository transaction.\n * \n * expected=0 creates; otherwise atomically replaces exactly the expected revision.\n * @param id - Logical row ID.\n * @param value - JSON payload admitted by configured limits/contracts.\n * @param expected - Safe integer expected revision from 0 to MAX_SAFE_INTEGER-1; 0 creates, otherwise exact CAS.\n * @typeParam T - JSON payload type read or persisted by this session operation.\n * @returns A cloned-payload envelope with revision expected+1.\n * @throws Rejects expired session, invalid IDs/revisions/limits, document/payload errors, duplicate/create or CAS conflict and provider failures as applicable.\n \n * @example\n * ```typescript\n * import type { AtomicRepository, PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export async function createTitle(repository: AtomicRepository, principal: PluginPrincipal, id: string, title: string) {\n * return repository.run(principal, session => session.put(id, { title }, 0));\n * }\n * ```\n */\n put<T>(id: string, value: T, expected: number): Promise<AtomicRow<T>>\n}\n/**\n * Host-admitted transactional entrypoint that scopes all session operations to one verified principal.\n * \n * @see createAtomicRepository for canonical host integration.\n */\nexport interface AtomicRepository {\n /**\n * Runs work in one verified tenant transaction whose session expires when work settles.\n * @param principal - Verified tenant/user principal; repository structure checks do not prove live permission.\n * @param work - Async domain work; never let session or joined SQL capabilities escape its lifetime.\n * @typeParam T - Value resolved by the transaction/connection callback.\n * @returns The callback result after successful commit; work/commit failure rejects and triggers rollback.\n * @throws Rejects propagated host persistence, validation or callback failures.\n \n * @example\n * ```typescript\n * import type { AtomicRepository, PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export async function updateTitle(repository: AtomicRepository, principal: PluginPrincipal, id: string, title: string) {\n * return repository.run(principal, async session => {\n * const current = await session.get<{ title: string }>(id);\n * if (!current) throw new Error(\"Record unavailable\");\n * return session.put(id, { title }, current.revision);\n * });\n * }\n * ```\n */\n run<T>(principal: PluginPrincipal, work: (session: AtomicSession) => Promise<T>): Promise<T>\n}\n/**\n * Connection-bound SQL operations sharing the enclosing commit/rollback boundary.\n * \n * @see createAtomicRepository for canonical host integration.\n */\nexport interface AtomicSqlConnection {\n /**\n * Executes one trusted SQL statement on the exact connection owning the enclosing transaction.\n * @param sql - Trusted parameterized SQL with tenant/namespace predicates.\n * @param binds - Positional bind values in placeholder order.\n * @returns Optional query rows and an accurate affected-row count.\n * @throws Rejects propagated host persistence, validation or callback failures.\n \n * @example\n * ```typescript\n * import type { AtomicSqlDriver, PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export async function queryJoined(driver: AtomicSqlDriver, principal: PluginPrincipal, trustedTenantSql: string, bindings: unknown[]) {\n * return driver.transaction(principal, async connection => {\n * return (await connection.execute(trustedTenantSql, bindings)).rows ?? [];\n * });\n * }\n * ```\n */\n execute(sql: string, binds: unknown[]): Promise<{ \n /**\n * Optional object rows from SELECT execution on this connection.\n */\n rows?: Record<string, unknown>[]; \n /**\n * Accurate affected-row count for scalar execution or one count per ordered batch bind row.\n */\n affectedRows: number }>\n /**\n * Optionally executes ordered bind batches on the same transaction connection.\n * @param sql - Trusted parameterized DML.\n * @param binds - Ordered positional bind rows.\n * @returns An affectedRows count for every bind row in input order; missing/wrong counts must fail CAS.\n * @throws Rejects propagated host persistence, validation or callback failures.\n \n * @example\n * ```typescript\n * import type { AtomicSqlDriver, PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export async function batchReviewed(driver: AtomicSqlDriver, principal: PluginPrincipal, trustedTenantDml: string, binds: unknown[][]) {\n * return driver.transaction(principal, async connection => {\n * if (!connection.executeMany) throw new Error(\"Batch DML not supported\");\n * return (await connection.executeMany(trustedTenantDml, binds)).affectedRows;\n * });\n * }\n * ```\n */\n executeMany?(sql: string, binds: unknown[][]): Promise<{ \n /**\n * Accurate affected-row count for scalar execution or one count per ordered batch bind row.\n */\n affectedRows: number[] }>\n}\n/**\n * Provider transaction boundary required for envelope CAS, domain writes and durable journal atomicity.\n * \n * @see createAtomicRepository for canonical host integration.\n */\nexport interface AtomicSqlDriver {\n /**\n * SQL placeholder/driver dialect selected by trusted host configuration.\n */\n dialect: 'sqlite' | 'oracle' | 'postgres'\n /**\n * Acquires one transaction connection, commits success and rolls back rejection.\n * \n * Same connection for every statement; commits on success, rolls back on rejection.\n * @param principal - Verified tenant/user principal used for host session admission.\n * @param work - Async work on the same connection for every domain/CAS/audit statement.\n * @typeParam T - Value resolved by the transaction/connection callback.\n * @returns The callback result after commit; all joined writes roll back on failure.\n * @throws Rejects propagated host persistence, validation or callback failures.\n \n * @example\n * ```typescript\n * import type { AtomicSqlDriver, PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export async function readJoined(driver: AtomicSqlDriver, principal: PluginPrincipal, trustedTenantSql: string, bindings: unknown[]) {\n * return driver.transaction(principal, async connection => {\n * const result = await connection.execute(trustedTenantSql, bindings);\n * return result.rows ?? [];\n * });\n * }\n * ```\n */\n transaction<T>(principal: PluginPrincipal, work: (connection: AtomicSqlConnection) => Promise<T>): Promise<T>\n}\n/**\n * Expose SQL execution on the exact active transaction that owns envelope CAS and receipts.\n * @param session - Currently active repository session carrying a trusted SQL capability binding.\n * @param principal - Verified principal matching both tenant and user of the joined transaction.\n * @returns The bound driver dialect and an execute(tenantId, sql, binds) method using the existing connection.\n * @throws Throws for malformed/mismatched principals, missing/expired transaction bindings or a foreign execute tenant; driver failures propagate.\n * @remarks Never retain or use the executor after the parent transaction callback returns. It does not open another transaction or authorize arbitrary SQL.\n * @example\n * import { joinedAtomicSqlExecutor, type AtomicRepository, type PluginPrincipal } from '@alneas/eaos-server/plugin-data'\n * export function queryJoined(repository: AtomicRepository, principal: PluginPrincipal, statement: string, binds: unknown[]) {\n * // The host supplies trusted SQL and verifies resource permission before entry.\n * return repository.run(principal, session => joinedAtomicSqlExecutor(session, principal).execute(principal.tenantId, statement, binds))\n * }\n */\nexport function joinedAtomicSqlExecutor(session: AtomicSession, principal: PluginPrincipal) {\n assertPrincipal(principal)\n const binding = joinedConnections.get(session)\n if (!binding || binding.principal.tenantId !== principal.tenantId || binding.principal.userId !== principal.userId) throw new Error('Live joined SQL transaction required')\n return {\n dialect: binding.dialect,\n/**\n * Executes trusted SQL on this session's still-active joined connection.\n * @param tenantId - Must match the verified tenant bound to the original session.\n * @param sql - Trusted parameterized SQL with explicit tenant predicates.\n * @param binds - Positional bind values in placeholder order.\n * @returns Query rows and affected-row metadata from the existing transaction.\n * @throws Rejects expired/mismatched bindings, foreign tenant or underlying SQL failure.\n * @see joinedAtomicSqlExecutor for scoped usage that does not retain this capability.\n */\nasync execute(tenantId: string, sql: string, binds: unknown[]) {\n if (joinedConnections.get(session) !== binding || tenantId !== binding.principal.tenantId) throw new Error('Joined SQL transaction expired or tenant differs')\n return binding.connection.execute(sql, binds)\n },\n }\n}\n/**\n * Compute the canonical JSON SHA-256 used by atomic commands and scoped cursors.\n * @param value - Canonical-JSON-compatible value to hash.\n * @returns Lowercase hexadecimal SHA-256.\n * @throws Canonical serialization rejects unsupported or invalid values.\n * @remarks A hash binds content; it is not a signature or external trust anchor.\n * @example\n * import { atomicHash } from '@alneas/eaos-server/plugin-data'\n * const hash = atomicHash({ id: 'example' })\n */\nexport function atomicHash(value: unknown): string {\n return canonicalJsonHash(value)\n}\n/**\n * Replay or atomically record one principal/operation-scoped command result in an existing transaction.\n * @param tx - Live tenant-scoped atomic session enclosing the actual domain work.\n * @param p - Verified principal whose user ID scopes the command receipt.\n * @param operation - Trusted operation name included in the receipt key.\n * @param input - Complete command input with a commandId of 1–80 letters/digits/underscore/hyphen.\n * @param work - Async domain callback run only for a new command; must remain inside the same transaction.\n * @typeParam T - JSON-serializable domain result stored and returned by the command receipt.\n * @returns The existing identical receipt result or the newly computed result.\n * @throws Rejects malformed command IDs, input reuse with a different hash, CAS/audit failures and propagated work errors.\n * @remarks Caller performs live resource authorization before replay as well as execution. Domain writes, receipt and audit share the existing transaction; irreversible external effects must be durably queued, not performed inside work.\n * @example\n * import { atomicCommand, type AtomicRepository, type AtomicSession, type PluginPrincipal } from '@alneas/eaos-server/plugin-data'\n * export function command<T>(repository: AtomicRepository, principal: PluginPrincipal, input: { commandId: string }, work: (session: AtomicSession) => Promise<T>) {\n * // The host performs live resource admission before replay or new execution.\n * return repository.run(principal, session => atomicCommand(session, principal, 'example-operation', input, () => work(session)))\n * }\n */\nexport async function atomicCommand<T>(tx: AtomicSession, p: PluginPrincipal, operation: string, input: { \n /**\n * Stable nonempty 1–80 character command ID scoped by actor and operation; identical full input replays the stored result.\n */\n commandId: string }, work: () => Promise<T>): Promise<T> {\n if (!/^[A-Za-z0-9_-]{1,80}$/.test(input.commandId)) throw new PluginError(400, 'Command ID required')\n const key = `command/${atomicHash([p.userId, operation, input.commandId])}`, hash = atomicHash(input)\n const old = await tx.get<{ hash: string; result: T }>(key)\n if (old) { if (old.value.hash !== hash) throw new PluginError(409, 'Command ID reused with different input'); return old.value.result }\n const result = await work()\n await tx.put(key, { hash, result }, 0)\n await appendAtomicAudit(tx,p,operation,input,result,key)\n return result\n}\n/**\n * Encode an exclusive record position bound to the canonical hash of its query scope.\n * @param scope - Tenant/user/operation/filter scope defined by the caller.\n * @param after - Exclusive logical record ID to resume after.\n * @returns Base64url cursor containing the scope hash and position.\n * @throws Unsupported canonical scope values or JSON serialization failures propagate.\n * @remarks Encoding is not encryption or a signature; the reader validates scope and record-key grammar.\n * @example\n * import { recordCursor } from '@alneas/eaos-server/plugin-data'\n * const cursor = recordCursor(['example-tenant', 'list'], 'record-1')\n */\nexport function recordCursor(scope: unknown, after: string): string { return Buffer.from(JSON.stringify({ scope: atomicHash(scope), after })).toString('base64url') }\n/**\n * Decode a cursor only when its scope hash and logical record key match the current query.\n * @param scope - Current tenant/user/operation/filter scope.\n * @param cursor - Optional base64url cursor; omission returns the initial empty position.\n * @returns Validated exclusive record ID, or an empty string for no cursor.\n * @throws Throws PluginError 400 for invalid encoding/JSON, changed scope or invalid record keys.\n * @example\n * import { parseRecordCursor } from '@alneas/eaos-server/plugin-data'\n * const after = parseRecordCursor(['example-tenant', 'list'])\n */\nexport function parseRecordCursor(scope: unknown, cursor?: string): string {\n if (!cursor) return ''\n try { const value = JSON.parse(Buffer.from(cursor, 'base64url').toString()); if (value.scope !== atomicHash(scope) || typeof value.after !== 'string') throw new Error(); return idInput(value.after) } catch { throw new PluginError(400, 'Invalid scoped cursor') }\n}\nconst idInput = (id: string) => { if (typeof id !== 'string' || !/^[A-Za-z0-9_.:/-]{1,240}$/.test(id)) throw new PluginError(400, 'Invalid record key'); return id }\n/**\n * Canonical namespace, JSON payload policy and optional document contracts for the atomic envelope table.\n * \n *\n * Plugin-owned table; tenant cannot be selected through individual row operations.\n * @see createAtomicRepository for canonical host integration.\n */\nexport interface AtomicRepositoryOptions {\n /**\n * Optional trusted logical namespace encoded into physical IDs for a shared table.\n */\n namespace?: string;\n /**\n * Declared payload/object/history limits; does not configure or authorize a provider.\n */\n storagePolicy?: PluginStoragePolicy;\n /**\n * Canonical closed payload contracts copied and enforced by the wrapper.\n */\n documents?: readonly JsonDocumentContract[] }\n/**\n * Create tenant/namespace-scoped CAS sessions on a trusted transactional SQL driver.\n * @param table - Trusted lowercase table identifier for envelope persistence.\n * @param driver - Driver that commits the callback result or rolls back all statements on rejection.\n * @param options - Optional namespace, payload policy and canonical document contracts.\n * @returns Repository whose run callback receives a temporary session valid only until the callback settles.\n * @throws Rejects invalid table/driver/namespace/document bindings; operations reject expired sessions, invalid IDs/revisions/payloads, duplicate keys and CAS conflicts.\n * @remarks Does not create tables. Driver transaction atomicity, connection cleanup and live authorization remain host-owned. Batch writes use the same transaction; session capabilities expire in finally. list supports limits 1–101; getMany preserves input order and missing nulls.\n * @example\n * import { createAtomicRepository } from '@alneas/eaos-server/plugin-data'\n * export function repository(driver: Parameters<typeof createAtomicRepository>[1]) { return createAtomicRepository('example_records', driver) }\n */\nexport function createAtomicRepository(table: string, driver: AtomicSqlDriver, options: AtomicRepositoryOptions = {}): AtomicRepository {\n if (!/^[a-z][a-z0-9_]{0,62}$/.test(table) || !driver?.transaction) throw new Error('Trusted table and transaction driver required')\n const prefix = options.namespace ? `${options.namespace}:` : ''\n const storagePolicy = resolvePluginStoragePolicy(options.storagePolicy)\n const documents = options.documents && structuredClone(options.documents)\n if (documents?.some(d => d.table !== table || d.namespace !== options.namespace)) throw Error('JSON document storage binding differs')\n const validateDocument = documents && createRecordDocumentValidator(documents)\n if (prefix && !/^[a-z][a-z0-9_]{0,62}:$/.test(prefix)) throw new Error('Invalid plugin storage namespace')\n const physicalId = (id: string) => { if (prefix && id.length + prefix.length > 256) throw new PluginError(400, 'Record id is too long for the shared plugin table'); return `${prefix}${id}` }\n const logicalId = (id: string) => prefix ? (id.startsWith(prefix) ? id.slice(prefix.length) : null) : id\n const bind = (n: number) => driver.dialect === 'oracle' ? `:${n}` : driver.dialect === 'postgres' ? `$${n}` : '?'\n const decode = <T>(tenant: string, row: Record<string, unknown>): AtomicRow<T> => { const id = logicalId(String(row.id ?? row.ID)); if (id === null || !id) throw new Error('Record belongs to another plugin storage namespace'); const record = { id, revision: Number(row.revision ?? row.REVISION), value: JSON.parse(String(row.payload ?? row.PAYLOAD)) }; validateDocument?.(tenant, record); return record }\n return { async run(principal, work) {\n assertPrincipal(principal)\n const p = structuredClone(principal)\n return driver.transaction(p, async conn => {\n let active = true\n const check = () => { if (!active) throw new Error('Transaction session expired') }\n const session: AtomicSession = {\n async get<T>(id: string) { check(); idInput(id); const r = await conn.execute(`SELECT id,revision,payload FROM ${table} WHERE tenant_id=${bind(1)} AND id=${bind(2)}`, [p.tenantId, physicalId(id)]); return r.rows?.[0] ? decode<T>(p.tenantId, r.rows[0]) : null },\n async getMany<T>(ids: string[]) {\n check(); ids.forEach(idInput)\n const found = new Map<string, AtomicRow<T>>()\n const unique = [...new Set(ids)]\n for (let offset = 0; offset < unique.length; offset += 200) {\n const batch = unique.slice(offset, offset + 200)\n const r = await conn.execute(`SELECT id,revision,payload FROM ${table} WHERE tenant_id=${bind(1)} AND id IN (${batch.map((_,i)=>bind(i+2)).join(',')})`, [p.tenantId,...batch.map(physicalId)])\n for (const raw of r.rows ?? []) { const row = decode<T>(p.tenantId, raw); found.set(row.id,row) }\n }\n return ids.map(id=>found.get(id) ?? null)\n },\n async putMany<T>(changes: {id:string;value:T;expected:number}[]) {\n check()\n if(new Set(changes.map(c=>c.id)).size!==changes.length)throw new PluginError(400,'Duplicate batch record key')\n const prepared=changes.map(c=>{idInput(c.id);if(!Number.isSafeInteger(c.expected)||c.expected<0||c.expected>=Number.MAX_SAFE_INTEGER)throw new PluginError(400,'Invalid revision');validateDocument?.(p.tenantId,{id:c.id,revision:c.expected+1,value:c.value});return {...c,payload:storagePayload(storagePolicy,c.value)}})\n if(!conn.executeMany){const result:AtomicRow<T>[]=[];for(const c of prepared)result.push(await session.put(c.id,c.value,c.expected));return result}\n try {\n for(const inserting of [true,false]){\n const group=prepared.filter(c=>(c.expected===0)===inserting)\n const sql=inserting?`INSERT INTO ${table}(tenant_id,id,revision,payload) VALUES(${bind(1)},${bind(2)},1,${bind(3)})`:`UPDATE ${table} SET revision=${bind(1)},payload=${bind(2)} WHERE tenant_id=${bind(3)} AND id=${bind(4)} AND revision=${bind(5)}`\n for(let offset=0;offset<group.length;offset+=100){const batch=group.slice(offset,offset+100),result=await conn.executeMany(sql,batch.map(c=>inserting?[p.tenantId,physicalId(c.id),c.payload]:[c.expected+1,c.payload,p.tenantId,physicalId(c.id),c.expected]));if(result.affectedRows.length!==batch.length||result.affectedRows.some(n=>n!==1))throw new PluginError(409,'Record revision changed')}\n }\n }catch(e:any){if(['SQLITE_CONSTRAINT_PRIMARYKEY','SQLITE_CONSTRAINT_UNIQUE','23505','ORA-00001'].includes(e?.code)||e?.errorNum===1)throw new PluginError(409,'Record already exists');throw e}\n return prepared.map(c=>({id:c.id,revision:c.expected+1,value:structuredClone(c.value)}))\n },\n async list<T>(prefix: string, after = '', limit = 100) {\n check(); if (prefix !== '') idInput(prefix)\n if (after) idInput(after)\n if (!Number.isInteger(limit) || limit < 1 || limit > 101) throw new PluginError(400, 'Invalid page limit')\n const tail = driver.dialect === 'oracle' ? `FETCH FIRST ${limit} ROWS ONLY` : `LIMIT ${limit}`\n // Range bounds avoid treating '_' as a LIKE wildcard.\n const physicalPrefix = physicalId(prefix), physicalAfter = after ? physicalId(after) : `${physicalPrefix} `\n const r = await conn.execute(`SELECT id,revision,payload FROM ${table} WHERE tenant_id=${bind(1)} AND id>=${bind(2)} AND id<${bind(3)} AND id>${bind(4)} ORDER BY id ${tail}`, [p.tenantId, physicalPrefix, `${physicalPrefix}\\uffff`, physicalAfter])\n return (r.rows ?? []).map(row => decode<T>(p.tenantId, row))\n },\n async put<T>(id: string, value: T, expected: number) {\n check(); idInput(id)\n if (!Number.isSafeInteger(expected) || expected < 0 || expected >= Number.MAX_SAFE_INTEGER) throw new PluginError(400, 'Invalid revision')\n validateDocument?.(p.tenantId, {id, revision: expected + 1, value})\n const payload = storagePayload(storagePolicy, value)\n try {\n const r = expected === 0\n ? await conn.execute(`INSERT INTO ${table}(tenant_id,id,revision,payload) VALUES(${bind(1)},${bind(2)},1,${bind(3)})`, [p.tenantId, physicalId(id), payload])\n : await conn.execute(`UPDATE ${table} SET revision=${bind(1)},payload=${bind(2)} WHERE tenant_id=${bind(3)} AND id=${bind(4)} AND revision=${bind(5)}`, [expected + 1, payload, p.tenantId, physicalId(id), expected])\n if (r.affectedRows !== 1) throw new PluginError(409, 'Record revision changed')\n } catch (e: any) {\n if (['SQLITE_CONSTRAINT_PRIMARYKEY', 'SQLITE_CONSTRAINT_UNIQUE', '23505', 'ORA-00001'].includes(e?.code) || e?.errorNum === 1) throw new PluginError(409, 'Record already exists')\n throw e\n }\n return { id, revision: expected + 1, value: structuredClone(value) }\n },\n }\n joinedConnections.set(session, {connection:conn,principal:p,dialect:driver.dialect})\n try { return await work(session) } finally { active = false; joinedConnections.delete(session) }\n })\n } }\n}\n\n/**\n * Adapt one active atomic session to the standard record-store boundary for exactly one tenant.\n * @param session - Live session obtained inside repository.run.\n * @param principal - Verified principal defining the only admitted tenant.\n * @typeParam T - JSON payload shape retained by the adapted store.\n * @returns A read/list/listPage/create/replace store backed by that same session.\n * @throws Malformed principals throw immediately; foreign tenant, invalid revision transitions or expired/CAS session failures reject operations.\n * @remarks Does not begin or commit a transaction and does not expose deletion. Replacement conflicts reject rather than returning false.\n * @example\n * import { createAtomicRecordStore, type AtomicRepository, type PluginPrincipal } from '@alneas/eaos-server/plugin-data'\n * export function readRecord<T>(repository: AtomicRepository, principal: PluginPrincipal, id: string) {\n * return repository.run(principal, session => createAtomicRecordStore<T>(session, principal).read(principal.tenantId, id))\n * }\n */\nexport function createAtomicRecordStore<T>(session: AtomicSession, principal: PluginPrincipal): PluginRecordStore<T> {\n assertPrincipal(principal)\n const tenantId = principal.tenantId\n const scope = (requested: string) => { if (requested !== tenantId) throw new PluginError(403, 'Atomic record tenant differs') }\n return {\n read: async (requested, id) => { scope(requested); return session.get<T>(id) },\n list: async (requested, limit) => { scope(requested); return session.list<T>('', '', limit) },\n listPage: async (requested, limit, after = '') => { scope(requested); return session.list<T>('', after, limit) },\n create: async (requested, record) => { scope(requested); if (record.revision !== 1) throw new PluginError(400, 'Invalid initial record revision'); await session.put(record.id, record.value, 0) },\n replace: async (requested, record, expected) => { scope(requested); if (record.revision !== expected + 1) throw new PluginError(400, 'Invalid next record revision'); await session.put(record.id, record.value, expected); return true },\n }\n}\n\n/**\n * Resolve manifest storage metadata to an atomic repository with canonical document enforcement.\n * @param manifest - Trusted schema with shared-storage binding or exactly one owned table.\n * @param driver - Trusted transactional SQL driver.\n * @param catalog - Required Data Contract catalog when shared storage is declared.\n * @returns Atomic repository for the manifest-selected table/namespace.\n * @throws Rejects absent/mismatched catalogs, ambiguous owned tables or invalid repository bindings.\n * @remarks Does not install/enable storage contracts; host lifecycle and admission are separate.\n * @example\n * import { createPluginAtomicRepository } from '@alneas/eaos-server/plugin-data'\n * export function repository(manifest: Parameters<typeof createPluginAtomicRepository>[0], driver: Parameters<typeof createPluginAtomicRepository>[1], catalog: Parameters<typeof createPluginAtomicRepository>[2]) { return createPluginAtomicRepository(manifest, driver, catalog) }\n */\nexport function createPluginAtomicRepository(manifest: Pick<PluginManifest, 'schema'>, driver: AtomicSqlDriver, catalog?: DataContractCatalog): AtomicRepository {\n const storage = manifest.schema.storage\n if (storage) { if (!catalog) throw Error('Contract-backed record storage requires a trusted schema catalog'); const documents = recordDocuments(catalog, storage); return createAtomicRepository(storage.table, driver, { namespace: storage.namespace, storagePolicy: manifest.schema.storagePolicy, ...(documents?.length ? { documents } : {}) }) }\n if (manifest.schema.ownedTables.length !== 1) throw new Error('Plugin manifest must declare one storage table or shared storage metadata')\n return createAtomicRepository(manifest.schema.ownedTables[0]!, driver, { storagePolicy: manifest.schema.storagePolicy })\n}\n\n/**\n * Structural synchronous SQLite database API; lifecycle and physical migrations remain host-owned.\n * \n *\n * Structural Bun SQLite connection. The host owns the database and migration application.\n * @see createSqliteAtomicDriver for canonical host integration.\n */\nexport interface SqliteAtomicDatabase {\n /**\n * Executes trusted SQLite control SQL on the host-owned connection.\n * @param sql - Trusted transaction/control SQL text.\n * @returns The native database execution result.\n * @throws SQLite control failures throw synchronously.\n \n * @example\n * ```typescript\n * import type { SqliteAtomicDatabase } from '@alneas/eaos-server/plugin-data';\n * export function enforceForeignKeys(db: SqliteAtomicDatabase) {\n * db.exec(\"PRAGMA foreign_keys = ON\");\n * }\n * ```\n */\n exec(sql: string): unknown\n /**\n * Prepares trusted parameterized SQLite SQL on the host-owned connection.\n * @param sql - Trusted SQL text with explicit tenant predicates.\n * @returns A statement exposing synchronous all/run methods.\n * @throws Preparation errors throw synchronously.\n \n * @example\n * ```typescript\n * import type { SqliteAtomicDatabase } from '@alneas/eaos-server/plugin-data';\n * export function tenantProjection(db: SqliteAtomicDatabase, tenantId: string) {\n * return db.query(\"SELECT ? AS tenant_id\").all(tenantId);\n * }\n * ```\n */\n query(sql: string): { \n /**\n * Synchronously execute the prepared query with positional values and return all rows.\n * @param values - Positional prepared-statement values.\n * @returns All prepared-query rows in provider order.\n * @throws Provider execution/binding errors throw synchronously.\n \n * @example\n * ```typescript\n * import type { SqliteAtomicDatabase } from '@alneas/eaos-server/plugin-data';\n * export function projectedRows(db: SqliteAtomicDatabase, tenantId: string) {\n * const statement = db.query(\"SELECT ? AS tenant_id\");\n * return statement.all(tenantId);\n * }\n * ```\n */\n all(...values: any[]): unknown[]; \n /**\n * Synchronously execute the prepared DML with positional values and return its change count.\n * @param values - Positional prepared-statement values.\n * @returns Native DML change-count metadata.\n * @throws Provider execution/binding errors throw synchronously.\n \n * @example\n * ```typescript\n * import type { SqliteAtomicDatabase } from '@alneas/eaos-server/plugin-data';\n * export function executeReviewed(db: SqliteAtomicDatabase, trustedTenantDml: string, bindings: unknown[]) {\n * return db.query(trustedTenantDml).run(...bindings).changes;\n * }\n * ```\n */\n run(...values: any[]): { \n /**\n * Number of rows affected by this prepared DML execution.\n */\n changes: number } }\n}\n/**\n * Serialize BEGIN IMMEDIATE transactions on a host-owned SQLite connection.\n * @param db - Structural SQLite database whose schema and connection lifetime are owned by the host.\n * @returns SQLite transaction driver with one connection-local promise queue.\n * @throws BEGIN/statement/COMMIT/ROLLBACK errors and callback failures reject; a rollback failure can replace the original error.\n * @remarks Queueing is per driver instance, not cross-process coordination. Do not nest repository transactions on the same connection; close the database only after all operations finish.\n * @example\n * import { createSqliteAtomicDriver } from '@alneas/eaos-server/plugin-data'\n * export function driver(db: Parameters<typeof createSqliteAtomicDriver>[0]) { return createSqliteAtomicDriver(db) }\n */\nexport function createSqliteAtomicDriver(db: SqliteAtomicDatabase): AtomicSqlDriver {\n let tail: Promise<unknown> = Promise.resolve()\n return { dialect: 'sqlite', transaction<T>(_p: PluginPrincipal, work: (conn: AtomicSqlConnection) => Promise<T>) {\n const next = tail.then(async () => {\n db.exec('BEGIN IMMEDIATE')\n try {\n const result = await work({ async execute(sql, binds) { const q = db.query(sql); return /^SELECT\\b/i.test(sql) ? { rows: q.all(...binds) as Record<string, unknown>[], affectedRows: 0 } : { affectedRows: q.run(...binds).changes } } })\n db.exec('COMMIT'); return result\n } catch (e) { db.exec('ROLLBACK'); throw e }\n })\n tail = next.catch(() => undefined); return next\n } }\n}\n\n/**\n * Host Oracle connection subset used with autocommit disabled and explicit commit/rollback.\n * \n * @see createOracleAtomicDriver for canonical host integration.\n */\nexport interface OracleAtomicConnection {\n /**\n * Executes one parameterized Oracle statement without autocommit.\n * @param sql - Trusted parameterized SQL.\n * @param binds - Ordered bind values, including explicit CLOB bindings for large payloads.\n * @param options - Provider options requiring autoCommit=false and object row format, with optional per-column fetch types.\n * @returns Optional object rows and rowsAffected count.\n * @throws Rejects Oracle execution/binding failures.\n \n * @example\n * ```typescript\n * import type { OracleAtomicHost, OracleAtomicConnection } from '@alneas/eaos-server/plugin-data';\n * export async function queryTenant(host: OracleAtomicHost, tenantId: string, trustedTenantSql: string, binds: unknown[], options: Parameters<OracleAtomicConnection[\"execute\"]>[2]) {\n * return host.withTenantConnection(\"PLUGIN_RECORDS\", async connection => {\n * return (await connection.execute(trustedTenantSql, binds, options)).rows ?? [];\n * }, { tenantId });\n * }\n * ```\n */\n execute(sql: string, binds: unknown[], options: { \n /**\n * Must be false so the host transaction explicitly commits or rolls back all joined work.\n */\n autoCommit: false; \n /**\n * Actual Oracle object-row output constant supplied by the installed driver.\n */\n outFormat: number; \n /**\n * Optional column-name to explicit fetch-type settings, including PAYLOAD string extraction.\n */\n fetchInfo?: Record<string, { \n /**\n * Actual installed Oracle provider type constant; no global conversion settings are changed.\n */\n type: unknown }> }): Promise<{ \n /**\n * Optional Oracle object rows returned by a query.\n */\n rows?: Record<string, unknown>[]; \n /**\n * Optional scalar DML affected-row count; adapter normalizes absence to 0.\n */\n rowsAffected?: number }>\n /**\n * Executes ordered Oracle bind batches without autocommit.\n * @param sql - Trusted parameterized DML.\n * @param binds - Ordered positional bind rows.\n * @param options - Provider options requiring autoCommit=false and dmlRowCounts=true.\n * @returns Per-bind-row DML counts; adapters reject missing/invalid lengths or counts.\n * @throws Rejects Oracle batch/binding failures.\n \n * @example\n * ```typescript\n * import type { OracleAtomicHost } from '@alneas/eaos-server/plugin-data';\n * export async function batchReviewed(host: OracleAtomicHost, tenantId: string, trustedTenantDml: string, binds: unknown[][]) {\n * return host.withTenantConnection(\"PLUGIN_RECORDS\", async connection => {\n * if (!connection.executeMany) throw new Error(\"Batch DML not supported\");\n * try {\n * const result = await connection.executeMany(trustedTenantDml, binds, { autoCommit: false, dmlRowCounts: true });\n * await connection.commit();\n * return result.dmlRowCounts;\n * } catch (error) { await connection.rollback(); throw error; }\n * }, { tenantId });\n * }\n * ```\n */\n executeMany?(sql: string, binds: unknown[][], options: { \n /**\n * Must be false so the host transaction explicitly commits or rolls back all joined work.\n */\n autoCommit: false; \n /**\n * Requested per-row batch counts (true in options), or returned per-bind-row counts in the result.\n */\n dmlRowCounts: true }): Promise<{ \n /**\n * Requested per-row batch counts (true in options), or returned per-bind-row counts in the result.\n */\n dmlRowCounts?: number[] }>\n /**\n * Explicitly commits the current Oracle transaction.\n * @returns Resolves without a value after provider commit completes.\n * @throws Rejects provider commit failure.\n \n * @example\n * ```typescript\n * import type { OracleAtomicConnection } from '@alneas/eaos-server/plugin-data';\n * export async function commitOwned(connection: OracleAtomicConnection) {\n * // Only the owner of this transaction chooses its completion outcome.\n * await connection.commit();\n * }\n * ```\n */\n commit(): Promise<void>;\n /**\n * Explicitly rolls back the current Oracle transaction.\n * @returns Resolves without a value after provider rollback completes.\n * @throws Rejects provider rollback failure.\n \n * @example\n * ```typescript\n * import type { OracleAtomicConnection } from '@alneas/eaos-server/plugin-data';\n * export async function rollbackOwned(connection: OracleAtomicConnection) {\n * // Only the owner of this transaction chooses its completion outcome.\n * await connection.rollback();\n * }\n * ```\n */\n rollback(): Promise<void>\n}\n/**\n * Trusted tenant Oracle connection acquisition and cleanup boundary.\n * \n * @see createOracleAtomicDriver for canonical host integration.\n */\nexport interface OracleAtomicHost {\n /**\n * Acquires a verified tenant Oracle connection and cleans up its host session after work.\n * @param domain - Trusted connection domain; this adapter uses PLUGIN_RECORDS.\n * @param callback - Async work receiving the single admitted connection.\n * @param context - Verified tenant/user session context; must not come from raw request authority.\n * @typeParam T - Value resolved by the transaction/connection callback.\n * @returns The callback result after host session cleanup and connection release.\n * @throws Rejects acquisition, admission, callback or cleanup failures.\n \n * @example\n * ```typescript\n * import type { OracleAtomicHost } from '@alneas/eaos-server/plugin-data';\n * export async function inspectTenant(host: OracleAtomicHost, tenantId: string, userId: string, inspect: (connection: Parameters<Parameters<OracleAtomicHost[\"withTenantConnection\"]>[1]>[0]) => Promise<unknown>) {\n * return host.withTenantConnection(\"PLUGIN_RECORDS\", inspect, { tenantId, userId });\n * }\n * ```\n */\n withTenantConnection<T>(domain: string, callback: (connection: OracleAtomicConnection) => Promise<T>, context: { \n /**\n * Verified concrete tenant admitted by the host session boundary.\n */\n tenantId: string; \n /**\n * Optional verified actor ID attached to the Oracle session.\n */\n userId?: string }): Promise<T>\n}\n/**\n * Run atomic envelope SQL on a host-provided tenant Oracle connection with explicit commit/rollback.\n * @param host - Trusted connection provider admitting PLUGIN_RECORDS operations for the verified tenant/user.\n * @param types - Actual Oracle object-format/string/CLOB constants; no global provider settings are changed.\n * @returns Oracle transaction driver with optional batch execution and scalar fallback for large strings.\n * @throws Connection/statement/commit/rollback errors and invalid batch row counts reject; rollback failures may replace the original failure.\n * @remarks Host owns session authorization, tenant cleanup and connection release. Strings over 4000 characters use explicit CLOB bindings; no production connection is opened at construction.\n * @example\n * import { createOracleAtomicDriver } from '@alneas/eaos-server/plugin-data'\n * export function driver(host: Parameters<typeof createOracleAtomicDriver>[0], types: Parameters<typeof createOracleAtomicDriver>[1]) { return createOracleAtomicDriver(host, types) }\n */\nexport function createOracleAtomicDriver(host: OracleAtomicHost, types: { \n /**\n * Actual installed Oracle object-row output format constant.\n */\n objectFormat: number; \n /**\n * Actual Oracle string fetch type for JSON PAYLOAD extraction.\n */\n stringType: unknown; \n /**\n * Actual Oracle CLOB type used for strings longer than 4000 characters.\n */\n clobType: unknown }): AtomicSqlDriver {\n return { dialect: 'oracle', transaction: (p, work) => host.withTenantConnection('PLUGIN_RECORDS', async conn => {\n try {\n const execute: AtomicSqlConnection['execute'] = async (sql, binds) => {\n const r = await conn.execute(sql, binds.map(value => typeof value === 'string' && value.length > 4000 ? { val: value, type: types.clobType } : value), { autoCommit: false, outFormat: types.objectFormat, ...(/^SELECT\\b/i.test(sql) ? { fetchInfo: { PAYLOAD: { type: types.stringType } } } : {}) })\n return { rows: r.rows, affectedRows: r.rowsAffected ?? 0 }\n }\n const result = await work({ execute, ...(conn.executeMany ? { async executeMany(sql: string, binds: unknown[][]) {\n // Large JSON uses the established scalar CLOB bindings instead of inferred batch string types.\n if (binds.some(row => row.some(value => typeof value === 'string' && value.length > 4000))) {\n const affectedRows: number[] = []\n for (const row of binds) affectedRows.push((await execute(sql, row)).affectedRows)\n return { affectedRows }\n }\n const result = await conn.executeMany!(sql, binds, { autoCommit: false, dmlRowCounts: true })\n if (!Array.isArray(result.dmlRowCounts) || result.dmlRowCounts.length !== binds.length || result.dmlRowCounts.some(n => !Number.isSafeInteger(n) || n < 0)) throw new Error('Oracle batch did not return valid row counts')\n return { affectedRows: result.dmlRowCounts }\n } } : {}) })\n await conn.commit(); return result\n } catch (e) { await conn.rollback(); throw e }\n }, { tenantId: p.tenantId, userId: p.userId }) }\n}\n","import { randomUUID } from 'node:crypto'\nimport { OutboxDispatcher, createOutboxEvent, type OutboxDispatcherOptions, type OutboxEvent, type OutboxEventInput, type OutboxStore, type WorkflowEventEnvelope, type WorkflowEventSink } from '@alneas/eaos-core'\nimport { PluginError, type PluginPrincipal } from './index'\nimport type { AtomicRepository, AtomicSession } from './atomic'\n\nconst outboxKey = (id: string) => `outbox/${id}`\n\n/**\n * Insert or replay one immutable Outbox event inside the same transaction as its domain write.\n * @param tx - Live tenant-scoped atomic session.\n * @param input - Canonical event input with stable tenant, topic and idempotency identity.\n * @typeParam T - JSON-serializable event payload type.\n * @returns A cloned new event or the matching existing event.\n * @throws Rejects invalid event input, conflicting idempotency input or transaction failures.\n * @remarks Does not deliver externally; the host scheduler and idempotent handler process the committed event later.\n * @example\n * import { enqueueOutboxEvent } from '@alneas/eaos-server/plugin-data'\n * export function enqueue<T>(tx: Parameters<typeof enqueueOutboxEvent>[0], input: Parameters<typeof enqueueOutboxEvent<T>>[1]) { return enqueueOutboxEvent(tx, input) }\n */\nexport async function enqueueOutboxEvent<T>(tx: AtomicSession, input: OutboxEventInput<T>): Promise<OutboxEvent<T>> {\n const event = createOutboxEvent(input)\n const key = outboxKey(event.id)\n const existing = await tx.get<OutboxEvent<T>>(key)\n if (existing) {\n if (existing.value.payloadHash !== event.payloadHash || existing.value.topic !== event.topic || existing.value.idempotencyKey !== event.idempotencyKey) throw new PluginError(409, 'Outbox idempotency key reused with different input')\n return structuredClone(existing.value)\n }\n await tx.put(key, event, 0)\n return structuredClone(event)\n}\n\n/**\n * Bind workflow event append operations to the caller's current atomic transaction.\n * @param tx - Live session containing the same domain CAS operation.\n * @param topicPrefix - Trusted nonempty topic prefix; defaults to workflow and admits letters/digits/underscore/dot/colon/slash/hyphen.\n * @returns A WorkflowEventSink that enqueues copied envelopes in the existing Outbox.\n * @throws Invalid session/prefix throws at construction; appended event validation/idempotency/store failures reject.\n * @remarks The sink owns no commit boundary and performs no external transport; use it only while the parent transaction is active.\n * @example\n * import { createAtomicWorkflowEventSink, type AtomicRepository, type PluginPrincipal } from '@alneas/eaos-server/plugin-data'\n * import type { WorkflowEventEnvelope } from '@alneas/eaos-core'\n * export function appendWorkflow<T>(repository: AtomicRepository, principal: PluginPrincipal, event: WorkflowEventEnvelope<T>) {\n * return repository.run(principal, session => createAtomicWorkflowEventSink(session).append(event))\n * }\n */\nexport function createAtomicWorkflowEventSink(tx: AtomicSession, topicPrefix = 'workflow'): WorkflowEventSink {\n if (!tx || typeof tx.put !== 'function') throw new Error('Atomic transaction is required')\n if (!/^[A-Za-z0-9_.:/-]+$/.test(topicPrefix)) throw new Error('Invalid workflow event topic prefix')\n return {\n async append<TPayload>(event: WorkflowEventEnvelope<TPayload>) {\n await enqueueOutboxEvent(tx, {\n tenantId: event.tenantId,\n producer: event.producer,\n topic: `${topicPrefix}.${event.type}`,\n idempotencyKey: event.idempotencyKey,\n payload: structuredClone(event),\n id: event.eventId,\n occurredAt: event.occurredAt,\n })\n },\n }\n}\n\n/**\n * Principal, repository and stale-claim settings for durable Outbox transitions.\n * \n * @see createAtomicOutboxStore for canonical host integration.\n */\nexport interface AtomicOutboxStoreOptions {\n /**\n * Real atomic repository for durable tenant-scoped Outbox transitions.\n */\n repository: AtomicRepository\n /**\n * Verified fixed tenant/user scope copied at construction; replace the store when identity changes.\n */\n principal: PluginPrincipal\n /**\n * Claim staleness threshold in milliseconds; defaults to 300000 and must be finite and at least 1000.\n */\n staleAfterMs?: number\n /**\n * Optional dispatcher clock; createAtomicOutboxDispatcher forwards it, while standalone store.claim uses its explicit now parameter.\n \n * @returns The trusted current Date when used by createAtomicOutboxDispatcher; standalone store.claim receives an explicit Date.\n * @throws Callback failures propagate to the owning operation; transactional writes roll back when the host boundary rejects.\n */\n now?: () => Date\n}\n\n/**\n * Bind durable Outbox claim/result transitions to one verified principal and atomic repository.\n * @param options - Repository/principal plus optional staleAfterMs (default 300000, minimum 1000) and clock.\n * @returns An OutboxStore using CAS claim tokens for publication/failure transitions.\n * @throws Invalid stale timeout throws; claims reject batch sizes outside 1–100, scope mismatches, nonadvancing pages or scan capacity above 30000; result writes reject changed claim tokens.\n * @remarks Stale claims can be reclaimed, so external handlers must tolerate duplicate delivery. No global scheduler or external exactly-once guarantee is provided.\n * @example\n * import { createAtomicOutboxStore } from '@alneas/eaos-server/plugin-data'\n * export function store(options: Parameters<typeof createAtomicOutboxStore>[0]) { return createAtomicOutboxStore(options) }\n */\nexport function createAtomicOutboxStore(options: AtomicOutboxStoreOptions): OutboxStore {\n const p = structuredClone(options.principal)\n const staleAfterMs = options.staleAfterMs ?? 5 * 60_000\n if (!Number.isFinite(staleAfterMs) || staleAfterMs < 1_000) throw new Error('Invalid outbox stale timeout')\n return {\n async claim(now, limit) {\n if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) throw new Error('Invalid outbox batch size')\n return options.repository.run(p, async tx => {\n const claimed: OutboxEvent[] = []\n let after='',scanned=0\n for (;;) {\n const rows=await tx.list<OutboxEvent>('outbox/',after,100)\n for (const row of rows) {\n if (claimed.length >= limit) break\n if(++scanned>30000)throw new PluginError(409,'Outbox scan at capacity')\n if(row.value.tenantId!==p.tenantId||row.id!==outboxKey(row.value.id))throw new PluginError(409,'Outbox scope differs')\n const due = row.value.status === 'pending' && Date.parse(row.value.availableAt) <= now.getTime()\n const stale = row.value.status === 'processing' && Date.parse(row.value.claimedAt ?? '') <= now.getTime() - staleAfterMs\n if (!due && !stale) continue\n const next = { ...row.value, status: 'processing' as const, attempts: row.value.attempts + 1, claimedAt: now.toISOString(), claimToken: randomUUID(), lastError: undefined }\n claimed.push((await tx.put(row.id, next, row.revision)).value)\n }\n if(claimed.length>=limit||rows.length<100)break\n const next=rows.at(-1)!.id;if(next<=after)throw new PluginError(409,'Outbox page did not advance');after=next\n }\n return claimed\n })\n },\n async markPublished(id, claimToken, publishedAt) {\n await options.repository.run(p, async tx => {\n const row = await tx.get<OutboxEvent>(outboxKey(id))\n if (!row || row.value.status !== 'processing' || row.value.claimToken !== claimToken) throw new PluginError(409, 'Outbox claim changed')\n await tx.put(row.id, { ...row.value, status: 'published' as const, publishedAt: publishedAt.toISOString(), claimedAt: undefined, claimToken: undefined }, row.revision)\n })\n },\n async markFailed(id, claimToken, error, retryAt) {\n await options.repository.run(p, async tx => {\n const row = await tx.get<OutboxEvent>(outboxKey(id))\n if (!row || row.value.status !== 'processing' || row.value.claimToken !== claimToken) throw new PluginError(409, 'Outbox claim changed')\n await tx.put(row.id, { ...row.value, status: retryAt ? 'pending' as const : 'failed' as const, availableAt: retryAt?.toISOString() ?? row.value.availableAt, claimedAt: undefined, claimToken: undefined, lastError: error }, row.revision)\n })\n },\n }\n}\n\n/**\n * Existing dispatcher options combined with the canonical atomic tenant Outbox store.\n * \n * @see createAtomicOutboxDispatcher for canonical host integration.\n */\nexport interface AtomicOutboxDispatcherOptions extends Omit<OutboxDispatcherOptions, 'store'>, AtomicOutboxStoreOptions {}\n\n/**\n * Compose the existing OutboxDispatcher with the tenant-scoped atomic Outbox store.\n * @param options - Dispatcher handlers/time/retry settings plus the atomic repository and principal.\n * @returns An OutboxDispatcher instance; construction alone does not start a worker loop.\n * @throws Invalid store/dispatcher configuration throws; later dispatch rejects according to its host handlers and store.\n * @remarks Host scheduling and handler idempotency remain explicit; no parallel transport or global singleton is introduced.\n * @example\n * import { createAtomicOutboxDispatcher } from '@alneas/eaos-server/plugin-data'\n * export function dispatcher(options: Parameters<typeof createAtomicOutboxDispatcher>[0]) { return createAtomicOutboxDispatcher(options) }\n */\nexport function createAtomicOutboxDispatcher(options: AtomicOutboxDispatcherOptions): OutboxDispatcher {\n const { repository, principal, staleAfterMs, now, ...dispatcher } = options\n return new OutboxDispatcher({ ...dispatcher, now, store: createAtomicOutboxStore({ repository, principal, staleAfterMs, now }) })\n}\n\n/**\n * Reset one failed tenant event to pending while retaining its immutable identity.\n * @param tx - Live session entered after explicit host recovery authorization.\n * @param tenantId - Verified tenant identity required to match the stored event.\n * @param id - Existing failed event ID, nonempty and at most 256 characters.\n * @param availableAt - Parseable retry timestamp; defaults to the current ISO time.\n * @returns The requeued event with claim/error fields cleared.\n * @throws Rejects invalid identifiers/timestamps, missing/nonfailed/foreign events or CAS failures.\n * @remarks Does not perform delivery or authorize recovery. A prior uncertain external effect may already exist; handlers must deduplicate by the retained identity.\n * @example\n * import { requeueOutboxEvent } from '@alneas/eaos-server/plugin-data'\n * export function requeue(tx: Parameters<typeof requeueOutboxEvent>[0], tenantId: string, id: string) { return requeueOutboxEvent(tx, tenantId, id) }\n */\nexport async function requeueOutboxEvent(tx:AtomicSession,tenantId:string,id:string,availableAt=new Date().toISOString()):Promise<OutboxEvent>{\n if(!id||id.length>256||!Number.isFinite(Date.parse(availableAt)))throw new PluginError(400,'Invalid outbox recovery')\n const row=await tx.get<OutboxEvent>(outboxKey(id));if(!row||row.value.tenantId!==tenantId||row.value.id!==id||row.value.status!=='failed')throw new PluginError(409,'Failed outbox event unavailable')\n const next={...row.value,status:'pending' as const,availableAt,claimedAt:undefined,claimToken:undefined,lastError:undefined}\n await tx.put(row.id,next,row.revision);return next\n}\n","import {appendAtomicAudit} from './audit'\nimport Ajv from 'ajv'\nimport { assertPrincipal, exactKeys, PluginError, parseRecordCursor, recordCursor, revisionInput, textInput, type PluginPrincipal, type PluginRecordStore } from './index'\nimport { createAtomicRecordStore, atomicHash, atomicCommand, type AtomicSession, type AtomicRepository } from './atomic'\n\n/**\n * Host record storage and live resource authorization, optionally joined to a shared atomic repository.\n * @typeParam T - Tenant-owned stored record payload.\n * \n * @see ScopedRecordService for canonical host integration.\n */\nexport interface ScopedRecordHost<T> {\n /**\n * Host record store with real tenant scoping and revision-predicated writes.\n */\n store: PluginRecordStore<T>\n /**\n * Checks current plugin activation and resource permission before exposing or persisting records.\n * @param principal - Verified current principal.\n * @param operation - Declared operation name.\n * @param input - Operation input, list criteria or created payload appropriate to the check.\n * @param current - Optional copied current record; absence requires operation-level admission.\n * @returns Exactly true to admit the operation/record; false denies or filters the record during lists.\n * @throws Rejects propagated host persistence, validation or callback failures.\n \n * @example\n * ```typescript\n * import type { ScopedRecordHost, PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export async function admitted(host: ScopedRecordHost<{ title: string }>, principal: PluginPrincipal, operation: string, input: unknown, current?: unknown) {\n * return await host.authorize(principal, operation, input, current) === true;\n * }\n * ```\n */\n authorize(principal: PluginPrincipal, operation: string, input: unknown, current?: unknown): Promise<boolean>\n /**\n * Optional trusted operation clock; defaults to new Date().\n \n * @returns A valid Date used for the current CRUD/domain operation timestamp.\n * @throws Callback failures propagate to the owning operation; transactional writes roll back when the host boundary rejects.\n */\n now?: () => Date\n /**\n * Optional existing atomic repository joining ordinary CRUD, workflow commands, reservations and audit in one commit boundary.\n * \n * Ordinary CRUD and workflow commands share the provided transaction boundary.\n */\n repository?: AtomicRepository\n}\n\n/**\n * Plugin-owned schemas, CRUD reducers, filtering and transactional identity/composition rules.\n * @typeParam T - Stored record payload with stable tenantId/id.\n * @typeParam S - Decoded record view extending T with a positive CAS revision.\n * \n * @see ScopedRecordService for canonical host integration.\n */\nexport interface ScopedRecordDefinition<T extends { tenantId: string; id: string }, S extends T & { revision: number }> {\n /**\n * Explicit per-operation JSON Schemas compiled with coercion disabled.\n */\n schemas: Record<string, object>\n /**\n * Exact list/get/create/update/archive operation names used for shared dispatch.\n */\n operations: { \n /**\n * Host operation name for bounded or keyset-paged authorized record listing.\n */\n list: string; \n /**\n * Host operation name for reading one authorized record.\n */\n get: string; \n /**\n * Host operation name for creating one tenant record.\n */\n create: string; \n /**\n * Host operation name for revision-predicated record patching.\n */\n update: string; \n /**\n * Host operation name for the plugin-owned retained-data archive transition.\n */\n archive: string }\n /**\n * Response property under which admitted records are returned.\n */\n listKey: string\n /**\n * Trusted domain label used in validation/conflict errors.\n */\n label: string\n /**\n * Enable filtered keyset scanning when the host store supplies listPage; otherwise a supplied cursor is rejected.\n * \n * Enable complete filtered paging when the store supplies listPage.\n */\n pagination?: boolean\n /**\n * Additional auxiliary record prefixes omitted from business CRUD results.\n * \n * Plugin-owned auxiliary keys must not appear as business records.\n */\n excludedIdPrefixes?: readonly string[]\n /**\n * Optional composite identity reservation rules; require a shared transaction for concurrent enforcement.\n * \n * Transactional reservations enforce composite business identities across concurrent writers.\n */\n unique?: readonly { \n /**\n * Trusted uniqueness constraint label matching lowercase letter followed by up to 60 lowercase letters/digits/underscore/hyphen characters.\n */\n name: string; \n /**\n * Nonempty ordered stored field keys; every active value must be a nonblank string.\n */\n fields: readonly (keyof T & string)[];\n /** Trusted domain predicate; false releases this record's reservation. \n * @param record - Cloned current record; this predicate must be pure.\n * @returns True to reserve the composite identity, false to release it; nonboolean results reject.\n * @throws Callback failures propagate to the owning operation; transactional writes roll back when the host boundary rejects.\n */ when?: (record:T)=>boolean }[]\n /**\n * Fields searched by the generic case-insensitive query filter.\n */\n searchableFields?: readonly (keyof S & string)[]\n /**\n * Optional synchronous domain filter applied in addition to standard criteria and live record authorization.\n \n * @param input - Schema-admitted list criteria.\n * @param value - Decoded scoped record being considered.\n * @returns True to retain this candidate before the additional search/live-record permission checks.\n * @throws Callback failures propagate to the owning operation; transactional writes roll back when the host boundary rejects.\n */\n filter?: (input: Record<string, any>, value: S) => boolean\n /**\n * Creates a new tenant-owned domain payload from admitted inputs.\n * @param input - Schema-validated create input.\n * @param principal - Verified current tenant principal.\n * @param at - Trusted UTC ISO operation timestamp.\n * @returns The new payload with stable id and matching tenantId; no persistence is performed by this reducer.\n * @throws Reducer errors propagate; do not perform irreversible external effects.\n \n * @example\n * ```typescript\n * import type { ScopedRecordDefinition, PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * type Stored = { tenantId: string; id: string; archived: boolean };\n * type View = Stored & { revision: number };\n * export function reduceCreate(definition: ScopedRecordDefinition<Stored, View>, principal: PluginPrincipal, admittedInput: Record<string, unknown>) {\n * return definition.create(admittedInput, principal, new Date().toISOString());\n * }\n * ```\n */\n create(input: Record<string, any>, principal: PluginPrincipal, at: string): T\n /**\n * Mutates only the private record snapshot with the admitted patch.\n * @param value - Mutable current decoded revisioned record; preserve tenantId/id.\n * @param patch - Schema-admitted patch fields.\n * @param at - Trusted UTC ISO operation timestamp.\n * @returns Completes without a value; the owning service performs CAS persistence.\n * @throws Reducer errors propagate and roll back joined transactional work.\n \n * @example\n * ```typescript\n * import type { ScopedRecordDefinition } from '@alneas/eaos-server/plugin-data';\n * type Stored = { tenantId: string; id: string; archived: boolean };\n * type View = Stored & { revision: number };\n * export function reduceUpdate(definition: ScopedRecordDefinition<Stored, View>, snapshot: View, admittedPatch: Record<string, unknown>) {\n * const next = structuredClone(snapshot);\n * definition.update(next, admittedPatch, new Date().toISOString());\n * return next; // The owning service still performs revision-checked persistence.\n * }\n * ```\n */\n update(value: S, patch: Record<string, unknown>, at: string): void\n /**\n * Mutates the private record snapshot to the plugin's archive state.\n * @param value - Mutable current record; preserve stable tenantId/id.\n * @param at - Trusted UTC ISO operation timestamp.\n * @param input - Optional schema-admitted archive command input.\n * @param principal - Optional verified current principal supplied by the service.\n * @returns Completes without a value; archive retains data according to the plugin reducer.\n * @throws Reducer errors propagate; do not perform irreversible external effects.\n \n * @example\n * ```typescript\n * import type { ScopedRecordDefinition, PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * type Stored = { tenantId: string; id: string; archived: boolean };\n * type View = Stored & { revision: number };\n * export function reduceArchive(definition: ScopedRecordDefinition<Stored, View>, snapshot: View, principal: PluginPrincipal, admittedInput: Record<string, unknown>) {\n * const next = structuredClone(snapshot);\n * definition.archive(next, new Date().toISOString(), admittedInput, principal);\n * return next; // No persistence is performed by this reducer call.\n * }\n * ```\n */\n archive(value: S, at: string, input?: Record<string, any>, principal?: PluginPrincipal): void\n /**\n * Additional plugin-owned mutation reducers persisted through the same CAS path; never perform irreversible external effects here.\n * \n * Plugin-owned durable workflow commands. Each command is validated by its\n * declared schema, receives the current revision, and is persisted through\n * the same tenant-scoped CAS path as update/archive.\n \n * @param value - Private mutable revisioned record; preserve stable tenant/id.\n * @param input - Schema-admitted custom command input.\n * @param at - Trusted ISO operation timestamp.\n * @param principal - Verified current principal.\n * @returns Completes without a value after mutating the private snapshot; the owning service performs CAS persistence.\n * @throws Callback failures propagate to the owning operation; transactional writes roll back when the host boundary rejects.\n */\n custom?: Record<string, (value: S, input: Record<string, any>, at: string, principal: PluginPrincipal) => void>\n /**\n * Optional async owning-domain composition inside the shared transaction before final authorization; not an external side-effect hook.\n * \n * Owning domain composition inside the existing transaction, before final live authorization. Never use for external effects.\n \n * @param principal - Verified current principal.\n * @param operation - Declared mutation operation.\n * @param input - Schema-admitted command input.\n * @param current - Cloned resulting decoded record; do not mutate service state through this copy.\n * @param previous - Optional prior decoded record, absent on create.\n * @returns Resolves without a value after owning-domain composition inside the same transaction; no external effects.\n * @throws Callback failures propagate to the owning operation; transactional writes roll back when the host boundary rejects.\n */\n afterWrite?: (principal: PluginPrincipal, operation: string, input: Record<string, any>, current: S, previous?: S) => Promise<void>\n}\n\n/**\n * Derive a stable atomic reservation key for a named composite business identity.\n * @param name - Trusted lowercase uniqueness label of at most 61 characters.\n * @param values - Nonempty tuple of nonblank string values in canonical field order.\n * @returns unique/ followed by a canonical content hash.\n * @throws Invalid declarations throw Error; nonstring/blank identity values throw PluginError 409.\n * @remarks Derivation alone reserves nothing; concurrent uniqueness requires CAS reservations in the enclosing atomic transaction.\n * @example\n * import { uniqueRecordKey } from '@alneas/eaos-server/plugin-data'\n * const key = uniqueRecordKey('external-id', ['example'])\n */\nexport function uniqueRecordKey(name:string,values:readonly unknown[]):string {\n if(!/^[a-z][a-z0-9_-]{0,60}$/.test(name)||!values.length)throw new Error('Invalid trusted uniqueness declaration')\n if(values.some(value=>typeof value!=='string'||!value.trim()))throw new PluginError(409,'Unique identity fields must be nonempty strings')\n return `unique/${atomicHash([name,values])}`\n}\n\n/**\n * Applies schema-validated record CRUD and workflow commands through tenant checks, live admission and optimistic revisions.\n * \n * Shared tenant-scoped CRUD/CAS boundary for small plugin-owned master records.\n * @typeParam T - Stored tenant-owned record payload containing stable tenantId and id.\n * @typeParam S - Decoded public record view extending T with a positive CAS revision.\n * \n * @remarks\n * Use a real atomic repository for unique identity reservations, owning-domain composition and command/audit receipts. Repository execution joins CRUD/domain writes and final authorization in one transaction; plain stores do not gain those guarantees. Domain reducers must not perform irreversible external effects. Auxiliary audit/command/event/unique keys are excluded from business results as configured.\n * \n * @example\n * ```typescript\n * import { ScopedRecordService, type ScopedRecordHost, type ScopedRecordDefinition } from '@alneas/eaos-server/plugin-data';\n * type Row = { tenantId: string; id: string; title: string };\n * type RevisionedRow = Row & { revision: number };\n * export function connectRecords(host: ScopedRecordHost<Row>, definition: ScopedRecordDefinition<Row, RevisionedRow>) { return new ScopedRecordService(host, definition); }\n * ```\n */\nexport class ScopedRecordService<T extends { tenantId: string; id: string }, S extends T & { revision: number }> {\n private readonly validators: Map<string, (value: unknown) => boolean>\n /**\n * Compiles strict noncoercing command schemas for one trusted record definition.\n * @param host - Durable tenant-scoped store, live authorization, optional clock and shared atomic repository.\n * @param definition - Plugin-owned operation names, schemas, reducers, paging and identity rules.\n * @param atomicSession - Optional already active internal session used for joined composition/uniqueness; its lifetime must not exceed the enclosing repository callback.\n * @throws Throws when durable store or live authorization is missing, or strict schema compilation fails.\n * \n * @example\n * ```typescript\n * import { ScopedRecordService, type ScopedRecordHost, type ScopedRecordDefinition } from '@alneas/eaos-server/plugin-data';\n * type Row = { tenantId: string; id: string; title: string };\n * type RevisionedRow = Row & { revision: number };\n * export function connectRecords(host: ScopedRecordHost<Row>, definition: ScopedRecordDefinition<Row, RevisionedRow>) { return new ScopedRecordService(host, definition); }\n * ```\n */\n constructor(private readonly host: ScopedRecordHost<T>, private readonly definition: ScopedRecordDefinition<T, S>, private readonly atomicSession?: AtomicSession) {\n if (!host?.store || typeof host.authorize !== 'function') throw new Error('Durable scoped record store and live authorization required')\n const ajv = new Ajv({ strict: true, coerceTypes: false })\n this.validators = new Map(Object.entries(definition.schemas).map(([name, schema]) => [name, ajv.compile(schema)]))\n }\n private async allow(principal: PluginPrincipal, operation: string, input: unknown, current?: S) {\n assertPrincipal(principal)\n if (await this.host.authorize(structuredClone(principal), operation, structuredClone(input), current && structuredClone(current)) !== true) throw new PluginError(403, `${this.definition.label} access denied`)\n }\n /**\n * Exposes the same live tenant/permission check to a plugin's read-only\n * domain previews. Preview operations do not persist records, but they must\n * still be authorized through the host before invoking domain logic.\n */\n protected async authorizeOperation(principal: PluginPrincipal, operation: string, input: unknown, current?: S) {\n await this.allow(principal, operation, input, current)\n }\n protected currentTime(): Date { return this.host.now?.() ?? new Date() }\n private excluded(id: string): boolean { return id.startsWith('audit/') || (!!this.definition.unique?.length && id.startsWith('unique/')) || (Object.values(this.definition.schemas).some(schema => (schema as any)?.properties?.commandId) && /^(?:command|event)\\//.test(id)) || this.definition.excludedIdPrefixes?.some(prefix=>id.startsWith(prefix)) === true }\n private decode(principal: PluginPrincipal, record: { id: string; revision: number; value: T }): S {\n if (record.id !== record.value.id || record.value.tenantId !== principal.tenantId || !Number.isSafeInteger(record.revision) || record.revision < 1) throw new Error(`Invalid scoped ${this.definition.label} record`)\n return { ...structuredClone(record.value), revision: record.revision } as S\n }\n private async load(principal: PluginPrincipal, id: string): Promise<S> {\n if (this.excluded(id)) throw new PluginError(404,`${this.definition.label} not found`)\n const record = await this.host.store.read(principal.tenantId, id)\n if (!record) throw new PluginError(404, `${this.definition.label} not found`)\n return this.decode(principal, record)\n }\n private matches(args: Record<string,any>, value: S): boolean {\n return (!this.definition.filter || this.definition.filter(args,value)) && (!args.search || this.definition.searchableFields?.some(key=>typeof value[key]==='string' && String(value[key]).toLocaleLowerCase().includes(args.search.toLocaleLowerCase()))) === true\n }\n /** Read all authorized records for plugin-owned reports; providers must support keyset paging. */\n protected async readAllAuthorized(principal: PluginPrincipal, operation: string, input: unknown, accept: (value: S)=>boolean): Promise<S[]> {\n if (this.host.repository) return this.host.repository.run(principal, tx => this.readAllFromStore(principal, operation, input, accept, createAtomicRecordStore(tx, principal)))\n return this.readAllFromStore(principal, operation, input, accept, this.host.store)\n }\n private async readAllFromStore(principal: PluginPrincipal, operation: string, input: unknown, accept: (value: S)=>boolean, store: PluginRecordStore<T>): Promise<S[]> {\n await this.allow(principal,operation,input)\n if (!store.listPage) throw new PluginError(409,'Paged record storage required for complete reports')\n const values:S[]=[];let after=''\n for (;;) { const rows=await store.listPage(principal.tenantId,100,after);for(const raw of rows){if(this.excluded(raw.id))continue;const value=this.decode(principal,raw);if(accept(value) && await this.host.authorize(structuredClone(principal),operation,structuredClone(input),structuredClone(value))===true)values.push(value)}if(rows.length<100)break;const next=rows.at(-1)!.id;if(next<=after)throw new Error('Record page did not advance');after=next }\n await this.allow(principal,operation,input);return values\n }\n private async reserveUnique(value: T, previous?: T) {\n if (!this.definition.unique?.length) return\n const tx = this.atomicSession\n if (!tx) throw new PluginError(409, 'Transactional storage required for unique business identities')\n for (const constraint of this.definition.unique) {\n if(!constraint.fields.length)throw new Error('Invalid trusted uniqueness declaration')\n const key=(record:T)=>uniqueRecordKey(constraint.name,constraint.fields.map(field=>record[field]))\n const applies=(record:T)=>{const active=constraint.when?constraint.when(structuredClone(record)):true;if(typeof active!=='boolean')throw new Error('Unique predicate must return a boolean');return active}\n const nextActive=applies(value),oldActive=previous?applies(previous):false,nextKey=nextActive?key(value):null,oldKey=previous&&oldActive?key(previous):null\n if(nextKey){\n const reservation=await tx.get<{recordId:string|null}>(nextKey)\n if(reservation&&reservation.value.recordId!==null&&reservation.value.recordId!==value.id)throw new PluginError(409,`${this.definition.label} identity already exists`)\n if(!reservation||reservation.value.recordId===null)await tx.put(nextKey,{recordId:value.id},reservation?.revision??0)\n }\n if(oldKey&&oldKey!==nextKey){\n const old=await tx.get<{recordId:string|null}>(oldKey)\n if(!old||old.value.recordId!==value.id)throw new PluginError(409,'Unique identity reservation conflicts')\n await tx.put(oldKey,{recordId:null},old.revision)\n }\n }\n }\n\n /**\n * Dispatches one admitted record operation and optionally joins it to durable command/audit receipt handling.\n * @param principal - Verified current tenant/user principal; host authorization is rechecked throughout the operation.\n * @param operation - Declared list/get/create/update/archive or plugin custom reducer key.\n * @param input - Operation-schema input; mutations require matching record revision and optional durable commandId when declared.\n * @returns List operations return the configured listKey with scoped records and paging metadata; get/mutations return a decoded revisioned record. Paged results may be incomplete and carry nextCursor/mayHaveMore.\n * @throws Rejects invalid principal (401), denied/revoked admission (403), schema/operation errors (400), missing/excluded record (404), stale revision/uniqueness/CAS conflict or missing required transactional capability (409), foreign/corrupt records, and propagated domain/store/clock/callback failures.\n * \n * @remarks\n * Pagination scans at most 10000 rows per request, selecting authorized/filter-matching records. Without paging, filtering applies only to the bounded store result. Repository writes with declared commandId replay the stored identical result; other repository writes append audit. Recheck live resource permission before replay, and reload uncertain plain-store outcomes rather than retrying blindly.\n * \n * @example\n * ```typescript\n * import { ScopedRecordService, type PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export function dispatch<T extends {tenantId: string; id: string}, S extends T & {revision: number}>(service: ScopedRecordService<T, S>, principal: PluginPrincipal, operation: string, input: unknown) { return service.execute(principal, operation, input); }\n * ```\n */\n async execute(principal: PluginPrincipal, operation: string, input: unknown): Promise<unknown> {\n if (this.host.repository) {\n await this.allow(principal, operation, input)\n const p = structuredClone(principal)\n return this.host.repository.run(p, async tx => {\n const service = new ScopedRecordService<T, S>({ ...this.host, repository: undefined, store: createAtomicRecordStore<T>(tx, p) }, this.definition, tx)\n const write = operation !== this.definition.operations.list && operation !== this.definition.operations.get\n const journaled = write && (this.definition.schemas[operation] as any)?.properties?.commandId && typeof (input as any)?.commandId === 'string'\n const perform = () => service.execute(p, operation, input)\n if (journaled && !this.validators.get(operation)?.(input)) throw new PluginError(400, `Invalid ${this.definition.label} command`)\n const result = journaled ? await atomicCommand(tx, p, operation, input as { commandId: string }, perform) : await perform()\n if(write&&!journaled)await appendAtomicAudit(tx,p,operation,input,result)\n const resource = operation === this.definition.operations.list ? undefined : await service.load(p, (result as S).id)\n await this.allow(p, operation, input, resource)\n return result\n })\n }\n await this.allow(principal, operation, input)\n const validate = this.validators.get(operation)\n if (!validate || !validate(input)) throw new PluginError(400, `Invalid ${this.definition.label} command`)\n if (!this.atomicSession && operation !== this.definition.operations.list && operation !== this.definition.operations.get && (this.definition.schemas[operation] as any)?.properties?.commandId && typeof (input as any)?.commandId === 'string') throw new PluginError(409, 'Transactional storage required for durable command receipts')\n const args = input as Record<string, any>, at = (this.host.now?.() ?? new Date()).toISOString(), ops = this.definition.operations\n if (this.definition.afterWrite && !this.atomicSession && operation !== ops.list && operation !== ops.get) throw new PluginError(409, 'Transactional storage required for owning record composition')\n if (operation === ops.list) {\n const limit = args.limit ?? 50, values:S[]=[]\n if (this.definition.pagination && this.host.store.listPage) {\n const {cursor,...criteria}=args,scope=[principal.tenantId,principal.userId,operation,criteria];let position=parseRecordCursor(scope,cursor),finished=false,scannedCount=0\n while(values.length<limit && scannedCount<10000){const rows=await this.host.store.listPage(principal.tenantId,100,position);if(!rows.length){finished=true;break}for(const raw of rows){position=raw.id;scannedCount++;if(this.excluded(raw.id))continue;const value=this.decode(principal,raw);if(this.matches(args,value) && await this.host.authorize(structuredClone(principal),operation,{...criteria,id:value.id},structuredClone(value))===true)values.push(value);if(values.length===limit)break}if(values.length<limit&&rows.length<100){finished=true;break}}\n await this.allow(principal,operation,input)\n return { [this.definition.listKey]:values,scannedLimit:limit,scannedCount,mayHaveMore:!finished,nextCursor:finished?null:recordCursor(scope,position) }\n }\n if (args.cursor) throw new PluginError(409,'Paged record storage unavailable')\n const records=await this.host.store.list(principal.tenantId,limit)\n for(const raw of records){if(this.excluded(raw.id))continue;const value=this.decode(principal,raw);if(this.matches(args,value) && await this.host.authorize(structuredClone(principal),operation,{id:value.id},structuredClone(value))===true)values.push(value)}\n await this.allow(principal,operation,input)\n return { [this.definition.listKey]:values,scannedLimit:limit,mayHaveMore:records.length===limit }\n\n }\n if (operation === ops.create) {\n const value = this.definition.create(args, principal, at)\n if (value.tenantId !== principal.tenantId || !value.id || this.excluded(value.id)) throw new Error(`Invalid ${this.definition.label} scope`)\n await this.allow(principal, operation, value)\n await this.reserveUnique(value)\n await this.host.store.create(principal.tenantId, { id: value.id, revision: 1, value })\n const created = { ...value, revision: 1 } as S\n if (this.definition.afterWrite) {\n await this.definition.afterWrite(structuredClone(principal), operation, structuredClone(args), structuredClone(created))\n await this.allow(principal, operation, input, created)\n }\n return created\n }\n const current = await this.load(principal, textInput(args.id, 'id', 128)); await this.allow(principal, operation, input, current)\n if (operation === ops.get) return current\n const previous = structuredClone(current)\n const expected = revisionInput(args.revision)\n if (expected !== current.revision) throw new PluginError(409, `${this.definition.label} changed`)\n if (operation === ops.archive) {\n this.definition.archive(current, at, args, principal)\n } else if (operation === ops.update) {\n const patch = args.patch as Record<string, unknown>\n const patchSchema = (this.definition.schemas[ops.update] as any)?.properties?.patch?.properties\n if (patchSchema) exactKeys(patch, Object.keys(patchSchema))\n this.definition.update(current, patch, at)\n } else if (this.definition.custom?.[operation]) {\n this.definition.custom[operation](current, args, at, principal)\n } else {\n throw new PluginError(400, `Unknown ${this.definition.label} operation`)\n }\n await this.allow(principal, operation, input, current)\n await this.reserveUnique(current, previous)\n const nextRevision = expected + 1\n const {revision:_revision,...payload}=current\n if (!await this.host.store.replace(principal.tenantId, { id: current.id, revision: nextRevision, value: payload as unknown as T }, expected)) throw new PluginError(409, `${this.definition.label} changed`)\n current.revision = nextRevision\n if (this.definition.afterWrite) {\n await this.definition.afterWrite(structuredClone(principal), operation, structuredClone(args), structuredClone(current), previous)\n await this.allow(principal, operation, input, current)\n }\n return current\n }\n}\n","import { PluginError, type PluginPrincipal } from './index'\n\n/**\n * Minimal verified-principal operation dispatch contract shared by bounded composite services.\n * \n * @see createCompositePluginService for canonical host integration.\n */\nexport interface PluginOperationService {\n /**\n * Executes one service-owned operation using host-verified identity and operation input.\n * @param principal - Verified current tenant principal.\n * @param operation - Declared service operation name.\n * @param input - Operation input whose schema/permission must be checked by the owning service.\n * @returns The owner's operation result; no composite layer adds authentication or transactions.\n * @throws Rejects owning-service schema, authorization, persistence or domain failures.\n \n * @example\n * ```typescript\n * import type { PluginOperationService, PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export async function executeAdmitted(service: PluginOperationService, principal: PluginPrincipal, operation: string, input: unknown) {\n * // The owning service validates input and live resource permission.\n * return service.execute(principal, operation, input);\n * }\n * ```\n */\n execute(principal: PluginPrincipal, operation: string, input: unknown): Promise<unknown>\n}\n\n/**\n * Route explicitly owned operations to their bounded service instances.\n * @param services - Trusted service instances keyed by owner name.\n * @param operationOwners - Explicit operation-to-owner mapping copied at construction.\n * @returns A principal-aware execute service forwarding to the declared owner.\n * @throws Unknown declared owners throw at construction; unknown operations reject with PluginError 400 and owner errors propagate.\n * @remarks Does not authenticate principals or add authorization/transactions; each owner service retains its actual boundaries.\n * @example\n * import { createCompositePluginService } from '@alneas/eaos-server/plugin-data'\n * export function composite(services: Parameters<typeof createCompositePluginService>[0]) { return createCompositePluginService(services, { list: 'records' }) }\n */\nexport function createCompositePluginService(\n services: Readonly<Record<string, PluginOperationService>>,\n operationOwners: Readonly<Record<string, string>>,\n): PluginOperationService {\n const owned = new Map(Object.entries(operationOwners))\n for (const [operation, owner] of owned) {\n if (!services[owner]) throw new Error(`Unknown composite service: ${owner} (${operation})`)\n }\n return {\n async execute(principal, operation, input) {\n const owner = owned.get(operation)\n if (!owner) throw new PluginError(400, 'Unknown bundled plugin operation')\n return services[owner]!.execute(principal, operation, input)\n },\n }\n}\n","import { atomicHash, parseRecordCursor, recordCursor, type AtomicSession } from './atomic'\nimport { PluginError, type PluginPrincipal } from './index'\n\n/**\n * Pinned owning-document scope hash and admitted anchor/check IDs; authorization is supplied by its owner.\n * \n *\n * The owning plugin authorizes and pins the document before entering this transaction.\n * @see documentAnnotations for canonical host integration.\n */\nexport interface AnnotationTarget {\n /**\n * Trusted 64-character document-scope hash pinned by the owning plugin.\n */\n scope: string;\n /**\n * Exact anchor IDs valid for newly created reader comments.\n */\n anchorIds: readonly string[];\n /**\n * Exact reading-check IDs admitted for this pinned document.\n */\n checkIds: readonly string[] }\n/**\n * Document-scoped reader comment with author-controlled resolution and private/shared visibility.\n * \n * @see documentAnnotations for canonical host integration.\n */\nexport interface ReaderComment {\n /**\n * Generated comment UUID; physical storage also prefixes the pinned document and visibility scope.\n */\n id: string;\n /**\n * Pinned valid document anchor, or null for a document-wide comment.\n */\n anchorId: string | null;\n /**\n * Nonblank trimmed comment text; outer schema limits input to 4000 characters.\n */\n body: string;\n /**\n * private scopes rows to the actor hash; shared scopes them to the authorized document audience.\n */\n visibility: 'private' | 'shared';\n /**\n * Authenticated creator; only this actor may change resolution.\n */\n authorId: string;\n /**\n * Trusted ISO timestamp supplied by the owning command.\n */\n createdAt: string;\n /**\n * Author-controlled resolution flag, updated using the stored CAS revision.\n */\n resolved: boolean }\n/**\n * Supported reader annotation operation names; this list itself grants no document access.\n * \n * @see documentAnnotations for canonical usage.\n */\nexport const annotationOperations = ['get_annotations', 'set_check', 'add_comment', 'resolve_comment'] as const\n/**\n * Compose closed annotation operation schemas from the owning document's trusted target fields.\n * @param target - Trusted JSON Schema property map for the owning document identity; those keys are required on every operation.\n * @returns Schemas for get_annotations, set_check, add_comment and resolve_comment.\n * @remarks Schema generation does not authorize or execute annotations; the owner validates input and pins the exact document before transaction work.\n * @example\n * import { annotationSchemas } from '@alneas/eaos-server/plugin-data'\n * const schemas = annotationSchemas({ documentId: { type: 'string', minLength: 1 } })\n */\nexport function annotationSchemas(target: Record<string, unknown>) {\n const id = { type: 'string', pattern: '^[a-zA-Z0-9_-]{1,80}$' }, revision = { type: 'integer', minimum: 0, maximum: 9007199254740990 }\n const visibility = { enum: ['private', 'shared'] }, anchorId = { anyOf: [{ type: 'string', minLength: 1, maxLength: 1000 }, { type: 'null' }] }\n const schema = (properties: Record<string, unknown>, required: string[]) => ({ type: 'object', additionalProperties: false, required: [...Object.keys(target), ...required], properties: { ...target, ...properties } })\n return {\n get_annotations: schema({ visibility, cursor: { type: 'string', maxLength: 1000 } }, ['visibility']),\n set_check: schema({ commandId: id, revision, itemId: { type: 'string', minLength: 1, maxLength: 1000 }, checked: { type: 'boolean' } }, ['commandId', 'revision', 'itemId', 'checked']),\n add_comment: schema({ commandId: id, visibility, anchorId, body: { type: 'string', minLength: 1, maxLength: 4000 } }, ['commandId', 'visibility', 'anchorId', 'body']),\n resolve_comment: schema({ commandId: id, revision, visibility, commentId: id, resolved: { type: 'boolean' } }, ['commandId', 'revision', 'visibility', 'commentId', 'resolved']),\n }\n}\n/**\n * Read or mutate document checks/comments within an already authorized atomic document command.\n * @param tx - Live tenant-scoped atomic session inside the owner's atomicCommand.\n * @param p - Verified document reader principal.\n * @param target - Pinned document scope hash and its admitted anchor/check IDs.\n * @param operation - One of annotationOperations.\n * @param a - Input already validated against the selected annotation schema.\n * @param now - Trusted ISO timestamp used for newly created comments.\n * @returns Operation-specific checks, comment or page data with CAS revisions and optional scoped cursor.\n * @throws Rejects invalid scope/cursors, unknown checks/anchors/operations, comment ownership violations, missing comments, capacity or CAS conflicts.\n * @remarks Does not enforce the outer schema or own authorization/transaction/table creation. The owner must authorize the exact document and wrap write operations in atomicCommand; private/shared visibility is scoped by user and document hash.\n * @example\n * import { documentAnnotations } from '@alneas/eaos-server/plugin-data'\n * export function readComments(tx: Parameters<typeof documentAnnotations>[0], p: Parameters<typeof documentAnnotations>[1], target: Parameters<typeof documentAnnotations>[2], now: string) { return documentAnnotations(tx, p, target, 'get_annotations', { visibility: 'private' }, now) }\n */\nexport async function documentAnnotations(tx: AtomicSession, p: PluginPrincipal, target: AnnotationTarget, operation: string, a: Record<string, any>, now: string) {\n if (!/^[a-f0-9]{64}$/.test(target.scope)) throw new Error('Trusted annotation scope required')\n const owner = atomicHash(p.userId), checksKey = `checks/${target.scope}/${owner}`\n const prefix = `comments/${target.scope}/${a.visibility === 'shared' ? 'shared' : owner}/`\n const visible = (row: { revision: number; value: ReaderComment }) => ({ ...row.value, revision: row.revision, canResolve: row.value.authorId === p.userId })\n if (operation === 'get_annotations') {\n const scope = [p.tenantId, p.userId, target.scope, a.visibility], after = parseRecordCursor(scope, a.cursor)\n if (after && !after.startsWith(prefix)) throw new PluginError(400, 'Invalid comment cursor')\n const checks = await tx.get<Record<string, boolean>>(checksKey), rows = await tx.list<ReaderComment>(prefix, after, 51)\n return { checkIds: target.checkIds, checks: checks?.value ?? {}, revision: checks?.revision ?? 0, comments: rows.slice(0, 50).map(visible), ...(rows.length > 50 ? { cursor: recordCursor(scope, rows[49].id) } : {}) }\n }\n if (operation === 'set_check') {\n if (!target.checkIds.includes(a.itemId)) throw new PluginError(400, 'Unknown reading check')\n const old = await tx.get<Record<string, boolean>>(checksKey), value = { ...old?.value }\n if (a.checked) Object.defineProperty(value, a.itemId, { value: true, enumerable: true, configurable: true, writable: true })\n else delete value[a.itemId]\n if (Object.keys(value).length > 1000) throw new PluginError(400, 'Reading check capacity exceeded')\n const saved = await tx.put(checksKey, value, a.revision)\n return { checks: saved.value, revision: saved.revision }\n }\n if (operation === 'add_comment') {\n if (!a.body.trim() || (a.anchorId !== null && !target.anchorIds.includes(a.anchorId))) throw new PluginError(400, 'Comment body and valid anchor required')\n const comment: ReaderComment = { id: crypto.randomUUID(), anchorId: a.anchorId, body: a.body.trim(), visibility: a.visibility, authorId: p.userId, createdAt: now, resolved: false }\n return visible(await tx.put(prefix + comment.id, comment, 0))\n }\n if (operation === 'resolve_comment') {\n const row = await tx.get<ReaderComment>(prefix + a.commentId)\n if (!row) throw new PluginError(404, 'Comment unavailable')\n if (row.value.authorId !== p.userId) throw new PluginError(403, 'Only the comment author may resolve it')\n return visible(await tx.put(row.id, { ...row.value, resolved: a.resolved }, a.revision))\n }\n throw new PluginError(400, 'Unknown annotation operation')\n}\n","import Ajv from 'ajv'\nimport { randomUUID } from 'node:crypto'\nimport { assertPrincipal, PluginError, type PluginPrincipal } from './index'\nimport { atomicCommand, atomicHash, type AtomicRow, type AtomicRepository } from './atomic'\n/**\n * Immutable staged artifact identity, content hash and size returned by the host builder.\n * \n * @see ArtifactDeliveryService for canonical host integration.\n */\nexport interface DeliveryArtifact {\n /**\n * Immutable host artifact key, at most 1000 characters.\n */\n key:string;\n /**\n * Lowercase 64-character SHA-256 for the staged artifact.\n */\n contentHash:string;\n /**\n * Positive safe-integer artifact size in bytes.\n */\n bytes:number}\n/**\n * Exact target/content/approval identity requested for one public channel delivery.\n * \n * @see ArtifactDeliveryService for canonical host integration.\n */\nexport interface DeliveryRequest {\n /**\n * Stable delivery job identity within its tenant repository.\n */\n jobId:string;\n /**\n * Host-defined publication channel serialized against other unfinished delivery work.\n */\n channel:string;\n /**\n * publish stages an artifact; withdraw starts at activation/withdrawal without a build.\n */\n kind:'publish'|'withdraw';\n /**\n * Exact host-owned public destination metadata bound to the approval request.\n */\n target:Record<string,unknown>;\n /**\n * Reviewed source-content SHA-256; the host verifies exact target/hash/approval binding.\n */\n contentHash:string;\n /**\n * Exact host approval request admitting this public delivery; reader access alone is insufficient.\n */\n approvalRequestId:string}\n/**\n * Durable delivery phase, worker ownership and retry state for one approved publication/withdrawal.\n * \n * @see ArtifactDeliveryService for canonical host integration.\n */\nexport interface DeliveryJob extends DeliveryRequest {\n /**\n * Authenticated user who enqueued the approved request.\n */\n requestedBy:string;\n /**\n * Trusted UTC ISO enqueue time.\n */\n createdAt:string;\n /**\n * queued/running/failed/done/cancelled state retained with CAS revisions.\n */\n state:'queued'|'running'|'failed'|'done'|'cancelled';\n /**\n * Last durable build/activate/purge/cancel/done phase; uncertain external effects are retried idempotently.\n */\n phase:'build'|'activate'|'purge'|'cancel'|'done';\n /**\n * Number of worker claims; incremented when a new run owns the job.\n */\n attempts:number;\n /**\n * Worker ownership token; recovery requires proving prior workers drained rather than waiting for expiry.\n */\n token?:string;\n /**\n * Optional immutable build artifact used by the activation stage.\n */\n artifact?:DeliveryArtifact;\n /**\n * Sanitized failure notice; sensitive host details remain in host-owned logs.\n */\n error?:string}\n/**\n * Host publication approval, immutable artifact and idempotent external delivery capabilities.\n * \n * @see ArtifactDeliveryService for canonical host integration.\n */\nexport interface DeliveryPorts {\n /**\n * Verify public publication/withdrawal approval for the exact target and content.\n * \n * Verify explicit PUBLIC publication (or withdrawal) permission, exact target/hash and approval. Ordinary reader access is insufficient.\n * @param p - Verified principal requiring explicit public publication/withdrawal permission.\n * @param job - Pinned request/job with exact approved target/contentHash/approvalRequestId.\n * @returns Exactly true only when public permission and exact binding/approval remain valid.\n * @throws Rejects host permission, artifact, delivery or worker-control failures; external effects may already be partially complete.\n \n * @example\n * ```typescript\n * import type { DeliveryPorts, DeliveryRequest, PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export async function verifyReviewed(ports: DeliveryPorts, principal: PluginPrincipal, job: DeliveryRequest) {\n * // The host binds permission and external effects to this exact job.\n * return ports.verify(principal, job);\n * }\n * ```\n */\n verify(p:PluginPrincipal,job:DeliveryRequest):Promise<boolean>\n /**\n * Build and stage an immutable artifact outside the database transaction.\n * \n * Build and stage an immutable artifact outside a DB transaction. Must be idempotent for jobId.\n * @param p - Verified current principal.\n * @param job - Durable job carrying the stable jobId idempotency identity.\n * @returns An immutable staged artifact key, lowercase hash and positive safe byte size.\n * @throws Rejects host permission, artifact, delivery or worker-control failures; external effects may already be partially complete.\n \n * @example\n * ```typescript\n * import type { DeliveryPorts, DeliveryJob, PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export async function buildReviewed(ports: DeliveryPorts, principal: PluginPrincipal, job: DeliveryJob) {\n * // The host binds permission and external effects to this exact job.\n * return ports.build(principal, job);\n * }\n * ```\n */\n build(p:PluginPrincipal,job:DeliveryJob):Promise<DeliveryArtifact>\n /**\n * Apply or withdraw the exact public channel version idempotently.\n * \n * Atomic, idempotent channel update/withdrawal. Serialize with other host publishers; key=jobId.\n * @param p - Verified current principal.\n * @param job - Exact pinned publish/withdraw job, including staged artifact when publishing.\n * @returns Resolves without a value after the idempotent channel switch/withdrawal.\n * @throws Rejects host permission, artifact, delivery or worker-control failures; external effects may already be partially complete.\n \n * @example\n * ```typescript\n * import type { DeliveryPorts, DeliveryJob, PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export async function activateReviewed(ports: DeliveryPorts, principal: PluginPrincipal, job: DeliveryJob) {\n * // The host binds permission and external effects to this exact job.\n * await ports.activate(principal, job);\n * }\n * ```\n */\n activate(p:PluginPrincipal,job:DeliveryJob):Promise<void>\n /**\n * Invalidate the delivered channel idempotently before recording completion.\n * \n * Idempotent CDN invalidation; completion is recorded only after success.\n * @param p - Verified current principal.\n * @param job - Exact job channel/version requiring invalidation.\n * @returns Resolves without a value only after actual idempotent invalidation succeeds.\n * @throws Rejects host permission, artifact, delivery or worker-control failures; external effects may already be partially complete.\n \n * @example\n * ```typescript\n * import type { DeliveryPorts, DeliveryJob, PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export async function purgeReviewed(ports: DeliveryPorts, principal: PluginPrincipal, job: DeliveryJob) {\n * // The host binds permission and external effects to this exact job.\n * await ports.purge(principal, job);\n * }\n * ```\n */\n purge(p:PluginPrincipal,job:DeliveryJob):Promise<void>\n /**\n * Reconcile uncertain job effects and purge only this job's owned version.\n * \n * Reconcile any uncertain activation for this job and purge it, idempotently. Never remove a newer publisher's version.\n * @param p - Verified current principal admitted for cancellation.\n * @param job - Pinned job whose uncertain effects need reconciliation.\n * @returns Resolves without a value after idempotent reconciliation/purge of only this owned version; never remove newer publications.\n * @throws Rejects host permission, artifact, delivery or worker-control failures; external effects may already be partially complete.\n \n * @example\n * ```typescript\n * import type { DeliveryPorts, DeliveryJob, PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export async function cancelReviewed(ports: DeliveryPorts, principal: PluginPrincipal, job: DeliveryJob) {\n * if (!ports.cancel) throw new Error(\"Required recovery port unavailable\");\n * // The host binds permission and external effects to this exact job.\n * await ports.cancel(principal, job);\n * }\n * ```\n */\n cancel?(p:PluginPrincipal,job:DeliveryJob):Promise<void>\n /**\n * Prove prior workers for this job token can no longer perform effects.\n * @param p - Verified principal admitted for recovery.\n * @param job - Exact running job revision/token whose prior workers must be stopped.\n * @returns Exactly true only when prior workers cannot perform further effects; false/absence prevents recovery.\n * @throws Rejects host permission, artifact, delivery or worker-control failures; external effects may already be partially complete.\n \n * @example\n * ```typescript\n * import type { DeliveryPorts, DeliveryJob, PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export async function drainedReviewed(ports: DeliveryPorts, principal: PluginPrincipal, job: DeliveryJob) {\n * if (!ports.drained) throw new Error(\"Required recovery port unavailable\");\n * // The host binds permission and external effects to this exact job.\n * return ports.drained(principal, job);\n * }\n * ```\n */\n drained?(p:PluginPrincipal,job:DeliveryJob):Promise<boolean>\n}\n/**\n * Supported durable delivery command names; each requires live host resource/publication authorization.\n * \n * @see ArtifactDeliveryService for canonical usage.\n */\nexport const deliveryOperations=['enqueue_delivery','get_delivery','run_delivery','recover_delivery','cancel_delivery'] as const\nconst id={type:'string',pattern:'^[a-zA-Z0-9_-]{1,80}$'},hash={type:'string',pattern:'^[a-f0-9]{64}$'}\n/**\n * Closed schema for a new approved delivery request with stable command/job/target/content identities.\n * \n * @see ArtifactDeliveryService for canonical usage.\n */\nexport const enqueueDeliverySchema={type:'object',additionalProperties:false,required:['commandId','jobId','channel','kind','target','contentHash','approvalRequestId'],properties:{commandId:id,jobId:id,channel:id,kind:{enum:['publish','withdraw']},target:{type:'object',maxProperties:10,additionalProperties:true},contentHash:hash,approvalRequestId:id}}\n/**\n * Closed schema selecting an existing delivery job by its stable identifier.\n * \n * @see ArtifactDeliveryService for canonical usage.\n */\nexport const deliveryJobSchema={type:'object',additionalProperties:false,required:['jobId'],properties:{jobId:id}}\n/**\n * Closed schema requiring the exact job revision for explicit drained-worker recovery.\n * \n * @see ArtifactDeliveryService for canonical usage.\n */\nexport const recoverDeliverySchema={type:'object',additionalProperties:false,required:['jobId','revision'],properties:{jobId:id,revision:{type:'integer',minimum:1,maximum:9007199254740990}}}\nconst ajv=new Ajv({strict:true}),validators={enqueue_delivery:ajv.compile(enqueueDeliverySchema),cancel_delivery:ajv.compile(deliveryJobSchema),get_delivery:ajv.compile(deliveryJobSchema),run_delivery:ajv.compile(deliveryJobSchema),recover_delivery:ajv.compile(recoverDeliverySchema)}\n/**\n * Coordinates durable approved publication/withdrawal jobs with channel ownership and resumable idempotent host effects.\n * \n * @remarks\n * Requires a real atomic repository and host public-approval/build/channel/purge ports. Channel locks serialize unfinished jobs per tenant/repository. External build/activate/purge/cancel run outside database transactions; a failed reply can follow a completed external effect. Ports must deduplicate by stable jobId. Recovery requires proof that previous workers drained, never an elapsed lease alone.\n * \n * @example\n * ```typescript\n * import { ArtifactDeliveryService } from '@alneas/eaos-server/plugin-data';\n * export function connectDelivery(options: ConstructorParameters<typeof ArtifactDeliveryService>[0]) { return new ArtifactDeliveryService(options); }\n * ```\n */\nexport class ArtifactDeliveryService {\n /**\n * Binds the host atomic delivery ledger, public publication ports and live operation authorization.\n * @param options - Real atomic repository, idempotent host delivery ports and current operation/resource authorization; construction does not validate or execute those ports.\n * \n * @example\n * ```typescript\n * import { ArtifactDeliveryService } from '@alneas/eaos-server/plugin-data';\n * export function connectDelivery(options: ConstructorParameters<typeof ArtifactDeliveryService>[0]) { return new ArtifactDeliveryService(options); }\n * ```\n */\n constructor(private readonly options:{\n /**\n * Real atomic delivery ledger used for jobs, channel ownership and enqueue command receipts.\n */\n repository:AtomicRepository;\n /**\n * Host public-approval, artifact, channel, purge and recovery adapters with stable jobId idempotency.\n */\n ports:DeliveryPorts;\n /**\n * Live operation/resource permission callback; exactly true admits, false denies; schema validation follows initial admission.\n * @param p - Verified current tenant/user principal.\n * @param operation - Declared operation name.\n * @param input - Operation input to validate and authorize at the owning service boundary.\n * @param resource - Optional current delivery job/resource when available.\n * @returns Exactly true to admit the current operation; false denies.\n * @throws Rejects underlying service, authorization or persistence failures.\n \n * @example\n * ```typescript\n * import type { ArtifactDeliveryService, PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export async function canEnqueue(options: ConstructorParameters<typeof ArtifactDeliveryService>[0], principal: PluginPrincipal, input: unknown) {\n * return await options.authorize(principal, \"enqueue_delivery\", input) === true;\n * }\n * ```\n */\n authorize(p:PluginPrincipal,operation:string,input:unknown,resource?:unknown):Promise<boolean>}){}\n private async allow(p:PluginPrincipal,op:string,a:unknown,j?:DeliveryJob){assertPrincipal(p);if(await this.options.authorize(structuredClone(p),op,structuredClone(a),structuredClone(j))!==true)throw new PluginError(403,'Delivery access denied')}\n private async verify(p:PluginPrincipal,j:DeliveryRequest){if(await this.options.ports.verify(p,structuredClone(j))!==true)throw new PluginError(403,'Public delivery approval unavailable')}\n /**\n * Enqueues, reads, runs, cancels or explicitly recovers one durable approved delivery job.\n * @param p - Verified current tenant principal; operation/resource admission is rechecked before transitions.\n * @param op - One of deliveryOperations; each input is checked by its closed schema.\n * @param a - jobId for every operation; enqueue additionally needs commandId/channel/kind/target/contentHash/approvalRequestId, and recovery needs the exact running job revision.\n * @returns The durable AtomicRow<DeliveryJob>, possibly an existing identical enqueue receipt or already terminal job; query get_delivery for current state after receipt replay.\n * @throws Rejects invalid principal/input (401/400), denied live/public approval (403), absent job (404), busy channel/worker, stale recovery or unavailable cancellation port (409), invalid built artifact and propagated repository/port failures; effects may already have occurred.\n * \n * @remarks\n * Publish starts at build, withdrawal at activate; completion follows successful purge. Cancellation requires a reconciliation port and never removes a newer host version. Completed jobs require a new withdrawal job instead of cancellation. Recovery requires exact revision and drained(old token), marks failed and clears ownership for retry. Failure retains the last durable phase and a sanitized error, while the original host error may reject the call.\n * \n * @example\n * ```typescript\n * import { ArtifactDeliveryService, type PluginPrincipal } from '@alneas/eaos-server/plugin-data';\n * export function readDelivery(service: ArtifactDeliveryService, principal: PluginPrincipal, jobId: string) { return service.execute(principal, 'get_delivery', { jobId }); }\n * ```\n */\n async execute(p:PluginPrincipal,op:string,a:{\n /**\n * Stable job ID required by every delivery operation; 1–80 letters/digits/underscore/hyphen characters.\n */\n jobId:string;\n /**\n * Exact current positive running-job revision required only for explicit drained-worker recovery.\n */\n revision?:number;\n /**\n * Stable enqueue idempotency ID; identical input replays the original receipt and conflicting reuse rejects.\n */\n commandId?:string}&Partial<DeliveryRequest>):Promise<any>{\n p=structuredClone(p);a=structuredClone(a)\n await this.allow(p,op,a)\n if(!Object.hasOwn(validators,op)||!validators[op as keyof typeof validators](a))throw new PluginError(400,'Invalid delivery job')\n const repo=this.options.repository,ports=this.options.ports,key='delivery/'+a.jobId\n if(op==='enqueue_delivery'){\n if(!a.commandId||!a.channel||!a.target||!['publish','withdraw'].includes(a.kind??'')||!/^[a-f0-9]{64}$/.test(a.contentHash??'')||!a.approvalRequestId||JSON.stringify(a.target).length>4000)throw new PluginError(400,'Invalid delivery request')\n await this.verify(p,a as DeliveryRequest)\n return repo.run(p,async tx=>atomicCommand(tx,p,op,a as any,async()=>{\n const j:DeliveryJob={jobId:a.jobId,channel:a.channel!,kind:a.kind!,target:a.target!,contentHash:a.contentHash!,approvalRequestId:a.approvalRequestId!,requestedBy:p.userId,createdAt:new Date().toISOString(),state:'queued',phase:a.kind==='publish'?'build':'activate',attempts:0}\n const channel='delivery-channel/'+atomicHash(j.channel),lock=await tx.get<{jobId:string|null}>(channel)\n if(lock?.value.jobId)throw new PluginError(409,'Channel has unfinished delivery')\n await this.allow(p,op,a,j);await tx.put(channel,{jobId:j.jobId},lock?.revision??0)\n return tx.put(key,j,0)\n }))\n }\n const row=await repo.run(p,tx=>tx.get<DeliveryJob>(key));if(!row)throw new PluginError(404,'Delivery unavailable')\n await this.allow(p,op,a,row.value)\n if(op==='get_delivery')return row\n if(op==='recover_delivery'){\n if(row.revision!==a.revision||row.value.state!=='running'||await ports.drained?.(p,structuredClone(row.value))!==true)throw new PluginError(409,'Recovery requires a drained worker at this revision')\n return repo.run(p,async tx=>{await this.allow(p,op,a,row.value);const j={...row.value,state:'failed' as const};delete j.token;return tx.put(key,j,row.revision)})\n }\n if(['done','cancelled'].includes(row.value.state)){if(op==='cancel_delivery'&&row.value.state==='done')throw new PluginError(409,'Use a new withdrawal job for completed delivery');return row}\n if(row.value.state==='running')throw new PluginError(409,'Delivery worker already running')\n if(op==='cancel_delivery'&&!ports.cancel)throw new PluginError(409,'Cancellation reconciliation port unavailable')\n if(op!=='cancel_delivery'&&!['purge','cancel'].includes(row.value.phase))await this.verify(p,row.value)\n let current:AtomicRow<DeliveryJob>=await repo.run(p,async tx=>{await this.allow(p,op,a,row.value);return tx.put(key,{...row.value,...(op==='cancel_delivery'?{phase:'cancel' as const}:{}),state:'running' as const,token:randomUUID(),attempts:row.value.attempts+1,error:undefined},row.revision)})\n try{\n while(current.value.phase!=='done'){\n const j=current.value;await this.allow(p,op,a,j);if(!['purge','cancel'].includes(j.phase))await this.verify(p,j)\n let patch:Partial<DeliveryJob>\n if(j.phase==='cancel'){await this.allow(p,'cancel_delivery',a,j);if(!ports.cancel)throw new PluginError(409,'Cancellation reconciliation port unavailable');await ports.cancel(p,structuredClone(j));patch={phase:'done',state:'cancelled'}}else if(j.phase==='build'){\n const artifact=await ports.build(p,structuredClone(j))\n if(!artifact||typeof artifact.key!=='string'||artifact.key.length>1000||!/^[a-f0-9]{64}$/.test(artifact.contentHash)||!Number.isSafeInteger(artifact.bytes)||artifact.bytes<1)throw new Error('Invalid delivery artifact')\n patch={artifact,phase:'activate'}\n }else if(j.phase==='activate'){await ports.activate(p,structuredClone(j));patch={phase:'purge'}}\n else {await ports.purge(p,structuredClone(j));patch={phase:'done',state:'done'}}\n current=await repo.run(p,async tx=>{\n await this.allow(p,op,a,j)\n const saved=await tx.put(key,{...j,...patch},current.revision)\n if(patch.phase==='done'){\n const ck='delivery-channel/'+atomicHash(j.channel),lock=await tx.get<{jobId:string|null}>(ck)\n if(lock?.value.jobId!==j.jobId)throw new PluginError(409,'Delivery channel ownership changed')\n await tx.put(ck,{jobId:null},lock.revision)\n }\n return saved\n })\n }\n return current\n }catch(e){\n // Preserve the last durable phase. An uncertain external side effect is repeated with the same jobId.\n await repo.run(p,async tx=>{const fresh=await tx.get<DeliveryJob>(key);if(fresh&&fresh.value.token===current.value.token&&fresh.value.state==='running')await tx.put(key,{...fresh.value,state:'failed',error:'Delivery step failed; inspect host logs and retry'},fresh.revision)})\n throw e\n }\n }\n}\n"],"mappings":";;;;;;AACA,SAAS,wBAAwB;AACjC,SAAS,2BAA2B,mCAAkH;;;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AM,wBAAwB;AAAE,mBAAO;AAAA,UAAM,CAAC;AAAA,QACzJ,EAAC,IAAE,CAAC;AAAA,MACL;AACA,YAAM,UAAQ,wBAAwB,QAAO,OAAO;AACpD,UAAG;AAAC,eAAO,MAAM,KAAK,OAAO;AAAA,MAAC,UAAC;AAAQ,iBAAO;AAAM,gBAAQ;AAAA,MAAC;AAAA,IAC9D,CAAC;AAAA,EACF,EAAE;AACH;","names":["assertPayloadWithinPolicy","resolvePluginStoragePolicy","ajv","id","hash","hash","id","prefix","result","id","next","Ajv","ajv","Ajv","id","id","Ajv","randomUUID","Ajv","randomUUID","storagePayload","assertPayloadWithinPolicy","resolvePluginStoragePolicy","id","res","id"]}
|