@bluelibs/runner 6.0.0 → 6.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/browser/index.cjs +452 -249
  2. package/dist/browser/index.cjs.map +1 -1
  3. package/dist/browser/index.mjs +452 -249
  4. package/dist/browser/index.mjs.map +1 -1
  5. package/dist/edge/index.cjs +452 -249
  6. package/dist/edge/index.cjs.map +1 -1
  7. package/dist/edge/index.mjs +452 -249
  8. package/dist/edge/index.mjs.map +1 -1
  9. package/dist/node/node.cjs +4047 -3842
  10. package/dist/node/node.cjs.map +1 -1
  11. package/dist/node/node.mjs +4047 -3842
  12. package/dist/node/node.mjs.map +1 -1
  13. package/dist/types/definers/assertDefinitionId.d.ts +1 -0
  14. package/dist/types/definers/builders/resource/index.d.ts +1 -3
  15. package/dist/types/definers/builders/resource/types.d.ts +0 -1
  16. package/dist/types/errors/domain-error-ids.d.ts +0 -2
  17. package/dist/types/errors/domain-runtime.errors.d.ts +0 -6
  18. package/dist/types/globals/globalResources.d.ts +4 -4
  19. package/dist/types/globals/middleware/keyBuilder.shared.d.ts +2 -0
  20. package/dist/types/globals/middleware/rateLimit.middleware.d.ts +8 -2
  21. package/dist/types/globals/middleware/temporal.middleware.d.ts +7 -26
  22. package/dist/types/globals/middleware/temporal.shared.d.ts +28 -0
  23. package/dist/types/models/Store.d.ts +1 -1
  24. package/dist/types/models/StoreRegistry.d.ts +3 -0
  25. package/dist/types/models/createFrameworkRootGateway.d.ts +3 -1
  26. package/dist/types/models/store-registry/CanonicalIdCompiler.d.ts +8 -0
  27. package/dist/types/models/store-registry/OwnerScope.d.ts +5 -0
  28. package/dist/types/models/store-registry/StoreRegistryWriter.d.ts +6 -3
  29. package/dist/types/models/store-registry/registerableKind.d.ts +19 -0
  30. package/dist/types/node/node.d.ts +2 -2
  31. package/dist/types/node/rpc-lanes/rpcLanes.resource.d.ts +1 -0
  32. package/dist/types/public.d.ts +10 -189
  33. package/dist/types/types/resource.d.ts +0 -9
  34. package/dist/types/types/subtree.d.ts +4 -2
  35. package/dist/universal/index.cjs +452 -249
  36. package/dist/universal/index.cjs.map +1 -1
  37. package/dist/universal/index.mjs +452 -249
  38. package/dist/universal/index.mjs.map +1 -1
  39. package/package.json +1 -1
  40. package/readmes/AI.md +21 -18
@@ -292,6 +292,9 @@ var init_isSameDefinition = __esm({
292
292
  function isReservedDefinitionLocalName(name) {
293
293
  return reservedDefinitionLocalNameSet.has(name);
294
294
  }
295
+ function isReservedInternalDefinitionId(id3) {
296
+ return reservedInternalDefinitionIdSet.has(id3);
297
+ }
295
298
  function canUseFrameworkDottedId(definitionId, allowReservedDottedNamespace) {
296
299
  if (!allowReservedDottedNamespace) {
297
300
  return false;
@@ -300,6 +303,9 @@ function canUseFrameworkDottedId(definitionId, allowReservedDottedNamespace) {
300
303
  (prefix) => definitionId.startsWith(prefix)
301
304
  );
302
305
  }
306
+ function canUseReservedInternalDefinitionId(allowReservedInternalId) {
307
+ return allowReservedInternalId === true;
308
+ }
303
309
  function toDisplayId(value) {
304
310
  if (typeof value === "string") {
305
311
  return value.length > 0 ? value : "<empty>";
@@ -342,8 +348,15 @@ function assertDefinitionId(definitionType, id3, options) {
342
348
  originalError: `${definitionType} id "${definitionId}" is reserved by Runner and cannot be used as a standalone id.`
343
349
  });
344
350
  }
351
+ if (isReservedInternalDefinitionId(definitionId) && !canUseReservedInternalDefinitionId(options?.allowReservedInternalId)) {
352
+ validationError.throw({
353
+ subject: `${definitionType} id`,
354
+ id: definitionId,
355
+ originalError: `${definitionType} id "${definitionId}" is reserved for internal Runner resources.`
356
+ });
357
+ }
345
358
  }
346
- var RESERVED_DEFINITION_LOCAL_NAMES, FRAMEWORK_DOTTED_ID_PREFIXES, reservedDefinitionLocalNameSet;
359
+ var RESERVED_DEFINITION_LOCAL_NAMES, RESERVED_INTERNAL_DEFINITION_IDS, FRAMEWORK_DOTTED_ID_PREFIXES, reservedDefinitionLocalNameSet, reservedInternalDefinitionIdSet;
347
360
  var init_assertDefinitionId = __esm({
348
361
  "src/definers/assertDefinitionId.ts"() {
349
362
  init_errors2();
@@ -356,6 +369,9 @@ var init_assertDefinitionId = __esm({
356
369
  "errors",
357
370
  "asyncContexts"
358
371
  ]);
372
+ RESERVED_INTERNAL_DEFINITION_IDS = Object.freeze([
373
+ "runtime-framework-root"
374
+ ]);
359
375
  FRAMEWORK_DOTTED_ID_PREFIXES = Object.freeze([
360
376
  "runner.",
361
377
  "system."
@@ -363,8 +379,13 @@ var init_assertDefinitionId = __esm({
363
379
  reservedDefinitionLocalNameSet = new Set(
364
380
  RESERVED_DEFINITION_LOCAL_NAMES
365
381
  );
382
+ reservedInternalDefinitionIdSet = new Set(
383
+ RESERVED_INTERNAL_DEFINITION_IDS
384
+ );
366
385
  __name(isReservedDefinitionLocalName, "isReservedDefinitionLocalName");
386
+ __name(isReservedInternalDefinitionId, "isReservedInternalDefinitionId");
367
387
  __name(canUseFrameworkDottedId, "canUseFrameworkDottedId");
388
+ __name(canUseReservedInternalDefinitionId, "canUseReservedInternalDefinitionId");
368
389
  __name(toDisplayId, "toDisplayId");
369
390
  __name(requireStringId, "requireStringId");
370
391
  __name(assertDefinitionId, "assertDefinitionId");
@@ -3517,8 +3538,6 @@ var init_domain_error_ids = __esm({
3517
3538
  RunnerErrorId2["RpcLaneOwnershipConflict"] = "runner.errors.rpcLane.ownershipConflict";
3518
3539
  RunnerErrorId2["RpcLaneExposureOwnerInvalid"] = "runner.errors.rpcLane.exposureOwnerInvalid";
3519
3540
  RunnerErrorId2["ResourceForkNonLeafUnsupported"] = "runner.errors.resourceFork.nonLeafUnsupported";
3520
- RunnerErrorId2["ResourceForkGatewayUnsupported"] = "runner.errors.resourceFork.gatewayUnsupported";
3521
- RunnerErrorId2["RunRootGatewayUnsupported"] = "runner.errors.run.rootGatewayUnsupported";
3522
3541
  RunnerErrorId2["BuilderInvalidHttpCode"] = "runner.errors.builder.invalidHttpCode";
3523
3542
  RunnerErrorId2["OverrideUnsupportedBase"] = "runner.errors.override.unsupportedBase";
3524
3543
  RunnerErrorId2["OverrideDefinitionRequired"] = "runner.errors.overrideDefinitionRequired";
@@ -3552,7 +3571,7 @@ var init_domain_error_ids = __esm({
3552
3571
  });
3553
3572
 
3554
3573
  // src/errors/domain-runtime.errors.ts
3555
- var httpBaseUrlRequiredError, httpFetchUnavailableError, httpContextSerializationError, httpEventWithResultUnavailableError, httpClientInputUnsupportedError, middlewareConcurrencyConflictError, middlewareContextRequiredError, middlewareTimeoutError, middlewareCircuitBreakerOpenError, middlewareRateLimitExceededError, middlewareTemporalDisposedError, rpcLaneHttpClientPresetNotFoundError, rpcLaneCommunicatorContractError, rpcLaneInvalidIdError, rpcLaneProfileNotFoundError, rpcLaneBindingNotFoundError, rpcLaneDuplicateBindingError, rpcLaneTaskAssignmentConflictError, rpcLaneEventAssignmentConflictError, rpcLaneApplyToInvalidTargetError, rpcLaneApplyToTargetTypeError, rpcLaneApplyToTargetNotFoundError, rpcLaneAssignmentEventLaneConflictError, rpcLaneCommunicatorResourceInvalidError, rpcLanesExposureModeError, rpcLanesExposureOwnerInvalidError, remoteLaneAuthSignerMissingError, remoteLaneAuthVerifierMissingError, remoteLaneAuthUnauthorizedError, resourceForkNonLeafUnsupportedError, resourceForkGatewayUnsupportedError, runRootGatewayUnsupportedError, builderInvalidHttpCodeError, overrideUnsupportedBaseError, platformUnreachableError, platformInvariantError, serializerInvalidPayloadError, serializerValidationError, serializerPayloadValidationError, serializerDepthExceededError, serializerReferenceResolutionError, serializerUnsupportedFeatureError, serializerTypeRegistryError, serializerSymbolPolicyError, nodeInputFileConsumedError, nodeInputFileUnavailableError, nodeExposureMultipartLimitExceededError, optionalDependencyInvalidExportError, optionalDependencyMissingError, durableStoreShapeError, durableQueueNotInitializedError, eventLaneQueueNotInitializedError, eventLaneInvalidIdError, eventLaneProfileNotFoundError, eventLaneBindingNotFoundError, eventLaneDuplicateBindingError, eventLaneRetryPolicyInvalidError, eventLaneQueueReferenceInvalidError, eventLaneAssignmentConflictError, eventLaneApplyToInvalidTargetError, eventLaneApplyToTargetTypeError, eventLaneApplyToTargetNotFoundError, eventLaneAssignmentRpcLaneConflictError, eventLaneEventNotRegisteredError, eventLaneMessageMalformedError, durableContextCancelledError, durableStepDefinitionError, durableDeterminismViolationError, durableSignalTimeoutError, durableScheduleConfigError, durableExecutionError, durableExecutionInvariantError, durableOperatorUnsupportedStoreCapabilityError, lockableMapLockedError;
3574
+ var httpBaseUrlRequiredError, httpFetchUnavailableError, httpContextSerializationError, httpEventWithResultUnavailableError, httpClientInputUnsupportedError, middlewareConcurrencyConflictError, middlewareContextRequiredError, middlewareTimeoutError, middlewareCircuitBreakerOpenError, middlewareRateLimitExceededError, middlewareTemporalDisposedError, rpcLaneHttpClientPresetNotFoundError, rpcLaneCommunicatorContractError, rpcLaneInvalidIdError, rpcLaneProfileNotFoundError, rpcLaneBindingNotFoundError, rpcLaneDuplicateBindingError, rpcLaneTaskAssignmentConflictError, rpcLaneEventAssignmentConflictError, rpcLaneApplyToInvalidTargetError, rpcLaneApplyToTargetTypeError, rpcLaneApplyToTargetNotFoundError, rpcLaneAssignmentEventLaneConflictError, rpcLaneCommunicatorResourceInvalidError, rpcLanesExposureModeError, rpcLanesExposureOwnerInvalidError, remoteLaneAuthSignerMissingError, remoteLaneAuthVerifierMissingError, remoteLaneAuthUnauthorizedError, resourceForkNonLeafUnsupportedError, builderInvalidHttpCodeError, overrideUnsupportedBaseError, platformUnreachableError, platformInvariantError, serializerInvalidPayloadError, serializerValidationError, serializerPayloadValidationError, serializerDepthExceededError, serializerReferenceResolutionError, serializerUnsupportedFeatureError, serializerTypeRegistryError, serializerSymbolPolicyError, nodeInputFileConsumedError, nodeInputFileUnavailableError, nodeExposureMultipartLimitExceededError, optionalDependencyInvalidExportError, optionalDependencyMissingError, durableStoreShapeError, durableQueueNotInitializedError, eventLaneQueueNotInitializedError, eventLaneInvalidIdError, eventLaneProfileNotFoundError, eventLaneBindingNotFoundError, eventLaneDuplicateBindingError, eventLaneRetryPolicyInvalidError, eventLaneQueueReferenceInvalidError, eventLaneAssignmentConflictError, eventLaneApplyToInvalidTargetError, eventLaneApplyToTargetTypeError, eventLaneApplyToTargetNotFoundError, eventLaneAssignmentRpcLaneConflictError, eventLaneEventNotRegisteredError, eventLaneMessageMalformedError, durableContextCancelledError, durableStepDefinitionError, durableDeterminismViolationError, durableSignalTimeoutError, durableScheduleConfigError, durableExecutionError, durableExecutionInvariantError, durableOperatorUnsupportedStoreCapabilityError, lockableMapLockedError;
3556
3575
  var init_domain_runtime_errors = __esm({
3557
3576
  "src/errors/domain-runtime.errors.ts"() {
3558
3577
  init_error2();
@@ -3668,7 +3687,7 @@ var init_domain_runtime_errors = __esm({
3668
3687
  'Use mode: "network" when enabling exposure.http, or remove exposure.http for transparent/local-simulated modes.'
3669
3688
  ).build();
3670
3689
  rpcLanesExposureOwnerInvalidError = frameworkError("runner.errors.rpcLane.exposureOwnerInvalid" /* RpcLaneExposureOwnerInvalid */).format(
3671
- ({ ownerResourceId }) => `RPC HTTP exposure can only be owned by "platform-node-resources-rpcLanes". Received owner "${ownerResourceId}".`
3690
+ ({ ownerResourceId }) => `RPC HTTP exposure can only be owned by "runner.node.rpcLanes". Received owner "${ownerResourceId}".`
3672
3691
  ).remediation(
3673
3692
  "Start RPC HTTP exposure only through rpcLanesResource.with({ exposure: { http: ... } }) in network mode."
3674
3693
  ).build();
@@ -3692,16 +3711,6 @@ var init_domain_runtime_errors = __esm({
3692
3711
  ).remediation(
3693
3712
  ({ id: id3 }) => `Do not call .fork() on non-leaf resource "${id3}". Compose a distinct parent resource and register distinct children explicitly. Use a dedicated factory API when the template owns a registered subtree.`
3694
3713
  ).build();
3695
- resourceForkGatewayUnsupportedError = frameworkError("runner.errors.resourceFork.gatewayUnsupported" /* ResourceForkGatewayUnsupported */).format(
3696
- ({ id: id3 }) => `Resource "${id3}" cannot be forked because gateway resources suppress their own namespace segment.`
3697
- ).remediation(
3698
- ({ id: id3 }) => `Do not call .fork() on gateway resource "${id3}". Register a distinct non-gateway resource, or compose separate gateway resources with unique registered children instead.`
3699
- ).build();
3700
- runRootGatewayUnsupportedError = frameworkError("runner.errors.run.rootGatewayUnsupported" /* RunRootGatewayUnsupported */).format(
3701
- ({ id: id3 }) => `Resource "${id3}" cannot be passed to run() because gateway resources are structural-only.`
3702
- ).remediation(
3703
- ({ id: id3 }) => `Wrap gateway resource "${id3}" in a distinct non-gateway root resource, then call run(root) instead.`
3704
- ).build();
3705
3714
  builderInvalidHttpCodeError = frameworkError("runner.errors.builder.invalidHttpCode" /* BuilderInvalidHttpCode */).format(
3706
3715
  ({ value }) => `Error httpCode must be an integer between 100 and 599. Received: ${value}`
3707
3716
  ).remediation(
@@ -3968,7 +3977,6 @@ __export(errors_exports, {
3968
3977
  remoteLaneAuthUnauthorizedError: () => remoteLaneAuthUnauthorizedError,
3969
3978
  remoteLaneAuthVerifierMissingError: () => remoteLaneAuthVerifierMissingError,
3970
3979
  resourceCooldownAdmissionTargetInvalidError: () => resourceCooldownAdmissionTargetInvalidError,
3971
- resourceForkGatewayUnsupportedError: () => resourceForkGatewayUnsupportedError,
3972
3980
  resourceForkNonLeafUnsupportedError: () => resourceForkNonLeafUnsupportedError,
3973
3981
  resourceNotFoundError: () => resourceNotFoundError,
3974
3982
  resultSchemaValidationError: () => resultSchemaValidationError,
@@ -3990,7 +3998,6 @@ __export(errors_exports, {
3990
3998
  rpcLanesExposureOwnerInvalidError: () => rpcLanesExposureOwnerInvalidError,
3991
3999
  runResultDisposeDuringBootstrapError: () => runResultDisposeDuringBootstrapError,
3992
4000
  runResultDisposedError: () => runResultDisposedError,
3993
- runRootGatewayUnsupportedError: () => runRootGatewayUnsupportedError,
3994
4001
  runtimeAccessViolationError: () => runtimeAccessViolationError,
3995
4002
  runtimeAdmissionControlDuringBootstrapError: () => runtimeAdmissionControlDuringBootstrapError,
3996
4003
  runtimeAdmissionsPausedError: () => runtimeAdmissionsPausedError,
@@ -4611,6 +4618,21 @@ function normalizeResourceSubtreePolicy(policy) {
4611
4618
  return normalized;
4612
4619
  }
4613
4620
  __name(normalizeResourceSubtreePolicy, "normalizeResourceSubtreePolicy");
4621
+ function toSubtreePolicyArray(policy) {
4622
+ if (policy === void 0) {
4623
+ return [];
4624
+ }
4625
+ return Array.isArray(policy) ? [...policy] : [policy];
4626
+ }
4627
+ __name(toSubtreePolicyArray, "toSubtreePolicyArray");
4628
+ function mergeSubtreePolicyList(existing, incoming, options) {
4629
+ let merged = cloneNormalizedSubtreePolicy(existing);
4630
+ for (const policy of toSubtreePolicyArray(incoming)) {
4631
+ merged = mergeResourceSubtreePolicy(merged, policy, options);
4632
+ }
4633
+ return merged;
4634
+ }
4635
+ __name(mergeSubtreePolicyList, "mergeSubtreePolicyList");
4614
4636
  function mergeSubtreeMiddlewareBranch(existing, incoming, override) {
4615
4637
  if (!existing || override) {
4616
4638
  return {
@@ -4730,8 +4752,8 @@ __name(mergeResourceSubtreeDeclarations, "mergeResourceSubtreeDeclarations");
4730
4752
  function resolveResourceSubtreeDeclarations(declarations, config) {
4731
4753
  let merged;
4732
4754
  for (const declaration of declarations ?? []) {
4733
- const policy = typeof declaration.policy === "function" ? declaration.policy(config) : declaration.policy;
4734
- merged = mergeResourceSubtreePolicy(merged, policy, declaration.options);
4755
+ const policyList = typeof declaration.policy === "function" ? declaration.policy(config) : declaration.policy;
4756
+ merged = mergeSubtreePolicyList(merged, policyList, declaration.options);
4735
4757
  }
4736
4758
  return merged;
4737
4759
  }
@@ -4746,7 +4768,7 @@ function createDisplaySubtreePolicy(declarations) {
4746
4768
  if (!hasDynamic) {
4747
4769
  let merged;
4748
4770
  for (const declaration of declarations) {
4749
- merged = mergeResourceSubtreePolicy(
4771
+ merged = mergeSubtreePolicyList(
4750
4772
  merged,
4751
4773
  declaration.policy,
4752
4774
  declaration.options
@@ -4910,7 +4932,8 @@ function defineResource(constConfig) {
4910
4932
  const filePath = constConfig[symbolFilePath] || getCallerFile();
4911
4933
  const id3 = constConfig.id;
4912
4934
  assertDefinitionId("Resource", id3, {
4913
- allowReservedDottedNamespace: isFrameworkDefinitionMarked(constConfig)
4935
+ allowReservedDottedNamespace: isFrameworkDefinitionMarked(constConfig),
4936
+ allowReservedInternalId: isFrameworkDefinitionMarked(constConfig)
4914
4937
  });
4915
4938
  const configSchema = normalizeOptionalValidationSchema(
4916
4939
  constConfig.configSchema,
@@ -4936,7 +4959,6 @@ function defineResource(constConfig) {
4936
4959
  [symbolResourceRegistersChildren]: constConfig.register !== void 0 ? true : void 0,
4937
4960
  [symbolFilePath]: filePath,
4938
4961
  id: id3,
4939
- gateway: constConfig.gateway === true,
4940
4962
  dependencies: constConfig.dependencies,
4941
4963
  dispose: constConfig.dispose,
4942
4964
  ready: constConfig.ready,
@@ -4983,8 +5005,7 @@ function defineResource(constConfig) {
4983
5005
  isolate: current.isolate,
4984
5006
  subtree: current.subtree,
4985
5007
  [symbolResourceIsolateDeclarations]: current[symbolResourceIsolateDeclarations],
4986
- [symbolResourceSubtreeDeclarations]: current[symbolResourceSubtreeDeclarations],
4987
- gateway: current.gateway
5008
+ [symbolResourceSubtreeDeclarations]: current[symbolResourceSubtreeDeclarations]
4988
5009
  }), "buildDefinition");
4989
5010
  base.with = function(config) {
4990
5011
  const current = resolveCurrent(this);
@@ -5021,9 +5042,6 @@ function defineResource(constConfig) {
5021
5042
  if (current[symbolResourceRegistersChildren] === true) {
5022
5043
  resourceForkNonLeafUnsupportedError.throw({ id: current.id });
5023
5044
  }
5024
- if (current.gateway === true) {
5025
- resourceForkGatewayUnsupportedError.throw({ id: current.id });
5026
- }
5027
5045
  const forkCallerFilePath = getCallerFile();
5028
5046
  const forked = defineResource({
5029
5047
  ...buildDefinition(current),
@@ -10158,9 +10176,15 @@ init_defineError();
10158
10176
  init_errors2();
10159
10177
  init_check();
10160
10178
  init_symbols();
10179
+
10180
+ // src/globals/middleware/keyBuilder.shared.ts
10181
+ var defaultTaskKeyBuilder = /* @__PURE__ */ __name((taskId) => taskId, "defaultTaskKeyBuilder");
10182
+
10183
+ // src/globals/middleware/rateLimit.middleware.ts
10161
10184
  var rateLimitConfigPattern = exports.Match.ObjectIncluding({
10162
10185
  windowMs: exports.Match.PositiveInteger,
10163
- max: exports.Match.PositiveInteger
10186
+ max: exports.Match.PositiveInteger,
10187
+ keyBuilder: exports.Match.Optional(Function)
10164
10188
  });
10165
10189
  var RateLimitError = class extends exports.RunnerError {
10166
10190
  static {
@@ -10177,6 +10201,7 @@ var RateLimitError = class extends exports.RunnerError {
10177
10201
  );
10178
10202
  }
10179
10203
  };
10204
+ var RATE_LIMIT_STATE_PRUNE_THRESHOLD = 1e3;
10180
10205
  var journalKeys3 = {
10181
10206
  /** Number of remaining requests in the current window */
10182
10207
  remaining: journal.createKey(
@@ -10202,6 +10227,17 @@ var rateLimitResource = defineResource(
10202
10227
  }, "init")
10203
10228
  })
10204
10229
  );
10230
+ function pruneExpiredRateLimitStates(keyedStates, now) {
10231
+ if (keyedStates.size < RATE_LIMIT_STATE_PRUNE_THRESHOLD) {
10232
+ return;
10233
+ }
10234
+ for (const [key, keyedState] of keyedStates) {
10235
+ if (now >= keyedState.resetTime) {
10236
+ keyedStates.delete(key);
10237
+ }
10238
+ }
10239
+ }
10240
+ __name(pruneExpiredRateLimitStates, "pruneExpiredRateLimitStates");
10205
10241
  var rateLimitTaskMiddleware = defineTaskMiddleware(
10206
10242
  markFrameworkDefinition({
10207
10243
  id: "runner.middleware.task.rateLimit",
@@ -10209,15 +10245,24 @@ var rateLimitTaskMiddleware = defineTaskMiddleware(
10209
10245
  configSchema: rateLimitConfigPattern,
10210
10246
  dependencies: { state: rateLimitResource },
10211
10247
  async run({ task: task2, next, journal: journal2 }, { state }, config) {
10248
+ const taskId = task2.definition.id;
10249
+ const keyBuilder = config.keyBuilder ?? defaultTaskKeyBuilder;
10250
+ const key = keyBuilder(taskId, task2.input);
10212
10251
  const { states } = state;
10213
- let limitState = states.get(config);
10214
10252
  const now = Date.now();
10253
+ let keyedStates = states.get(config);
10254
+ if (!keyedStates) {
10255
+ keyedStates = /* @__PURE__ */ new Map();
10256
+ states.set(config, keyedStates);
10257
+ }
10258
+ pruneExpiredRateLimitStates(keyedStates, now);
10259
+ let limitState = keyedStates.get(key);
10215
10260
  if (!limitState || now >= limitState.resetTime) {
10216
10261
  limitState = {
10217
10262
  count: 0,
10218
10263
  resetTime: now + config.windowMs
10219
10264
  };
10220
- states.set(config, limitState);
10265
+ keyedStates.set(key, limitState);
10221
10266
  }
10222
10267
  const remaining = Math.max(0, config.max - limitState.count);
10223
10268
  journal2.set(journalKeys3.remaining, remaining, { override: true });
@@ -10245,16 +10290,9 @@ var rateLimitTaskMiddleware = defineTaskMiddleware(
10245
10290
  init_markFrameworkDefinition();
10246
10291
  init_errors2();
10247
10292
  init_check();
10248
- var temporalConfigPattern = exports.Match.ObjectIncluding({
10249
- ms: exports.Match.PositiveInteger
10250
- });
10251
- var TEMPORAL_DISPOSED_ERROR_MESSAGE = "Temporal middleware resource has been disposed.";
10252
- function createTemporalDisposedError() {
10253
- return middlewareTemporalDisposedError.new({
10254
- message: TEMPORAL_DISPOSED_ERROR_MESSAGE
10255
- });
10256
- }
10257
- __name(createTemporalDisposedError, "createTemporalDisposedError");
10293
+
10294
+ // src/globals/middleware/temporal.shared.ts
10295
+ var TEMPORAL_STATE_PRUNE_THRESHOLD = 1e3;
10258
10296
  function rejectDebounceState(state, error2) {
10259
10297
  if (state.timeoutId) {
10260
10298
  clearTimeout(state.timeoutId);
@@ -10284,6 +10322,62 @@ function rejectThrottleState(state, error2) {
10284
10322
  });
10285
10323
  }
10286
10324
  __name(rejectThrottleState, "rejectThrottleState");
10325
+ function pruneIdleThrottleStates(keyedStates, trackedStates, now, windowMs) {
10326
+ if (keyedStates.size < TEMPORAL_STATE_PRUNE_THRESHOLD) {
10327
+ return;
10328
+ }
10329
+ for (const [key, throttleState] of keyedStates) {
10330
+ const isIdle = throttleState.timeoutId === void 0 && throttleState.currentPromise === void 0 && throttleState.resolveList.length === 0 && throttleState.rejectList.length === 0 && now - throttleState.lastExecution >= windowMs;
10331
+ if (isIdle) {
10332
+ trackedStates.delete(throttleState);
10333
+ keyedStates.delete(key);
10334
+ }
10335
+ }
10336
+ }
10337
+ __name(pruneIdleThrottleStates, "pruneIdleThrottleStates");
10338
+
10339
+ // src/globals/middleware/temporal.middleware.ts
10340
+ var temporalConfigPattern = exports.Match.ObjectIncluding({
10341
+ ms: exports.Match.PositiveInteger,
10342
+ keyBuilder: exports.Match.Optional(Function)
10343
+ });
10344
+ var TEMPORAL_DISPOSED_ERROR_MESSAGE = "Temporal middleware resource has been disposed.";
10345
+ function createTemporalDisposedError() {
10346
+ return middlewareTemporalDisposedError.new({
10347
+ message: TEMPORAL_DISPOSED_ERROR_MESSAGE
10348
+ });
10349
+ }
10350
+ __name(createTemporalDisposedError, "createTemporalDisposedError");
10351
+ function buildTemporalMiddlewareKey(config, taskId, input) {
10352
+ const key = (config.keyBuilder ?? defaultTaskKeyBuilder)(taskId, input);
10353
+ if (typeof key !== "string") {
10354
+ validationError.throw({
10355
+ subject: "Middleware config",
10356
+ id: taskId,
10357
+ originalError: `Temporal middleware keyBuilder must return a string. Received ${typeof key}.`
10358
+ });
10359
+ }
10360
+ return key;
10361
+ }
10362
+ __name(buildTemporalMiddlewareKey, "buildTemporalMiddlewareKey");
10363
+ function getDebounceStatesForConfig(state, config) {
10364
+ let keyedStates = state.debounceStates.get(config);
10365
+ if (!keyedStates) {
10366
+ keyedStates = /* @__PURE__ */ new Map();
10367
+ state.debounceStates.set(config, keyedStates);
10368
+ }
10369
+ return keyedStates;
10370
+ }
10371
+ __name(getDebounceStatesForConfig, "getDebounceStatesForConfig");
10372
+ function getThrottleStatesForConfig(state, config) {
10373
+ let keyedStates = state.throttleStates.get(config);
10374
+ if (!keyedStates) {
10375
+ keyedStates = /* @__PURE__ */ new Map();
10376
+ state.throttleStates.set(config, keyedStates);
10377
+ }
10378
+ return keyedStates;
10379
+ }
10380
+ __name(getThrottleStatesForConfig, "getThrottleStatesForConfig");
10287
10381
  var temporalResource = defineResource(
10288
10382
  markFrameworkDefinition({
10289
10383
  id: "runner.temporal",
@@ -10323,15 +10417,18 @@ var debounceTaskMiddleware = defineTaskMiddleware(
10323
10417
  if (state.isDisposed === true) {
10324
10418
  throw createTemporalDisposedError();
10325
10419
  }
10326
- const debounceStates = state.debounceStates;
10420
+ const taskId = task2.definition.id;
10421
+ const key = buildTemporalMiddlewareKey(config, taskId, task2.input);
10422
+ const debounceStates = getDebounceStatesForConfig(state, config);
10327
10423
  const trackedDebounceStates = state.trackedDebounceStates;
10328
- let debounceState = debounceStates.get(config);
10424
+ let debounceState = debounceStates.get(key);
10329
10425
  if (!debounceState) {
10330
10426
  debounceState = {
10427
+ key,
10331
10428
  resolveList: [],
10332
10429
  rejectList: []
10333
10430
  };
10334
- debounceStates.set(config, debounceState);
10431
+ debounceStates.set(key, debounceState);
10335
10432
  trackedDebounceStates.add(debounceState);
10336
10433
  }
10337
10434
  debounceState.latestInput = task2.input;
@@ -10348,6 +10445,8 @@ var debounceTaskMiddleware = defineTaskMiddleware(
10348
10445
  debounceState.resolveList = [];
10349
10446
  debounceState.rejectList = [];
10350
10447
  debounceState.latestInput = void 0;
10448
+ debounceStates.delete(debounceState.key);
10449
+ trackedDebounceStates.delete(debounceState);
10351
10450
  if (state.isDisposed === true) {
10352
10451
  const disposeError = createTemporalDisposedError();
10353
10452
  rejectList.forEach((reject) => {
@@ -10380,16 +10479,25 @@ var throttleTaskMiddleware = defineTaskMiddleware(
10380
10479
  if (state.isDisposed === true) {
10381
10480
  throw createTemporalDisposedError();
10382
10481
  }
10383
- const throttleStates = state.throttleStates;
10482
+ const taskId = task2.definition.id;
10483
+ const key = buildTemporalMiddlewareKey(config, taskId, task2.input);
10484
+ const throttleStates = getThrottleStatesForConfig(state, config);
10384
10485
  const trackedThrottleStates = state.trackedThrottleStates;
10385
- let throttleState = throttleStates.get(config);
10486
+ pruneIdleThrottleStates(
10487
+ throttleStates,
10488
+ trackedThrottleStates,
10489
+ Date.now(),
10490
+ config.ms
10491
+ );
10492
+ let throttleState = throttleStates.get(key);
10386
10493
  if (!throttleState) {
10387
10494
  throttleState = {
10495
+ key,
10388
10496
  lastExecution: 0,
10389
10497
  resolveList: [],
10390
10498
  rejectList: []
10391
10499
  };
10392
- throttleStates.set(config, throttleState);
10500
+ throttleStates.set(key, throttleState);
10393
10501
  trackedThrottleStates.add(throttleState);
10394
10502
  }
10395
10503
  const now = Date.now();
@@ -17887,8 +17995,9 @@ var StoreRegistryTagIndex = class {
17887
17995
 
17888
17996
  // src/models/store-registry/StoreRegistryWriter.ts
17889
17997
  init_errors2();
17998
+
17999
+ // src/models/store-registry/registerableKind.ts
17890
18000
  init_symbols();
17891
- init_assertDefinitionId();
17892
18001
  function hasSymbolBrand(item, symbolKey) {
17893
18002
  if (item === null || item === void 0) {
17894
18003
  return false;
@@ -17934,6 +18043,190 @@ function resolveRegisterableKind(item) {
17934
18043
  return null;
17935
18044
  }
17936
18045
  __name(resolveRegisterableKind, "resolveRegisterableKind");
18046
+
18047
+ // src/models/store-registry/CanonicalIdCompiler.ts
18048
+ init_errors2();
18049
+ init_assertDefinitionId();
18050
+ var CanonicalIdCompiler = class {
18051
+ static {
18052
+ __name(this, "CanonicalIdCompiler");
18053
+ }
18054
+ compute(ownerScope, kind, currentId) {
18055
+ this.assertLocalName(ownerScope.resourceId, kind, currentId);
18056
+ if (currentId.startsWith(`${ownerScope.resourceId}.`)) {
18057
+ return currentId;
18058
+ }
18059
+ if (ownerScope.usesFrameworkRootIds) {
18060
+ return this.computeFrameworkRootId(kind, currentId);
18061
+ }
18062
+ return this.computeOwnedId(ownerScope.resourceId, kind, currentId);
18063
+ }
18064
+ computeFrameworkRootId(kind, currentId) {
18065
+ switch (kind) {
18066
+ case "resource" /* Resource */:
18067
+ return currentId;
18068
+ case "task" /* Task */:
18069
+ return `tasks.${currentId}`;
18070
+ case "event" /* Event */:
18071
+ return `events.${currentId}`;
18072
+ case "hook" /* Hook */:
18073
+ return `hooks.${currentId}`;
18074
+ case "taskMiddleware" /* TaskMiddleware */:
18075
+ return `middleware.task.${currentId}`;
18076
+ case "resourceMiddleware" /* ResourceMiddleware */:
18077
+ return `middleware.resource.${currentId}`;
18078
+ case "tag" /* Tag */:
18079
+ return `tags.${currentId}`;
18080
+ case "error" /* Error */:
18081
+ return `errors.${currentId}`;
18082
+ case "asyncContext" /* AsyncContext */:
18083
+ return `asyncContexts.${currentId}`;
18084
+ default:
18085
+ return currentId;
18086
+ }
18087
+ }
18088
+ computeOwnedId(ownerResourceId, kind, currentId) {
18089
+ switch (kind) {
18090
+ case "resource" /* Resource */:
18091
+ return `${ownerResourceId}.${currentId}`;
18092
+ case "task" /* Task */:
18093
+ return `${ownerResourceId}.tasks.${currentId}`;
18094
+ case "event" /* Event */:
18095
+ return `${ownerResourceId}.events.${currentId}`;
18096
+ case "hook" /* Hook */:
18097
+ return `${ownerResourceId}.hooks.${currentId}`;
18098
+ case "taskMiddleware" /* TaskMiddleware */:
18099
+ return `${ownerResourceId}.middleware.task.${currentId}`;
18100
+ case "resourceMiddleware" /* ResourceMiddleware */:
18101
+ return `${ownerResourceId}.middleware.resource.${currentId}`;
18102
+ case "tag" /* Tag */:
18103
+ return `${ownerResourceId}.tags.${currentId}`;
18104
+ case "error" /* Error */:
18105
+ return `${ownerResourceId}.errors.${currentId}`;
18106
+ case "asyncContext" /* AsyncContext */:
18107
+ return `${ownerResourceId}.asyncContexts.${currentId}`;
18108
+ default:
18109
+ return `${ownerResourceId}.${currentId}`;
18110
+ }
18111
+ }
18112
+ assertLocalName(ownerResourceId, kind, currentId) {
18113
+ if (currentId.trim().length === 0) {
18114
+ validationError.throw({
18115
+ subject: "Definition local name",
18116
+ id: `${ownerResourceId}.${kind}`,
18117
+ originalError: "Definition local names must be non-empty strings when using scoped registration."
18118
+ });
18119
+ }
18120
+ if (isReservedDefinitionLocalName(currentId)) {
18121
+ validationError.throw({
18122
+ subject: "Definition local name",
18123
+ id: `${ownerResourceId}.${kind}.${currentId}`,
18124
+ originalError: `Local name "${currentId}" is reserved by Runner and cannot be used.`
18125
+ });
18126
+ }
18127
+ }
18128
+ };
18129
+
18130
+ // src/models/createFrameworkRootGateway.ts
18131
+ init_markFrameworkDefinition();
18132
+
18133
+ // src/models/BuiltinsRegistry.ts
18134
+ init_errors2();
18135
+ function collectUniqueTags() {
18136
+ const uniqueTags = [];
18137
+ const seenIds = /* @__PURE__ */ new Set();
18138
+ for (const tag2 of Object.values(globalTags)) {
18139
+ if (seenIds.has(tag2.id)) {
18140
+ continue;
18141
+ }
18142
+ seenIds.add(tag2.id);
18143
+ uniqueTags.push(tag2);
18144
+ }
18145
+ return uniqueTags;
18146
+ }
18147
+ __name(collectUniqueTags, "collectUniqueTags");
18148
+ var SYSTEM_FRAMEWORK_ITEMS = Object.freeze([
18149
+ globalResources.store,
18150
+ globalResources.eventManager,
18151
+ globalResources.taskRunner,
18152
+ globalResources.middlewareManager,
18153
+ globalResources.runtime,
18154
+ ...collectUniqueTags().filter((tag2) => tag2.id.startsWith("system.")),
18155
+ ...globalEventsArray
18156
+ ]);
18157
+ var RUNNER_FRAMEWORK_ITEMS = Object.freeze([
18158
+ globalResources.health,
18159
+ globalResources.timers,
18160
+ globalResources.logger,
18161
+ globalResources.serializer,
18162
+ globalResources.queue,
18163
+ ...collectUniqueTags().filter((tag2) => tag2.id.startsWith("runner.")),
18164
+ requireContextTaskMiddleware,
18165
+ retryTaskMiddleware,
18166
+ timeoutTaskMiddleware,
18167
+ concurrencyTaskMiddleware,
18168
+ debounceTaskMiddleware,
18169
+ throttleTaskMiddleware,
18170
+ fallbackTaskMiddleware,
18171
+ rateLimitTaskMiddleware,
18172
+ circuitBreakerMiddleware,
18173
+ retryResourceMiddleware,
18174
+ timeoutResourceMiddleware,
18175
+ rateLimitResource,
18176
+ circuitBreakerResource,
18177
+ temporalResource,
18178
+ concurrencyResource,
18179
+ middlewareTimeoutError,
18180
+ middlewareCircuitBreakerOpenError,
18181
+ middlewareRateLimitExceededError,
18182
+ durableExecutionError
18183
+ ]);
18184
+
18185
+ // src/models/createFrameworkRootGateway.ts
18186
+ var FRAMEWORK_RUNNER_RESOURCE_ID = "runner";
18187
+ var FRAMEWORK_SYSTEM_RESOURCE_ID = "system";
18188
+ var FRAMEWORK_ROOT_RESOURCE_ID = "runtime-framework-root";
18189
+ function createFrameworkNamespaceResource(resourceId, register) {
18190
+ return defineResource(
18191
+ markFrameworkDefinition({
18192
+ id: resourceId,
18193
+ register: [...register]
18194
+ })
18195
+ );
18196
+ }
18197
+ __name(createFrameworkNamespaceResource, "createFrameworkNamespaceResource");
18198
+ function createFrameworkRootResource({
18199
+ rootItem,
18200
+ debug: debug3
18201
+ }) {
18202
+ const runnerRegister = debug3 ? [...RUNNER_FRAMEWORK_ITEMS, debugResource.with(debug3)] : [...RUNNER_FRAMEWORK_ITEMS];
18203
+ const systemResource = createFrameworkNamespaceResource(
18204
+ FRAMEWORK_SYSTEM_RESOURCE_ID,
18205
+ SYSTEM_FRAMEWORK_ITEMS
18206
+ );
18207
+ const runnerResource = createFrameworkNamespaceResource(
18208
+ FRAMEWORK_RUNNER_RESOURCE_ID,
18209
+ runnerRegister
18210
+ );
18211
+ return defineResource(
18212
+ markFrameworkDefinition({
18213
+ id: FRAMEWORK_ROOT_RESOURCE_ID,
18214
+ register: [systemResource, runnerResource, rootItem]
18215
+ })
18216
+ );
18217
+ }
18218
+ __name(createFrameworkRootResource, "createFrameworkRootResource");
18219
+
18220
+ // src/models/store-registry/OwnerScope.ts
18221
+ function createOwnerScope(resourceId) {
18222
+ return {
18223
+ resourceId,
18224
+ usesFrameworkRootIds: resourceId === FRAMEWORK_ROOT_RESOURCE_ID
18225
+ };
18226
+ }
18227
+ __name(createOwnerScope, "createOwnerScope");
18228
+
18229
+ // src/models/store-registry/StoreRegistryWriter.ts
17937
18230
  var StoreRegistryWriter = class {
17938
18231
  constructor(collections, validator, visibilityTracker, tagIndex, definitionPreparer, aliasResolver) {
17939
18232
  this.collections = collections;
@@ -17942,6 +18235,7 @@ var StoreRegistryWriter = class {
17942
18235
  this.tagIndex = tagIndex;
17943
18236
  this.definitionPreparer = definitionPreparer;
17944
18237
  this.aliasResolver = aliasResolver;
18238
+ this.canonicalIdCompiler = new CanonicalIdCompiler();
17945
18239
  }
17946
18240
  static {
17947
18241
  __name(this, "StoreRegistryWriter");
@@ -18144,8 +18438,9 @@ var StoreRegistryWriter = class {
18144
18438
  const registerEntries = typeof element.register === "function" ? element.register(config) : element.register;
18145
18439
  const items = registerEntries ?? [];
18146
18440
  this.assignNormalizedRegisterEntries(element, items);
18441
+ const ownerScope = createOwnerScope(element.id);
18147
18442
  const scopedItems = items.map(
18148
- (item) => this.compileOwnedItem(element.id, element.gateway === true, item)
18443
+ (item) => this.compileOwnedItem(ownerScope, item)
18149
18444
  );
18150
18445
  for (const item of scopedItems) {
18151
18446
  this.visibilityTracker.recordOwnership(element.id, item);
@@ -18167,16 +18462,15 @@ var StoreRegistryWriter = class {
18167
18462
  }
18168
18463
  element.register = items;
18169
18464
  }
18170
- compileOwnedItem(ownerResourceId, ownerIsGateway, item) {
18465
+ compileOwnedItem(ownerScope, item) {
18171
18466
  const kind = resolveRegisterableKind(item);
18172
18467
  if (!kind) {
18173
18468
  return item;
18174
18469
  }
18175
18470
  if (kind === "resourceWithConfig" /* ResourceWithConfig */) {
18176
18471
  const withConfig = item;
18177
- const compiledResource = this.compileOwnedDefinition(
18178
- ownerResourceId,
18179
- ownerIsGateway,
18472
+ const compiledResource = this.compileOwnedDefinitionWithScope(
18473
+ ownerScope,
18180
18474
  withConfig.resource,
18181
18475
  "resource" /* Resource */
18182
18476
  );
@@ -18200,9 +18494,8 @@ var StoreRegistryWriter = class {
18200
18494
  );
18201
18495
  return compiledWithConfig;
18202
18496
  }
18203
- const compiled = this.compileOwnedDefinition(
18204
- ownerResourceId,
18205
- ownerIsGateway,
18497
+ const compiled = this.compileOwnedDefinitionWithScope(
18498
+ ownerScope,
18206
18499
  item,
18207
18500
  kind
18208
18501
  );
@@ -18211,11 +18504,10 @@ var StoreRegistryWriter = class {
18211
18504
  this.aliasResolver.registerDefinitionAlias(compiled, resolvedId);
18212
18505
  return compiled;
18213
18506
  }
18214
- compileOwnedDefinition(ownerResourceId, ownerIsGateway, item, kind) {
18507
+ compileOwnedDefinitionWithScope(ownerScope, item, kind) {
18215
18508
  const currentId = item.id;
18216
- const nextId = this.computeCanonicalId(
18217
- ownerResourceId,
18218
- ownerIsGateway,
18509
+ const nextId = this.canonicalIdCompiler.compute(
18510
+ ownerScope,
18219
18511
  kind,
18220
18512
  currentId
18221
18513
  );
@@ -18227,6 +18519,26 @@ var StoreRegistryWriter = class {
18227
18519
  nextId
18228
18520
  );
18229
18521
  }
18522
+ computeCanonicalId(ownerResourceId, ownerUsesFrameworkRootIds, kind, currentId) {
18523
+ return this.canonicalIdCompiler.compute(
18524
+ {
18525
+ resourceId: ownerResourceId,
18526
+ usesFrameworkRootIds: ownerUsesFrameworkRootIds
18527
+ },
18528
+ kind,
18529
+ currentId
18530
+ );
18531
+ }
18532
+ compileOwnedDefinition(ownerResourceId, ownerUsesFrameworkRootIds, item, kind) {
18533
+ return this.compileOwnedDefinitionWithScope(
18534
+ {
18535
+ resourceId: ownerResourceId,
18536
+ usesFrameworkRootIds: ownerUsesFrameworkRootIds
18537
+ },
18538
+ item,
18539
+ kind
18540
+ );
18541
+ }
18230
18542
  cloneDefinitionWithId(definition, id3) {
18231
18543
  const clone10 = Object.create(
18232
18544
  Object.getPrototypeOf(definition)
@@ -18256,79 +18568,11 @@ var StoreRegistryWriter = class {
18256
18568
  configurable: true
18257
18569
  });
18258
18570
  }
18259
- computeCanonicalId(ownerResourceId, ownerIsGateway, kind, currentId) {
18260
- this.assertLocalName(ownerResourceId, kind, currentId);
18261
- if (currentId.startsWith(`${ownerResourceId}.`)) {
18262
- return currentId;
18263
- }
18264
- if (ownerIsGateway) {
18265
- switch (kind) {
18266
- case "resource" /* Resource */:
18267
- return currentId;
18268
- case "task" /* Task */:
18269
- return `tasks.${currentId}`;
18270
- case "event" /* Event */:
18271
- return `events.${currentId}`;
18272
- case "hook" /* Hook */:
18273
- return `hooks.${currentId}`;
18274
- case "taskMiddleware" /* TaskMiddleware */:
18275
- return `middleware.task.${currentId}`;
18276
- case "resourceMiddleware" /* ResourceMiddleware */:
18277
- return `middleware.resource.${currentId}`;
18278
- case "tag" /* Tag */:
18279
- return `tags.${currentId}`;
18280
- case "error" /* Error */:
18281
- return `errors.${currentId}`;
18282
- case "asyncContext" /* AsyncContext */:
18283
- return `asyncContexts.${currentId}`;
18284
- default:
18285
- return currentId;
18286
- }
18287
- }
18288
- switch (kind) {
18289
- case "resource" /* Resource */:
18290
- return `${ownerResourceId}.${currentId}`;
18291
- case "task" /* Task */:
18292
- return `${ownerResourceId}.tasks.${currentId}`;
18293
- case "event" /* Event */:
18294
- return `${ownerResourceId}.events.${currentId}`;
18295
- case "hook" /* Hook */:
18296
- return `${ownerResourceId}.hooks.${currentId}`;
18297
- case "taskMiddleware" /* TaskMiddleware */:
18298
- return `${ownerResourceId}.middleware.task.${currentId}`;
18299
- case "resourceMiddleware" /* ResourceMiddleware */:
18300
- return `${ownerResourceId}.middleware.resource.${currentId}`;
18301
- case "tag" /* Tag */:
18302
- return `${ownerResourceId}.tags.${currentId}`;
18303
- case "error" /* Error */:
18304
- return `${ownerResourceId}.errors.${currentId}`;
18305
- case "asyncContext" /* AsyncContext */:
18306
- return `${ownerResourceId}.asyncContexts.${currentId}`;
18307
- default:
18308
- return `${ownerResourceId}.${currentId}`;
18309
- }
18310
- }
18311
- assertLocalName(ownerResourceId, kind, currentId) {
18312
- if (currentId.trim().length === 0) {
18313
- validationError.throw({
18314
- subject: "Definition local name",
18315
- id: `${ownerResourceId}.${kind}`,
18316
- originalError: "Definition local names must be non-empty strings when using scoped registration."
18317
- });
18318
- }
18319
- if (isReservedDefinitionLocalName(currentId)) {
18320
- validationError.throw({
18321
- subject: "Definition local name",
18322
- id: `${ownerResourceId}.${kind}.${currentId}`,
18323
- originalError: `Local name "${currentId}" is reserved by Runner and cannot be used.`
18324
- });
18325
- }
18326
- }
18327
18571
  resolveRegisterableId(item) {
18328
18572
  if (item === null || item === void 0) {
18329
18573
  return void 0;
18330
18574
  }
18331
- if (hasSymbolBrand(item, symbolResourceWithConfig)) {
18575
+ if (resolveRegisterableKind(item) === "resourceWithConfig" /* ResourceWithConfig */) {
18332
18576
  return item.resource.id;
18333
18577
  }
18334
18578
  if (typeof item === "object" && "id" in item) {
@@ -18407,15 +18651,16 @@ var StoreRegistryWriter = class {
18407
18651
  this.visibilityTracker.recordDefinitionTags(task2.id, tags2);
18408
18652
  }
18409
18653
  normalizeTaskMiddlewareAttachments(task2) {
18654
+ const ownerResourceId = this.resolveOwnerResourceIdFromTaskId(task2.id);
18410
18655
  return this.normalizeMiddlewareAttachments(
18411
- this.resolveOwnerResourceIdFromTaskId(task2.id),
18656
+ ownerResourceId ? createOwnerScope(ownerResourceId) : null,
18412
18657
  "taskMiddleware" /* TaskMiddleware */,
18413
18658
  task2.middleware
18414
18659
  );
18415
18660
  }
18416
18661
  normalizeResourceMiddlewareAttachments(resource2) {
18417
18662
  return this.normalizeMiddlewareAttachments(
18418
- resource2.id,
18663
+ createOwnerScope(resource2.id),
18419
18664
  "resourceMiddleware" /* ResourceMiddleware */,
18420
18665
  resource2.middleware
18421
18666
  );
@@ -18433,7 +18678,10 @@ var StoreRegistryWriter = class {
18433
18678
  let normalizedResourcePolicy = subtree.resources;
18434
18679
  if (subtree.tasks?.middleware?.length) {
18435
18680
  const middleware2 = subtree.tasks.middleware.map(
18436
- (entry) => this.normalizeSubtreeTaskMiddlewareEntry(resource2.id, entry)
18681
+ (entry) => this.normalizeSubtreeTaskMiddlewareEntry(
18682
+ createOwnerScope(resource2.id),
18683
+ entry
18684
+ )
18437
18685
  );
18438
18686
  if (this.didArrayChange(subtree.tasks.middleware, middleware2)) {
18439
18687
  normalizedTaskPolicy = {
@@ -18445,7 +18693,10 @@ var StoreRegistryWriter = class {
18445
18693
  }
18446
18694
  if (subtree.resources?.middleware?.length) {
18447
18695
  const middleware2 = subtree.resources.middleware.map(
18448
- (entry) => this.normalizeSubtreeResourceMiddlewareEntry(resource2.id, entry)
18696
+ (entry) => this.normalizeSubtreeResourceMiddlewareEntry(
18697
+ createOwnerScope(resource2.id),
18698
+ entry
18699
+ )
18449
18700
  );
18450
18701
  if (this.didArrayChange(subtree.resources.middleware, middleware2)) {
18451
18702
  normalizedResourcePolicy = {
@@ -18464,37 +18715,47 @@ var StoreRegistryWriter = class {
18464
18715
  ...normalizedResourcePolicy ? { resources: normalizedResourcePolicy } : {}
18465
18716
  };
18466
18717
  }
18467
- normalizeSubtreeTaskMiddlewareEntry(ownerResourceId, entry) {
18718
+ normalizeSubtreeTaskMiddlewareEntry(ownerScopeOrResourceId, entryOrUsesFrameworkRootIds, maybeEntry) {
18719
+ const ownerScope = this.normalizeOwnerScopeArg(
18720
+ ownerScopeOrResourceId,
18721
+ entryOrUsesFrameworkRootIds
18722
+ );
18723
+ const entry = maybeEntry ?? entryOrUsesFrameworkRootIds;
18468
18724
  return this.normalizeSubtreeMiddlewareEntry(
18469
- ownerResourceId,
18725
+ ownerScope,
18470
18726
  "taskMiddleware" /* TaskMiddleware */,
18471
18727
  entry,
18472
18728
  getSubtreeTaskMiddlewareAttachment
18473
18729
  );
18474
18730
  }
18475
- normalizeSubtreeResourceMiddlewareEntry(ownerResourceId, entry) {
18731
+ normalizeSubtreeResourceMiddlewareEntry(ownerScopeOrResourceId, entryOrUsesFrameworkRootIds, maybeEntry) {
18732
+ const ownerScope = this.normalizeOwnerScopeArg(
18733
+ ownerScopeOrResourceId,
18734
+ entryOrUsesFrameworkRootIds
18735
+ );
18736
+ const entry = maybeEntry ?? entryOrUsesFrameworkRootIds;
18476
18737
  return this.normalizeSubtreeMiddlewareEntry(
18477
- ownerResourceId,
18738
+ ownerScope,
18478
18739
  "resourceMiddleware" /* ResourceMiddleware */,
18479
18740
  entry,
18480
18741
  getSubtreeResourceMiddlewareAttachment
18481
18742
  );
18482
18743
  }
18483
- normalizeMiddlewareAttachments(ownerResourceId, kind, attachments) {
18744
+ normalizeMiddlewareAttachments(ownerScope, kind, attachments) {
18484
18745
  if (!Array.isArray(attachments) || attachments.length === 0) {
18485
18746
  return attachments;
18486
18747
  }
18487
- if (!ownerResourceId) {
18748
+ if (!ownerScope) {
18488
18749
  return attachments;
18489
18750
  }
18490
18751
  return attachments.map(
18491
- (attachment) => this.normalizeMiddlewareAttachment(ownerResourceId, kind, attachment)
18752
+ (attachment) => this.normalizeMiddlewareAttachment(ownerScope, kind, attachment)
18492
18753
  );
18493
18754
  }
18494
- normalizeSubtreeMiddlewareEntry(ownerResourceId, kind, entry, getAttachment) {
18755
+ normalizeSubtreeMiddlewareEntry(ownerScope, kind, entry, getAttachment) {
18495
18756
  const attachment = getAttachment(entry);
18496
18757
  const normalizedAttachment = this.normalizeMiddlewareAttachment(
18497
- ownerResourceId,
18758
+ ownerScope,
18498
18759
  kind,
18499
18760
  attachment
18500
18761
  );
@@ -18509,17 +18770,11 @@ var StoreRegistryWriter = class {
18509
18770
  }
18510
18771
  return normalizedAttachment;
18511
18772
  }
18512
- normalizeMiddlewareAttachment(ownerResourceId, kind, attachment) {
18513
- const ownerIsGateway = this.collections.resources.get(ownerResourceId)?.resource.gateway === true;
18773
+ normalizeMiddlewareAttachment(ownerScope, kind, attachment) {
18514
18774
  const isRegisteredMiddlewareId = /* @__PURE__ */ __name((candidateId) => kind === "taskMiddleware" /* TaskMiddleware */ ? this.collections.taskMiddlewares.has(candidateId) : this.collections.resourceMiddlewares.has(candidateId), "isRegisteredMiddlewareId");
18515
18775
  const resolvedByAliasCandidate = this.aliasResolver.resolveDefinitionId(attachment);
18516
18776
  const resolvedByAlias = typeof resolvedByAliasCandidate === "string" && isRegisteredMiddlewareId(resolvedByAliasCandidate) ? resolvedByAliasCandidate : void 0;
18517
- const resolvedId = resolvedByAlias ?? this.computeCanonicalId(
18518
- ownerResourceId,
18519
- ownerIsGateway,
18520
- kind,
18521
- attachment.id
18522
- );
18777
+ const resolvedId = resolvedByAlias ?? this.canonicalIdCompiler.compute(ownerScope, kind, attachment.id);
18523
18778
  if (resolvedId === attachment.id) {
18524
18779
  return attachment;
18525
18780
  }
@@ -18550,6 +18805,15 @@ var StoreRegistryWriter = class {
18550
18805
  }
18551
18806
  return false;
18552
18807
  }
18808
+ normalizeOwnerScopeArg(ownerScopeOrResourceId, entryOrUsesFrameworkRootIds) {
18809
+ if (typeof ownerScopeOrResourceId !== "string") {
18810
+ return ownerScopeOrResourceId;
18811
+ }
18812
+ return {
18813
+ resourceId: ownerScopeOrResourceId,
18814
+ usesFrameworkRootIds: typeof entryOrUsesFrameworkRootIds === "boolean" ? entryOrUsesFrameworkRootIds : false
18815
+ };
18816
+ }
18553
18817
  normalizeDefinitionTags(tags2) {
18554
18818
  return normalizeTags(tags2).map((tag2) => {
18555
18819
  const resolvedId = this.aliasResolver.resolveDefinitionId(tag2);
@@ -18605,6 +18869,7 @@ var StoreRegistry = class {
18605
18869
  this.definitionIdentityAliases = /* @__PURE__ */ new WeakMap();
18606
18870
  this.definitionAliasesBySourceId = /* @__PURE__ */ new Map();
18607
18871
  this.sourceIdsByCanonicalId = /* @__PURE__ */ new Map();
18872
+ this.displayIdsByCanonicalId = /* @__PURE__ */ new Map();
18608
18873
  const lookupResolver = /* @__PURE__ */ __name((key) => this.resolveDefinitionId(key), "lookupResolver");
18609
18874
  this.tasks.setLookupResolver(lookupResolver);
18610
18875
  this.resources.setLookupResolver(lookupResolver);
@@ -18675,6 +18940,7 @@ var StoreRegistry = class {
18675
18940
  this.recordDefinitionIdentityAlias(reference, canonicalId);
18676
18941
  this.recordSourceIdAlias(reference, canonicalId);
18677
18942
  this.recordCanonicalSourceId(reference, canonicalId);
18943
+ this.computeAndStoreDisplayId(canonicalId);
18678
18944
  }
18679
18945
  resolveDefinitionId(reference) {
18680
18946
  if (typeof reference === "string") {
@@ -18761,16 +19027,35 @@ var StoreRegistry = class {
18761
19027
  return candidates.values().next().value;
18762
19028
  }
18763
19029
  getDisplayId(id3) {
18764
- const sourceIds = this.sourceIdsByCanonicalId.get(id3);
19030
+ return this.displayIdsByCanonicalId.get(id3) ?? id3;
19031
+ }
19032
+ stripFrameworkRootPrefix(id3) {
19033
+ const prefix = `${FRAMEWORK_ROOT_RESOURCE_ID}.`;
19034
+ return id3.startsWith(prefix) ? id3.slice(prefix.length) : id3;
19035
+ }
19036
+ computeAndStoreDisplayId(canonicalId) {
19037
+ if (canonicalId === FRAMEWORK_ROOT_RESOURCE_ID || canonicalId.startsWith(`${FRAMEWORK_ROOT_RESOURCE_ID}.`)) {
19038
+ this.displayIdsByCanonicalId.set(
19039
+ canonicalId,
19040
+ this.stripFrameworkRootPrefix(canonicalId)
19041
+ );
19042
+ return;
19043
+ }
19044
+ const sourceIds = this.sourceIdsByCanonicalId.get(canonicalId);
18765
19045
  if (!sourceIds || sourceIds.size === 0) {
18766
- return id3;
19046
+ this.displayIdsByCanonicalId.set(canonicalId, canonicalId);
19047
+ return;
18767
19048
  }
18768
19049
  for (const sourceId of sourceIds) {
18769
- if (sourceId !== id3) {
18770
- return sourceId;
19050
+ if (sourceId !== canonicalId) {
19051
+ this.displayIdsByCanonicalId.set(canonicalId, sourceId);
19052
+ return;
18771
19053
  }
18772
19054
  }
18773
- return sourceIds.values().next().value;
19055
+ this.displayIdsByCanonicalId.set(
19056
+ canonicalId,
19057
+ sourceIds.values().next().value
19058
+ );
18774
19059
  }
18775
19060
  /** Lock every map in the registry, preventing further mutations. */
18776
19061
  lockAll() {
@@ -19980,90 +20265,6 @@ function getTopologicalInitOrder(resources2, initializedResources) {
19980
20265
  }
19981
20266
  __name(getTopologicalInitOrder, "getTopologicalInitOrder");
19982
20267
 
19983
- // src/models/BuiltinsRegistry.ts
19984
- init_errors2();
19985
- function collectUniqueTags() {
19986
- const uniqueTags = [];
19987
- const seenIds = /* @__PURE__ */ new Set();
19988
- for (const tag2 of Object.values(globalTags)) {
19989
- if (seenIds.has(tag2.id)) {
19990
- continue;
19991
- }
19992
- seenIds.add(tag2.id);
19993
- uniqueTags.push(tag2);
19994
- }
19995
- return uniqueTags;
19996
- }
19997
- __name(collectUniqueTags, "collectUniqueTags");
19998
- var SYSTEM_FRAMEWORK_ITEMS = Object.freeze([
19999
- globalResources.store,
20000
- globalResources.eventManager,
20001
- globalResources.taskRunner,
20002
- globalResources.middlewareManager,
20003
- globalResources.runtime,
20004
- ...collectUniqueTags().filter((tag2) => tag2.id.startsWith("system.")),
20005
- ...globalEventsArray
20006
- ]);
20007
- var RUNNER_FRAMEWORK_ITEMS = Object.freeze([
20008
- globalResources.health,
20009
- globalResources.timers,
20010
- globalResources.logger,
20011
- globalResources.serializer,
20012
- globalResources.queue,
20013
- ...collectUniqueTags().filter((tag2) => tag2.id.startsWith("runner.")),
20014
- requireContextTaskMiddleware,
20015
- retryTaskMiddleware,
20016
- timeoutTaskMiddleware,
20017
- concurrencyTaskMiddleware,
20018
- debounceTaskMiddleware,
20019
- throttleTaskMiddleware,
20020
- fallbackTaskMiddleware,
20021
- rateLimitTaskMiddleware,
20022
- circuitBreakerMiddleware,
20023
- retryResourceMiddleware,
20024
- timeoutResourceMiddleware,
20025
- rateLimitResource,
20026
- circuitBreakerResource,
20027
- temporalResource,
20028
- concurrencyResource,
20029
- middlewareTimeoutError,
20030
- middlewareCircuitBreakerOpenError,
20031
- middlewareRateLimitExceededError,
20032
- durableExecutionError
20033
- ]);
20034
-
20035
- // src/models/createFrameworkRootGateway.ts
20036
- var FRAMEWORK_RUNNER_RESOURCE_ID = "runner";
20037
- var FRAMEWORK_SYSTEM_RESOURCE_ID = "system";
20038
- var FRAMEWORK_ROOT_GATEWAY_ID = "runtime-framework-root";
20039
- function createFrameworkNamespaceResource(resourceId, register) {
20040
- return defineResource({
20041
- id: resourceId,
20042
- register: [...register]
20043
- });
20044
- }
20045
- __name(createFrameworkNamespaceResource, "createFrameworkNamespaceResource");
20046
- function createFrameworkRootGateway({
20047
- rootItem,
20048
- debug: debug3
20049
- }) {
20050
- const runnerRegister = debug3 ? [...RUNNER_FRAMEWORK_ITEMS, debugResource.with(debug3)] : [...RUNNER_FRAMEWORK_ITEMS];
20051
- const systemResource = createFrameworkNamespaceResource(
20052
- FRAMEWORK_SYSTEM_RESOURCE_ID,
20053
- SYSTEM_FRAMEWORK_ITEMS
20054
- );
20055
- const runnerResource = createFrameworkNamespaceResource(
20056
- FRAMEWORK_RUNNER_RESOURCE_ID,
20057
- runnerRegister
20058
- );
20059
- return defineResource({
20060
- id: FRAMEWORK_ROOT_GATEWAY_ID,
20061
- gateway: true,
20062
- register: [systemResource, runnerResource, rootItem]
20063
- });
20064
- }
20065
- __name(createFrameworkRootGateway, "createFrameworkRootGateway");
20066
-
20067
20268
  // src/models/Store.ts
20068
20269
  init_symbols();
20069
20270
  var Store = class {
@@ -20325,7 +20526,7 @@ var Store = class {
20325
20526
  if (this.#isInitialized) {
20326
20527
  storeAlreadyInitializedError.throw();
20327
20528
  }
20328
- const frameworkRoot = createFrameworkRootGateway({
20529
+ const frameworkRoot = createFrameworkRootResource({
20329
20530
  rootItem: root.with(config),
20330
20531
  debug: options?.debug
20331
20532
  });
@@ -20697,7 +20898,6 @@ function resolveExecutionContextConfig(executionContext) {
20697
20898
  __name(resolveExecutionContextConfig, "resolveExecutionContextConfig");
20698
20899
 
20699
20900
  // src/run.ts
20700
- init_errors2();
20701
20901
  var activeRunResults = /* @__PURE__ */ new Set();
20702
20902
  function normalizeRunOptions(options) {
20703
20903
  const debug3 = options?.debug;
@@ -20744,9 +20944,6 @@ async function run(resourceOrResourceWithConfig, options) {
20744
20944
  const { resource: resource2, config } = extractResourceAndConfig(
20745
20945
  resourceOrResourceWithConfig
20746
20946
  );
20747
- if (resource2.gateway === true) {
20748
- runRootGatewayUnsupportedError.throw({ id: resource2.id });
20749
- }
20750
20947
  const services = createRuntimeServices({
20751
20948
  mode: normalizedOptions.mode,
20752
20949
  lifecycleMode: normalizedOptions.lifecycleMode,
@@ -21056,7 +21253,6 @@ function makeResourceBuilder(state) {
21056
21253
  build() {
21057
21254
  const definition = {
21058
21255
  id: state.id,
21059
- gateway: state.gateway,
21060
21256
  dependencies: state.dependencies,
21061
21257
  register: state.register,
21062
21258
  middleware: state.middleware,
@@ -21095,7 +21291,6 @@ __name(makeResourceBuilder, "makeResourceBuilder");
21095
21291
  function createResourceBuilder(id3, options) {
21096
21292
  const initial = Object.freeze({
21097
21293
  id: id3,
21098
- gateway: options?.gateway === true,
21099
21294
  filePath: options.filePath,
21100
21295
  dependencies: void 0,
21101
21296
  register: void 0,
@@ -22617,10 +22812,18 @@ init_errors2();
22617
22812
  init_platform();
22618
22813
  init_defineError();
22619
22814
  init_check();
22620
- var resources = Object.freeze({ ...globalResources });
22621
- var events = Object.freeze({ ...globalEvents });
22622
- var middleware = Object.freeze({ ...globalMiddlewares });
22623
- var tags = Object.freeze({ ...globalTags });
22815
+ var resources = Object.freeze({
22816
+ ...globalResources
22817
+ });
22818
+ var events = Object.freeze({
22819
+ ...globalEvents
22820
+ });
22821
+ var middleware = Object.freeze({
22822
+ ...globalMiddlewares
22823
+ });
22824
+ var tags = Object.freeze({
22825
+ ...globalTags
22826
+ });
22624
22827
  var debug2 = Object.freeze({ levels: debug.levels });
22625
22828
  var r = Object.freeze({
22626
22829
  resource,