@dudousxd/nestjs-durable 0.56.0 → 0.57.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/dist/index.d.cts CHANGED
@@ -83,7 +83,8 @@ declare function attributesOf<C extends WorkflowClass>(workflow: C, run: {
83
83
  * Kept byte-aligned with nestjs-context's `ContextAccessor` (and the identical
84
84
  * mirror in `@dudousxd/nestjs-authz`): `traceId()` / `tenantId()` are REQUIRED
85
85
  * (the real accessor always provides them) and `get()` is included, so the
86
- * structural match stays exact when DurableModule auto-feeds the carrier.
86
+ * structural match stays exact when DurableModule auto-feeds the carrier. The tenancy
87
+ * members (`tenant`/`tenancy`/`tenantFilter`, nestjs-context ≥ 1.2) are optional.
87
88
  */
88
89
  interface UserRef {
89
90
  type: string;
@@ -100,7 +101,40 @@ interface ContextAccessor {
100
101
  userRef(): UserRef | undefined;
101
102
  /** The raw context store for the current request, or `undefined`. */
102
103
  get(): ContextStore | undefined;
104
+ /**
105
+ * The active tenant (the customer the request's data belongs to). Optional: an older context, or
106
+ * an app's own accessor, may not have it; durable then treats tenancy as off.
107
+ */
108
+ tenant?(): TenantRef | undefined;
109
+ /** The context's `tenancy` switch: `{ enabled, kinds? }`. Optional, as above. */
110
+ tenancy?(): {
111
+ enabled: boolean;
112
+ kinds?: string[];
113
+ };
114
+ /** How a lib must scope data right now. Optional, as above. */
115
+ tenantFilter?(options?: {
116
+ kinds?: string[];
117
+ }): TenantFilter;
118
+ }
119
+ /** A tenant as the context reports it. Structural mirror of nestjs-context's `TenantRef`. */
120
+ interface TenantRef {
121
+ id: string;
122
+ kind: string;
123
+ source: string;
124
+ slug?: string;
125
+ role?: string;
103
126
  }
127
+ /** How a lib must scope data right now. Structural mirror of nestjs-context's `TenantFilter`. */
128
+ type TenantFilter = {
129
+ mode: 'system';
130
+ } | {
131
+ mode: 'all';
132
+ } | {
133
+ mode: 'tenantless';
134
+ } | {
135
+ mode: 'tenant';
136
+ tenant: TenantRef;
137
+ };
104
138
 
105
139
  /** A class-validator DTO class — validated with the same `plainToInstance` + `validate` NestJS's
106
140
  * `ValidationPipe` runs. */
@@ -575,6 +609,22 @@ declare const OnEvent: typeof OnDurableEvent;
575
609
  */
576
610
  declare function getOnEvents(meta: WorkflowMeta, target: object): OnEventEntry[];
577
611
 
612
+ /**
613
+ * Tenancy for durable: the CUSTOMER a run belongs to (`@dudousxd/nestjs-context`'s tenant), not the
614
+ * worker-pool `namespace`. A local, structural reader of the context contract — durable never imports
615
+ * nestjs-context, so it works with any context version or none at all: with the accessor (or its
616
+ * tenancy methods) missing, tenancy reads as off and durable behaves exactly as without it.
617
+ */
618
+ /** The `tenancy` option of `DurableModule`. Same shape in every Aviary lib. */
619
+ type DurableTenancyOption = 'inherit' | false | {
620
+ /** `'inherit'` (default) follows `ContextModule`'s `tenancy.enabled`. */
621
+ enabled?: 'inherit' | boolean;
622
+ /** Tenant kinds durable honours, instead of the context's own `kinds`. */
623
+ kinds?: string[];
624
+ /** Whether a tenant request also sees runs with no tenant. Default `'tenantless'` (it does not). */
625
+ nullRows?: 'tenantless' | 'shared';
626
+ };
627
+
578
628
  /** What a tenant verifier receives for each request a tenant process sends. */
579
629
  interface TenantVerifierInput {
580
630
  /** The token presented on the request (the wire `tenant` field). */
@@ -927,6 +977,17 @@ interface DurableModuleSharedOptions {
927
977
  * authorization boundary. Operator only.
928
978
  */
929
979
  context?: () => Record<string, unknown> | undefined;
980
+ /**
981
+ * Tenancy: scope runs by the CUSTOMER they belong to (`@dudousxd/nestjs-context`'s tenant), not by
982
+ * the worker-pool {@link namespace}. With it on, `start` stamps the request's tenant on the run
983
+ * (an explicit `StartOptions.tenantId` wins), children, `continueAsNew` and schedules inherit it,
984
+ * every turn runs with it restored as the context tenant, and app-facing reads and control calls
985
+ * (`getRun`, `signal`, `cancel`, retry, the dashboard) only see the caller's tenant's runs.
986
+ *
987
+ * `'inherit'` (default) follows `ContextModule.forRoot({ tenancy: { enabled } })`, which is off by
988
+ * default; `false` keeps durable out of tenancy. Without nestjs-context ≥ 1.2, tenancy is off.
989
+ */
990
+ tenancy?: DurableTenancyOption;
930
991
  /** Attempts for each saga compensation when a run fails. Default 1 (no retry). Idempotent undos.
931
992
  * Operator only. */
932
993
  compensationRetries?: number;
@@ -1520,6 +1581,13 @@ declare class StoreRunGateway implements RunGateway {
1520
1581
  private readonly engine;
1521
1582
  constructor(store: StateStore, engine: WorkflowEngine);
1522
1583
  topology(): DurableTopology;
1584
+ /**
1585
+ * Narrow `query` to the caller's tenant (the tenancy matching rule; see `DurableModule`'s
1586
+ * `tenancy`). A no-op with tenancy off, or for a caller outside any request (`system`).
1587
+ */
1588
+ private scoped;
1589
+ /** The run, or null when it is missing OR belongs to a tenant the caller may not see (404). */
1590
+ private visibleRun;
1523
1591
  getRunDetail(runId: string, options?: RunDetailOptions): Promise<RunDetail | null>;
1524
1592
  /**
1525
1593
  * What a run detail reads beyond the run row and its checkpoints: what this run's settling
@@ -1578,6 +1646,10 @@ declare class StoreRunGateway implements RunGateway {
1578
1646
  redispatched: number;
1579
1647
  }) | null>;
1580
1648
  republishLifecycle(target: RepublishLifecycleTarget): Promise<RepublishLifecycleResult>;
1649
+ /**
1650
+ * Stream `runId`'s events. With tenancy, a run the caller may not see streams nothing; events of a
1651
+ * run that does not exist yet are held until its row shows whose it is.
1652
+ */
1581
1653
  subscribe(runId: string, onEvent: (event: EngineEvent) => void): () => void;
1582
1654
  }
1583
1655
 
@@ -1710,4 +1782,4 @@ declare class WorkflowService {
1710
1782
  republishLifecycle(target: RepublishLifecycleTarget): Promise<RepublishLifecycleResult>;
1711
1783
  }
1712
1784
 
1713
- export { BAD_RUN_REQUEST, CONTEXT_ACCESSOR, type ContextAccessor, type ContextStore, type ContractClass, type ControlPlaneDurableOptions, DEAD_LETTER_METADATA, DURABLE_STEP_METADATA, DURABLE_WORKER_RUNNERS, DURABLE_WORKER_RUNTIME, DeadLetter, type DtoClass, DurableModule, type DurableModuleAsyncOptions, type DurableModuleOptions, type DurableModuleSharedOptions, type DurableRetentionOptions, DurableStartClient, DurableStep, type DurableStepInterceptor, type DurableStepMeta, type DurableTopologyName, ENTITY_METADATA, ENTITY_ON_METADATA, Entity, EntityService, type ErrorClassWithCode, IN_APP_RUN_REDIS_WORKER, IN_APP_WORKER_BINDING, IN_APP_WORKER_RUNNERS, IN_APP_WORKER_RUNTIME, type InAppWorkerBinding, InAppWorkerBootstrap, type IoSchema, type LazyContract, ON_ERROR_METADATA, ON_EVENT_BATCH_METADATA, ON_EVENT_METADATA, On, OnDurableEvent, OnError, type OnErrorMethod, OnEvent, OnWorkflowCompleted, OnWorkflowFailed, type OnWorkflowFailedOptions, type OnWorkflowSettledOptions, ProxyRunGateway, RUN_GATEWAY, RUN_REDIS_WORKER, RunGatewayError, type RunGatewayErrorCode, type RunLookupStore, type RunRedisWorkerFn, RunRequestResponder, type RunRequestResponderOptions, type RunRequestTransport, STEP_INTERCEPTOR_METADATA, type StandaloneDurableOptions, Step, StepInterceptor, type StepOptions, StoreRunGateway, type SubscriberBatch, type SubscriberDebounce, type SubscriberDecorator, TENANT_REPUBLISH_MAX_LIMIT, type TenantCredentialsContract, type TenantDurableOptions, TenantEventRepublisher, type TenantTokenOption, type TenantVerifierContract, type TenantVerifierInput, type TenantVerifierOption, ThinStepRegistrar, ThinWorkerBootstrap, ThinWorkflowRegistrar, UNSUPPORTED_RUN_REQUEST, type UserRef, WORKFLOW_METADATA, Workflow, type WorkflowAttributesOf, type WorkflowMeta, type WorkflowOptions, WorkflowService, attributesOf, entityConfigFor, eventBatchOf, getDurableStepMeta, getEntityMeta, getOnEvents, getWorkflowMeta, inAppWorkerProviders, isDeadLetterHandler, isDrivingOperator, isOperatorRole, isStepInterceptor, onErrorCodesOf, thinWorkerProviders, unavailableRunGateway };
1785
+ export { BAD_RUN_REQUEST, CONTEXT_ACCESSOR, type ContextAccessor, type ContextStore, type ContractClass, type ControlPlaneDurableOptions, DEAD_LETTER_METADATA, DURABLE_STEP_METADATA, DURABLE_WORKER_RUNNERS, DURABLE_WORKER_RUNTIME, DeadLetter, type DtoClass, DurableModule, type DurableModuleAsyncOptions, type DurableModuleOptions, type DurableModuleSharedOptions, type DurableRetentionOptions, DurableStartClient, DurableStep, type DurableStepInterceptor, type DurableStepMeta, type DurableTopologyName, ENTITY_METADATA, ENTITY_ON_METADATA, Entity, EntityService, type ErrorClassWithCode, IN_APP_RUN_REDIS_WORKER, IN_APP_WORKER_BINDING, IN_APP_WORKER_RUNNERS, IN_APP_WORKER_RUNTIME, type InAppWorkerBinding, InAppWorkerBootstrap, type IoSchema, type LazyContract, ON_ERROR_METADATA, ON_EVENT_BATCH_METADATA, ON_EVENT_METADATA, On, OnDurableEvent, OnError, type OnErrorMethod, OnEvent, OnWorkflowCompleted, OnWorkflowFailed, type OnWorkflowFailedOptions, type OnWorkflowSettledOptions, ProxyRunGateway, RUN_GATEWAY, RUN_REDIS_WORKER, RunGatewayError, type RunGatewayErrorCode, type RunLookupStore, type RunRedisWorkerFn, RunRequestResponder, type RunRequestResponderOptions, type RunRequestTransport, STEP_INTERCEPTOR_METADATA, type StandaloneDurableOptions, Step, StepInterceptor, type StepOptions, StoreRunGateway, type SubscriberBatch, type SubscriberDebounce, type SubscriberDecorator, TENANT_REPUBLISH_MAX_LIMIT, type TenantCredentialsContract, type TenantDurableOptions, TenantEventRepublisher, type TenantFilter, type TenantRef, type TenantTokenOption, type TenantVerifierContract, type TenantVerifierInput, type TenantVerifierOption, ThinStepRegistrar, ThinWorkerBootstrap, ThinWorkflowRegistrar, UNSUPPORTED_RUN_REQUEST, type UserRef, WORKFLOW_METADATA, Workflow, type WorkflowAttributesOf, type WorkflowMeta, type WorkflowOptions, WorkflowService, attributesOf, entityConfigFor, eventBatchOf, getDurableStepMeta, getEntityMeta, getOnEvents, getWorkflowMeta, inAppWorkerProviders, isDeadLetterHandler, isDrivingOperator, isOperatorRole, isStepInterceptor, onErrorCodesOf, thinWorkerProviders, unavailableRunGateway };
package/dist/index.d.ts CHANGED
@@ -83,7 +83,8 @@ declare function attributesOf<C extends WorkflowClass>(workflow: C, run: {
83
83
  * Kept byte-aligned with nestjs-context's `ContextAccessor` (and the identical
84
84
  * mirror in `@dudousxd/nestjs-authz`): `traceId()` / `tenantId()` are REQUIRED
85
85
  * (the real accessor always provides them) and `get()` is included, so the
86
- * structural match stays exact when DurableModule auto-feeds the carrier.
86
+ * structural match stays exact when DurableModule auto-feeds the carrier. The tenancy
87
+ * members (`tenant`/`tenancy`/`tenantFilter`, nestjs-context ≥ 1.2) are optional.
87
88
  */
88
89
  interface UserRef {
89
90
  type: string;
@@ -100,7 +101,40 @@ interface ContextAccessor {
100
101
  userRef(): UserRef | undefined;
101
102
  /** The raw context store for the current request, or `undefined`. */
102
103
  get(): ContextStore | undefined;
104
+ /**
105
+ * The active tenant (the customer the request's data belongs to). Optional: an older context, or
106
+ * an app's own accessor, may not have it; durable then treats tenancy as off.
107
+ */
108
+ tenant?(): TenantRef | undefined;
109
+ /** The context's `tenancy` switch: `{ enabled, kinds? }`. Optional, as above. */
110
+ tenancy?(): {
111
+ enabled: boolean;
112
+ kinds?: string[];
113
+ };
114
+ /** How a lib must scope data right now. Optional, as above. */
115
+ tenantFilter?(options?: {
116
+ kinds?: string[];
117
+ }): TenantFilter;
118
+ }
119
+ /** A tenant as the context reports it. Structural mirror of nestjs-context's `TenantRef`. */
120
+ interface TenantRef {
121
+ id: string;
122
+ kind: string;
123
+ source: string;
124
+ slug?: string;
125
+ role?: string;
103
126
  }
127
+ /** How a lib must scope data right now. Structural mirror of nestjs-context's `TenantFilter`. */
128
+ type TenantFilter = {
129
+ mode: 'system';
130
+ } | {
131
+ mode: 'all';
132
+ } | {
133
+ mode: 'tenantless';
134
+ } | {
135
+ mode: 'tenant';
136
+ tenant: TenantRef;
137
+ };
104
138
 
105
139
  /** A class-validator DTO class — validated with the same `plainToInstance` + `validate` NestJS's
106
140
  * `ValidationPipe` runs. */
@@ -575,6 +609,22 @@ declare const OnEvent: typeof OnDurableEvent;
575
609
  */
576
610
  declare function getOnEvents(meta: WorkflowMeta, target: object): OnEventEntry[];
577
611
 
612
+ /**
613
+ * Tenancy for durable: the CUSTOMER a run belongs to (`@dudousxd/nestjs-context`'s tenant), not the
614
+ * worker-pool `namespace`. A local, structural reader of the context contract — durable never imports
615
+ * nestjs-context, so it works with any context version or none at all: with the accessor (or its
616
+ * tenancy methods) missing, tenancy reads as off and durable behaves exactly as without it.
617
+ */
618
+ /** The `tenancy` option of `DurableModule`. Same shape in every Aviary lib. */
619
+ type DurableTenancyOption = 'inherit' | false | {
620
+ /** `'inherit'` (default) follows `ContextModule`'s `tenancy.enabled`. */
621
+ enabled?: 'inherit' | boolean;
622
+ /** Tenant kinds durable honours, instead of the context's own `kinds`. */
623
+ kinds?: string[];
624
+ /** Whether a tenant request also sees runs with no tenant. Default `'tenantless'` (it does not). */
625
+ nullRows?: 'tenantless' | 'shared';
626
+ };
627
+
578
628
  /** What a tenant verifier receives for each request a tenant process sends. */
579
629
  interface TenantVerifierInput {
580
630
  /** The token presented on the request (the wire `tenant` field). */
@@ -927,6 +977,17 @@ interface DurableModuleSharedOptions {
927
977
  * authorization boundary. Operator only.
928
978
  */
929
979
  context?: () => Record<string, unknown> | undefined;
980
+ /**
981
+ * Tenancy: scope runs by the CUSTOMER they belong to (`@dudousxd/nestjs-context`'s tenant), not by
982
+ * the worker-pool {@link namespace}. With it on, `start` stamps the request's tenant on the run
983
+ * (an explicit `StartOptions.tenantId` wins), children, `continueAsNew` and schedules inherit it,
984
+ * every turn runs with it restored as the context tenant, and app-facing reads and control calls
985
+ * (`getRun`, `signal`, `cancel`, retry, the dashboard) only see the caller's tenant's runs.
986
+ *
987
+ * `'inherit'` (default) follows `ContextModule.forRoot({ tenancy: { enabled } })`, which is off by
988
+ * default; `false` keeps durable out of tenancy. Without nestjs-context ≥ 1.2, tenancy is off.
989
+ */
990
+ tenancy?: DurableTenancyOption;
930
991
  /** Attempts for each saga compensation when a run fails. Default 1 (no retry). Idempotent undos.
931
992
  * Operator only. */
932
993
  compensationRetries?: number;
@@ -1520,6 +1581,13 @@ declare class StoreRunGateway implements RunGateway {
1520
1581
  private readonly engine;
1521
1582
  constructor(store: StateStore, engine: WorkflowEngine);
1522
1583
  topology(): DurableTopology;
1584
+ /**
1585
+ * Narrow `query` to the caller's tenant (the tenancy matching rule; see `DurableModule`'s
1586
+ * `tenancy`). A no-op with tenancy off, or for a caller outside any request (`system`).
1587
+ */
1588
+ private scoped;
1589
+ /** The run, or null when it is missing OR belongs to a tenant the caller may not see (404). */
1590
+ private visibleRun;
1523
1591
  getRunDetail(runId: string, options?: RunDetailOptions): Promise<RunDetail | null>;
1524
1592
  /**
1525
1593
  * What a run detail reads beyond the run row and its checkpoints: what this run's settling
@@ -1578,6 +1646,10 @@ declare class StoreRunGateway implements RunGateway {
1578
1646
  redispatched: number;
1579
1647
  }) | null>;
1580
1648
  republishLifecycle(target: RepublishLifecycleTarget): Promise<RepublishLifecycleResult>;
1649
+ /**
1650
+ * Stream `runId`'s events. With tenancy, a run the caller may not see streams nothing; events of a
1651
+ * run that does not exist yet are held until its row shows whose it is.
1652
+ */
1581
1653
  subscribe(runId: string, onEvent: (event: EngineEvent) => void): () => void;
1582
1654
  }
1583
1655
 
@@ -1710,4 +1782,4 @@ declare class WorkflowService {
1710
1782
  republishLifecycle(target: RepublishLifecycleTarget): Promise<RepublishLifecycleResult>;
1711
1783
  }
1712
1784
 
1713
- export { BAD_RUN_REQUEST, CONTEXT_ACCESSOR, type ContextAccessor, type ContextStore, type ContractClass, type ControlPlaneDurableOptions, DEAD_LETTER_METADATA, DURABLE_STEP_METADATA, DURABLE_WORKER_RUNNERS, DURABLE_WORKER_RUNTIME, DeadLetter, type DtoClass, DurableModule, type DurableModuleAsyncOptions, type DurableModuleOptions, type DurableModuleSharedOptions, type DurableRetentionOptions, DurableStartClient, DurableStep, type DurableStepInterceptor, type DurableStepMeta, type DurableTopologyName, ENTITY_METADATA, ENTITY_ON_METADATA, Entity, EntityService, type ErrorClassWithCode, IN_APP_RUN_REDIS_WORKER, IN_APP_WORKER_BINDING, IN_APP_WORKER_RUNNERS, IN_APP_WORKER_RUNTIME, type InAppWorkerBinding, InAppWorkerBootstrap, type IoSchema, type LazyContract, ON_ERROR_METADATA, ON_EVENT_BATCH_METADATA, ON_EVENT_METADATA, On, OnDurableEvent, OnError, type OnErrorMethod, OnEvent, OnWorkflowCompleted, OnWorkflowFailed, type OnWorkflowFailedOptions, type OnWorkflowSettledOptions, ProxyRunGateway, RUN_GATEWAY, RUN_REDIS_WORKER, RunGatewayError, type RunGatewayErrorCode, type RunLookupStore, type RunRedisWorkerFn, RunRequestResponder, type RunRequestResponderOptions, type RunRequestTransport, STEP_INTERCEPTOR_METADATA, type StandaloneDurableOptions, Step, StepInterceptor, type StepOptions, StoreRunGateway, type SubscriberBatch, type SubscriberDebounce, type SubscriberDecorator, TENANT_REPUBLISH_MAX_LIMIT, type TenantCredentialsContract, type TenantDurableOptions, TenantEventRepublisher, type TenantTokenOption, type TenantVerifierContract, type TenantVerifierInput, type TenantVerifierOption, ThinStepRegistrar, ThinWorkerBootstrap, ThinWorkflowRegistrar, UNSUPPORTED_RUN_REQUEST, type UserRef, WORKFLOW_METADATA, Workflow, type WorkflowAttributesOf, type WorkflowMeta, type WorkflowOptions, WorkflowService, attributesOf, entityConfigFor, eventBatchOf, getDurableStepMeta, getEntityMeta, getOnEvents, getWorkflowMeta, inAppWorkerProviders, isDeadLetterHandler, isDrivingOperator, isOperatorRole, isStepInterceptor, onErrorCodesOf, thinWorkerProviders, unavailableRunGateway };
1785
+ export { BAD_RUN_REQUEST, CONTEXT_ACCESSOR, type ContextAccessor, type ContextStore, type ContractClass, type ControlPlaneDurableOptions, DEAD_LETTER_METADATA, DURABLE_STEP_METADATA, DURABLE_WORKER_RUNNERS, DURABLE_WORKER_RUNTIME, DeadLetter, type DtoClass, DurableModule, type DurableModuleAsyncOptions, type DurableModuleOptions, type DurableModuleSharedOptions, type DurableRetentionOptions, DurableStartClient, DurableStep, type DurableStepInterceptor, type DurableStepMeta, type DurableTopologyName, ENTITY_METADATA, ENTITY_ON_METADATA, Entity, EntityService, type ErrorClassWithCode, IN_APP_RUN_REDIS_WORKER, IN_APP_WORKER_BINDING, IN_APP_WORKER_RUNNERS, IN_APP_WORKER_RUNTIME, type InAppWorkerBinding, InAppWorkerBootstrap, type IoSchema, type LazyContract, ON_ERROR_METADATA, ON_EVENT_BATCH_METADATA, ON_EVENT_METADATA, On, OnDurableEvent, OnError, type OnErrorMethod, OnEvent, OnWorkflowCompleted, OnWorkflowFailed, type OnWorkflowFailedOptions, type OnWorkflowSettledOptions, ProxyRunGateway, RUN_GATEWAY, RUN_REDIS_WORKER, RunGatewayError, type RunGatewayErrorCode, type RunLookupStore, type RunRedisWorkerFn, RunRequestResponder, type RunRequestResponderOptions, type RunRequestTransport, STEP_INTERCEPTOR_METADATA, type StandaloneDurableOptions, Step, StepInterceptor, type StepOptions, StoreRunGateway, type SubscriberBatch, type SubscriberDebounce, type SubscriberDecorator, TENANT_REPUBLISH_MAX_LIMIT, type TenantCredentialsContract, type TenantDurableOptions, TenantEventRepublisher, type TenantFilter, type TenantRef, type TenantTokenOption, type TenantVerifierContract, type TenantVerifierInput, type TenantVerifierOption, ThinStepRegistrar, ThinWorkerBootstrap, ThinWorkflowRegistrar, UNSUPPORTED_RUN_REQUEST, type UserRef, WORKFLOW_METADATA, Workflow, type WorkflowAttributesOf, type WorkflowMeta, type WorkflowOptions, WorkflowService, attributesOf, entityConfigFor, eventBatchOf, getDurableStepMeta, getEntityMeta, getOnEvents, getWorkflowMeta, inAppWorkerProviders, isDeadLetterHandler, isDrivingOperator, isOperatorRole, isStepInterceptor, onErrorCodesOf, thinWorkerProviders, unavailableRunGateway };
package/dist/index.js CHANGED
@@ -1061,7 +1061,7 @@ function unavailableRunGateway() {
1061
1061
  __name(unavailableRunGateway, "unavailableRunGateway");
1062
1062
 
1063
1063
  // src/durable.module.ts
1064
- import { DURABLE_OPTIONS, DURABLE_OPTIONS_CANONICAL as DURABLE_OPTIONS_CANONICAL8, RunGateway as RunGateway2, STATE_STORE, STATE_STORE_CANONICAL as STATE_STORE_CANONICAL4, TRANSPORT, TRANSPORT_CANONICAL as TRANSPORT_CANONICAL3, WorkflowEngine as WorkflowEngine6 } from "@dudousxd/nestjs-durable-core";
1064
+ import { DURABLE_OPTIONS, DURABLE_OPTIONS_CANONICAL as DURABLE_OPTIONS_CANONICAL8, RunGateway as RunGateway2, STATE_STORE, STATE_STORE_CANONICAL as STATE_STORE_CANONICAL4, TRANSPORT, TRANSPORT_CANONICAL as TRANSPORT_CANONICAL3, WorkflowEngine as WorkflowEngine6, useDurableExecution } from "@dudousxd/nestjs-durable-core";
1065
1065
  import { Inject as Inject9, Injectable as Injectable13, Module } from "@nestjs/common";
1066
1066
  import { DiscoveryModule, ModuleRef as ModuleRef2 } from "@nestjs/core";
1067
1067
 
@@ -2519,9 +2519,23 @@ var StoreRunGateway = class {
2519
2519
  role: "control-plane"
2520
2520
  };
2521
2521
  }
2522
- async getRunDetail(runId, options) {
2522
+ /**
2523
+ * Narrow `query` to the caller's tenant (the tenancy matching rule; see `DurableModule`'s
2524
+ * `tenancy`). A no-op with tenancy off, or for a caller outside any request (`system`).
2525
+ */
2526
+ scoped(query) {
2527
+ return typeof this.engine?.scopeRunQuery === "function" ? this.engine.scopeRunQuery(query) : query;
2528
+ }
2529
+ /** The run, or null when it is missing OR belongs to a tenant the caller may not see (404). */
2530
+ async visibleRun(runId) {
2523
2531
  const run = await this.store.getRun(runId);
2524
2532
  if (!run) return null;
2533
+ const { tenantIds } = this.scoped({});
2534
+ return !tenantIds || tenantIds.includes(run.tenantId ?? null) ? run : null;
2535
+ }
2536
+ async getRunDetail(runId, options) {
2537
+ const run = await this.visibleRun(runId);
2538
+ if (!run) return null;
2525
2539
  const links = await this.lifecycleLinks(run);
2526
2540
  const over = options?.summarizeFansOver;
2527
2541
  if (over === void 0) {
@@ -2666,10 +2680,10 @@ var StoreRunGateway = class {
2666
2680
  return this.engine.lifecycleSubscribers(workflow, kind, namespace);
2667
2681
  }
2668
2682
  getRun(runId) {
2669
- return this.store.getRun(runId);
2683
+ return this.visibleRun(runId);
2670
2684
  }
2671
2685
  async getFanMembers(runId, group, query) {
2672
- if (!await this.store.getRun(runId)) return null;
2686
+ if (!await this.visibleRun(runId)) return null;
2673
2687
  if (aggregatesCheckpoints(this.store)) {
2674
2688
  const stats = await this.store.checkpointStats(runId, {
2675
2689
  group
@@ -2691,7 +2705,7 @@ var StoreRunGateway = class {
2691
2705
  return pageFan2(await this.store.listCheckpoints(runId), group, query);
2692
2706
  }
2693
2707
  async listRuns(query) {
2694
- const runs = await this.store.listRuns(withoutRegistry(query));
2708
+ const runs = await this.store.listRuns(this.scoped(withoutRegistry(query)));
2695
2709
  const waiterByRun = indexWaitersByRun(await listSignalWaitersOfRuns(this.store, runs.filter((run) => run.status === "suspended").map((run) => run.id)));
2696
2710
  return runs.map((run) => {
2697
2711
  const waiting = resolveRunWaiting(run, waiterByRun);
@@ -2708,7 +2722,7 @@ var StoreRunGateway = class {
2708
2722
  * listing — correct, but the unbounded read this exists to avoid, so it is the last resort.
2709
2723
  */
2710
2724
  async runFacets(query) {
2711
- const scoped = withoutRegistry(query);
2725
+ const scoped = this.scoped(withoutRegistry(query));
2712
2726
  if (this.store.runFacets) return this.store.runFacets(scoped);
2713
2727
  const runs = await this.store.listRuns(scoped);
2714
2728
  return mergeRunFacetRows(runs.map((r) => ({
@@ -2725,7 +2739,7 @@ var StoreRunGateway = class {
2725
2739
  * still works without it.
2726
2740
  */
2727
2741
  async runValueFacets(axis, query, opts) {
2728
- return this.store.runValueFacets?.(axis, withoutRegistry(query), opts) ?? [];
2742
+ return this.store.runValueFacets?.(axis, this.scoped(withoutRegistry(query)), opts) ?? [];
2729
2743
  }
2730
2744
  /**
2731
2745
  * Bulk-resolve what each of `runIds` is currently parked on — for a consumer with its own filtered/
@@ -2741,11 +2755,11 @@ var StoreRunGateway = class {
2741
2755
  if (runIds.length === 0) return {};
2742
2756
  const idSet = new Set(runIds);
2743
2757
  const [suspended, waiters] = await Promise.all([
2744
- this.store.listRuns({
2758
+ this.store.listRuns(this.scoped({
2745
2759
  statuses: [
2746
2760
  "suspended"
2747
2761
  ]
2748
- }),
2762
+ })),
2749
2763
  listSignalWaitersOfRuns(this.store, runIds)
2750
2764
  ]);
2751
2765
  const waiterByRun = indexWaitersByRun(waiters);
@@ -2781,10 +2795,44 @@ var StoreRunGateway = class {
2781
2795
  republishLifecycle(target) {
2782
2796
  return this.engine.republishLifecycle(target);
2783
2797
  }
2798
+ /**
2799
+ * Stream `runId`'s events. With tenancy, a run the caller may not see streams nothing; events of a
2800
+ * run that does not exist yet are held until its row shows whose it is.
2801
+ */
2784
2802
  subscribe(runId, onEvent) {
2785
- return this.engine.subscribe((event) => {
2786
- if (event.runId === runId) onEvent(event);
2803
+ const { tenantIds } = this.scoped({});
2804
+ if (!tenantIds) {
2805
+ return this.engine.subscribe((event) => {
2806
+ if (event.runId === runId) onEvent(event);
2807
+ });
2808
+ }
2809
+ let visible;
2810
+ let held = [];
2811
+ let checking = false;
2812
+ const check = /* @__PURE__ */ __name(() => {
2813
+ if (checking || visible !== void 0) return;
2814
+ checking = true;
2815
+ void this.store.getRun(runId).then((run) => {
2816
+ if (run) visible = tenantIds.includes(run.tenantId ?? null);
2817
+ }, () => void 0).finally(() => {
2818
+ checking = false;
2819
+ if (visible === void 0) return;
2820
+ const pending = held;
2821
+ held = [];
2822
+ if (visible) for (const event of pending) onEvent(event);
2823
+ });
2824
+ }, "check");
2825
+ const off = this.engine.subscribe((event) => {
2826
+ if (event.runId !== runId || visible === false) return;
2827
+ if (visible) return onEvent(event);
2828
+ held.push(event);
2829
+ check();
2787
2830
  });
2831
+ check();
2832
+ return () => {
2833
+ held = [];
2834
+ off();
2835
+ };
2788
2836
  }
2789
2837
  };
2790
2838
  StoreRunGateway = _ts_decorate9([
@@ -2797,6 +2845,111 @@ StoreRunGateway = _ts_decorate9([
2797
2845
  ])
2798
2846
  ], StoreRunGateway);
2799
2847
 
2848
+ // src/tenancy.ts
2849
+ var SLOT = Symbol.for("@dudousxd/nestjs-diagnostics:accessor");
2850
+ function accessorOf(accessor) {
2851
+ if (accessor) return accessor;
2852
+ const slot = globalThis[SLOT];
2853
+ return slot?.current ?? void 0;
2854
+ }
2855
+ __name(accessorOf, "accessorOf");
2856
+ function readTenancy(option, accessor) {
2857
+ const a = accessorOf(accessor);
2858
+ if (option === false || typeof a?.tenancy !== "function" || typeof a.tenantFilter !== "function") {
2859
+ return {
2860
+ enabled: false
2861
+ };
2862
+ }
2863
+ const own = typeof option === "object" ? option : {};
2864
+ const inherit = own.enabled === void 0 || own.enabled === "inherit";
2865
+ if (!(inherit ? a.tenancy().enabled : own.enabled)) return {
2866
+ enabled: false
2867
+ };
2868
+ const kinds = own.kinds;
2869
+ const tenantFilter = a.tenantFilter.bind(a);
2870
+ return {
2871
+ enabled: true,
2872
+ nullRows: own.nullRows ?? "tenantless",
2873
+ filter: /* @__PURE__ */ __name(() => tenantFilter(kinds ? {
2874
+ kinds
2875
+ } : void 0), "filter")
2876
+ };
2877
+ }
2878
+ __name(readTenancy, "readTenancy");
2879
+ function isTenantRuntime(x) {
2880
+ return !!x && typeof x.withTenant === "function";
2881
+ }
2882
+ __name(isTenantRuntime, "isTenantRuntime");
2883
+ function restore(runtime, tenant, fn) {
2884
+ return runtime.withTenant({
2885
+ id: tenant.id,
2886
+ kind: tenant.kind ?? "unknown",
2887
+ source: "carrier"
2888
+ }, fn);
2889
+ }
2890
+ __name(restore, "restore");
2891
+ function buildEngineTenancy(option, accessor, runtime) {
2892
+ if (option === false || !runtime) return void 0;
2893
+ return {
2894
+ current() {
2895
+ const t = readTenancy(option, accessor);
2896
+ if (!t.enabled) return void 0;
2897
+ const f = t.filter();
2898
+ return f.mode === "tenant" ? {
2899
+ id: f.tenant.id,
2900
+ kind: f.tenant.kind
2901
+ } : void 0;
2902
+ },
2903
+ filter() {
2904
+ const t = readTenancy(option, accessor);
2905
+ if (!t.enabled) return {
2906
+ mode: "system"
2907
+ };
2908
+ const f = t.filter();
2909
+ if (f.mode === "tenant") return {
2910
+ mode: "tenant",
2911
+ tenantId: f.tenant.id,
2912
+ nullRows: t.nullRows
2913
+ };
2914
+ if (f.mode === "tenantless") return {
2915
+ mode: "tenantless"
2916
+ };
2917
+ return f.mode === "all" ? {
2918
+ mode: "all"
2919
+ } : {
2920
+ mode: "system"
2921
+ };
2922
+ },
2923
+ run: /* @__PURE__ */ __name((tenant, fn) => restore(runtime, tenant, fn), "run")
2924
+ };
2925
+ }
2926
+ __name(buildEngineTenancy, "buildEngineTenancy");
2927
+ function tenantFromCarrier(carrier) {
2928
+ const ref = carrier?.tenant;
2929
+ if (ref && typeof ref.id === "string") {
2930
+ return typeof ref.kind === "string" ? {
2931
+ id: ref.id,
2932
+ kind: ref.kind
2933
+ } : {
2934
+ id: ref.id
2935
+ };
2936
+ }
2937
+ const id = carrier?.tenantId;
2938
+ return typeof id === "string" ? {
2939
+ id
2940
+ } : void 0;
2941
+ }
2942
+ __name(tenantFromCarrier, "tenantFromCarrier");
2943
+ function stepTenantWrapper(option, accessor, runtime) {
2944
+ return (execution, next) => {
2945
+ if (execution.unit !== "step") return next();
2946
+ const tenant = tenantFromCarrier(execution.context);
2947
+ if (!tenant || !readTenancy(option, accessor).enabled) return next();
2948
+ return restore(runtime, tenant, next);
2949
+ };
2950
+ }
2951
+ __name(stepTenantWrapper, "stepTenantWrapper");
2952
+
2800
2953
  // src/tenant-event-republisher.ts
2801
2954
  function isTerminalRunEvent(event) {
2802
2955
  return event.type === "run.completed" || event.type === "run.failed";
@@ -3382,11 +3535,18 @@ function carrierFromAccessor(accessor) {
3382
3535
  if (traceId !== void 0) carrier.traceId = traceId;
3383
3536
  const tenantId = accessor.tenantId();
3384
3537
  if (tenantId !== void 0) carrier.tenantId = tenantId;
3538
+ const tenant = accessor.tenant?.();
3539
+ if (tenant !== void 0 && tenant.source !== "legacy") carrier.tenant = tenant;
3385
3540
  const userRef = accessor.userRef();
3386
3541
  if (userRef !== void 0) carrier.userRef = userRef;
3387
3542
  return carrier;
3388
3543
  }
3389
3544
  __name(carrierFromAccessor, "carrierFromAccessor");
3545
+ function contextSlotPresent() {
3546
+ const slot = globalThis[Symbol.for("@dudousxd/nestjs-diagnostics:accessor")];
3547
+ return !!slot?.current;
3548
+ }
3549
+ __name(contextSlotPresent, "contextSlotPresent");
3390
3550
  function isContextRuntime(x) {
3391
3551
  return !!x && typeof x.deserialize === "function";
3392
3552
  }
@@ -3572,6 +3732,38 @@ RunGatewayBootstrap = _ts_decorate13([
3572
3732
  typeof ResolvedTenantAuth === "undefined" ? Object : ResolvedTenantAuth
3573
3733
  ])
3574
3734
  ], RunGatewayBootstrap);
3735
+ var DurableTenancyBridge = class DurableTenancyBridge2 {
3736
+ static {
3737
+ __name(this, "DurableTenancyBridge");
3738
+ }
3739
+ options;
3740
+ moduleRef;
3741
+ unregister;
3742
+ constructor(options, moduleRef) {
3743
+ this.options = options;
3744
+ this.moduleRef = moduleRef;
3745
+ }
3746
+ async onApplicationBootstrap() {
3747
+ if (this.options.tenancy === false) return;
3748
+ const accessor = resolveAccessor(this.moduleRef);
3749
+ if (!readTenancy(this.options.tenancy, accessor).enabled) return;
3750
+ const runtime = await resolveContextRuntime();
3751
+ if (!isTenantRuntime(runtime)) return;
3752
+ this.unregister = useDurableExecution(stepTenantWrapper(this.options.tenancy, accessor, runtime));
3753
+ }
3754
+ onModuleDestroy() {
3755
+ this.unregister?.();
3756
+ }
3757
+ };
3758
+ DurableTenancyBridge = _ts_decorate13([
3759
+ Injectable13(),
3760
+ _ts_param9(0, Inject9(DURABLE_OPTIONS_CANONICAL8)),
3761
+ _ts_metadata13("design:type", Function),
3762
+ _ts_metadata13("design:paramtypes", [
3763
+ typeof DurableModuleOptions === "undefined" ? Object : DurableModuleOptions,
3764
+ typeof ModuleRef2 === "undefined" ? Object : ModuleRef2
3765
+ ])
3766
+ ], DurableTenancyBridge);
3575
3767
  var DurableModule = class _DurableModule {
3576
3768
  static {
3577
3769
  __name(this, "DurableModule");
@@ -3669,7 +3861,8 @@ var DurableModule = class _DurableModule {
3669
3861
  const primary = transport ?? options.transports?.[0]?.transport;
3670
3862
  const accessor = resolveAccessor(moduleRef);
3671
3863
  const context = options.context ?? (accessor ? () => carrierFromAccessor(accessor) : void 0);
3672
- const runtime = accessor ? await resolveContextRuntime() : void 0;
3864
+ const runtimeNeeded = accessor !== void 0 || contextSlotPresent();
3865
+ const runtime = runtimeNeeded ? await resolveContextRuntime() : void 0;
3673
3866
  const rehydrate = runtime && ((carrier, fn) => carrier && Object.keys(carrier).length > 0 ? runtime.deserialize(carrier, fn) : fn());
3674
3867
  if (options.consumers === false) {
3675
3868
  for (const t of [
@@ -3707,7 +3900,9 @@ var DurableModule = class _DurableModule {
3707
3900
  webhookUrl: options.webhookUrl,
3708
3901
  traceparent: options.traceparent,
3709
3902
  context,
3710
- rehydrate: rehydrate || void 0,
3903
+ rehydrate: accessor && rehydrate || void 0,
3904
+ // The run's tenant, restored around every turn (see `tenancy` above).
3905
+ tenancy: buildEngineTenancy(options.tenancy, accessor, isTenantRuntime(runtime) ? runtime : void 0),
3711
3906
  compensationRetries: options.compensationRetries,
3712
3907
  verifyTenant: auth.verifyTenant,
3713
3908
  // A non-driving (dashboard/API) operator must not run workflows: enqueue-only, leaving
@@ -3762,6 +3957,7 @@ var DurableModule = class _DurableModule {
3762
3957
  ]
3763
3958
  },
3764
3959
  RunGatewayBootstrap,
3960
+ DurableTenancyBridge,
3765
3961
  // Co-located in-app worker (uniform dispatch): inert unless BOTH `store` and `connection` are
3766
3962
  // set — see `in-app-worker.ts`.
3767
3963
  ...inAppWorkerProviders(),