@deslop/auth 0.1.1896 → 0.1.1920

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/server.js CHANGED
@@ -602,7 +602,7 @@ const mix = (h) => {
602
602
  *
603
603
  * @internal
604
604
  */
605
- const combine$4 = (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507));
605
+ const combine$5 = (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507));
606
606
  // ../../node_modules/.pnpm/effect@4.1.7/node_modules/effect/dist/internal/predicate.js
607
607
  /**
608
608
  * Data-first `Predicate.hasProperty`.
@@ -789,7 +789,7 @@ const random$1 = (self) => {
789
789
  * @category hashing
790
790
  * @since 2.0.0
791
791
  */
792
- const combine$3 = /*#__PURE__*/ dual(2, combine$4);
792
+ const combine$4 = /*#__PURE__*/ dual(2, combine$5);
793
793
  /**
794
794
  * Applies bit manipulation techniques to optimize a hash value.
795
795
  *
@@ -882,7 +882,7 @@ const number$2 = (n) => {
882
882
  const h = n | 0;
883
883
  if (h === n) return optimize(h);
884
884
  float64.setFloat64(0, n !== n ? NaN : n);
885
- return optimize(combine$4(float64.getInt32(0), float64.getInt32(4)));
885
+ return optimize(combine$5(float64.getInt32(0), float64.getInt32(4)));
886
886
  };
887
887
  /**
888
888
  * Computes a hash value for a string using the djb2 algorithm.
@@ -953,7 +953,7 @@ const string$2 = (str) => {
953
953
  * @category hashing
954
954
  * @since 2.0.0
955
955
  */
956
- const structureKeys = (o, keys) => hashUnordered(12289, keys, (key) => combine$4(hash(key), hash(o[key])));
956
+ const structureKeys = (o, keys) => hashUnordered(12289, keys, (key) => combine$5(hash(key), hash(o[key])));
957
957
  /**
958
958
  * Computes a structural hash for an object using Effect's object key collection.
959
959
  *
@@ -1028,18 +1028,18 @@ const hashUnordered = (seed, iter, f) => {
1028
1028
  */
1029
1029
  const array = (arr) => {
1030
1030
  let h = 6151;
1031
- for (const element of arr) h = combine$4(h, hash(element));
1031
+ for (const element of arr) h = combine$5(h, hash(element));
1032
1032
  return optimize(h);
1033
1033
  };
1034
1034
  const hashIndexed = (arr) => {
1035
1035
  let h = 6151;
1036
- for (let i = 0; i < arr.length; i++) h = combine$4(h, hash(arr[i]));
1036
+ for (let i = 0; i < arr.length; i++) h = combine$5(h, hash(arr[i]));
1037
1037
  return optimize(h);
1038
1038
  };
1039
1039
  const mapSeed = /*#__PURE__*/ string$2("Map");
1040
1040
  const setSeed = /*#__PURE__*/ string$2("Set");
1041
- const hashMapEntry = ([k, v]) => combine$4(hash(k), hash(v));
1042
- const hashSetElement = (element) => combine$4(setSeed, hash(element));
1041
+ const hashMapEntry = ([k, v]) => combine$5(hash(k), hash(v));
1042
+ const hashSetElement = (element) => combine$5(setSeed, hash(element));
1043
1043
  const randomHashCache = /*#__PURE__*/ new WeakMap();
1044
1044
  const visitedObjects = /*#__PURE__*/ new WeakSet();
1045
1045
  // ../../node_modules/.pnpm/effect@4.1.7/node_modules/effect/dist/Equal.js
@@ -3010,7 +3010,7 @@ var Fail = class extends ReasonBase {
3010
3010
  }
3011
3011
  [symbol$3]() {
3012
3012
  const error = hash(this.error);
3013
- return combine$4(combine$4(hash(this.annotations), error), string$2(this._tag));
3013
+ return combine$5(combine$5(hash(this.annotations), error), string$2(this._tag));
3014
3014
  }
3015
3015
  };
3016
3016
  /** @internal */
@@ -3071,7 +3071,7 @@ var Die = class extends ReasonBase {
3071
3071
  }
3072
3072
  [symbol$3]() {
3073
3073
  const defect = hash(this.defect);
3074
- return combine$4(combine$4(hash(this.annotations), defect), string$2(this._tag));
3074
+ return combine$5(combine$5(hash(this.annotations), defect), string$2(this._tag));
3075
3075
  }
3076
3076
  };
3077
3077
  /** @internal */
@@ -3157,7 +3157,7 @@ const makeExit = (options) => {
3157
3157
  return isExit$1(that) && that._tag === this._tag && equals$1(this["~effect/Effect/args"], that["~effect/Effect/args"]);
3158
3158
  },
3159
3159
  [symbol$3]() {
3160
- return combine$4(opHash, hash(this[args]));
3160
+ return combine$5(opHash, hash(this[args]));
3161
3161
  }
3162
3162
  };
3163
3163
  const ExitPrimitive = function(value) {
@@ -3433,7 +3433,7 @@ const fiberCachedKeys = /*#__PURE__*/ new Set([
3433
3433
  * @category constructors
3434
3434
  * @since 2.0.0
3435
3435
  */
3436
- const make$91 = (isEquivalent) => (self, that) => self === that || isEquivalent(self, that);
3436
+ const make$92 = (isEquivalent) => (self, that) => self === that || isEquivalent(self, that);
3437
3437
  const isStrictEquivalent = (x, y) => x === y;
3438
3438
  /**
3439
3439
  * Creates an equivalence relation that uses strict equality (`===`) to compare values.
@@ -3543,7 +3543,7 @@ const strictEqual = () => isStrictEquivalent;
3543
3543
  * @since 4.0.0
3544
3544
  */
3545
3545
  function Tuple$1(elements) {
3546
- return make$91((self, that) => {
3546
+ return make$92((self, that) => {
3547
3547
  if (self.length !== that.length) return false;
3548
3548
  for (let i = 0; i < self.length; i++) if (!elements[i](self[i], that[i])) return false;
3549
3549
  return true;
@@ -3553,7 +3553,7 @@ function Tuple$1(elements) {
3553
3553
  * @since 4.0.0
3554
3554
  */
3555
3555
  function Array_(item) {
3556
- return make$91((self, that) => {
3556
+ return make$92((self, that) => {
3557
3557
  if (self.length !== that.length) return false;
3558
3558
  for (let i = 0; i < self.length; i++) if (!item(self[i], that[i])) return false;
3559
3559
  return true;
@@ -3578,7 +3578,7 @@ const SomeProto = /*#__PURE__*/ Object.defineProperty(/*#__PURE__*/ Object.assig
3578
3578
  return isOption$1(that) && isSome$1(that) && equals$1(this.value, that.value);
3579
3579
  },
3580
3580
  [symbol$3]() {
3581
- return combine$3(hash(this._tag))(hash(this.value));
3581
+ return combine$4(hash(this._tag))(hash(this.value));
3582
3582
  },
3583
3583
  toString() {
3584
3584
  return `some(${format$5(this.value)})`;
@@ -3649,7 +3649,7 @@ const SuccessProto = /*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(Com
3649
3649
  return isResult$1(that) && isSuccess$3(that) && equals$1(this.success, that.success);
3650
3650
  },
3651
3651
  [symbol$3]() {
3652
- return combine$3(hash(this._tag))(hash(this.success));
3652
+ return combine$4(hash(this._tag))(hash(this.success));
3653
3653
  },
3654
3654
  toString() {
3655
3655
  return `success(${format$5(this.success)})`;
@@ -3669,7 +3669,7 @@ const FailureProto = /*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(Com
3669
3669
  return isResult$1(that) && isFailure$2(that) && equals$1(this.failure, that.failure);
3670
3670
  },
3671
3671
  [symbol$3]() {
3672
- return combine$3(hash(this._tag))(hash(this.failure));
3672
+ return combine$4(hash(this._tag))(hash(this.failure));
3673
3673
  },
3674
3674
  toString() {
3675
3675
  return `failure(${format$5(this.failure)})`;
@@ -3754,7 +3754,7 @@ const getSuccess$1 = (self) => isFailure$2(self) ? none$1 : some$2(self.success)
3754
3754
  * @category constructors
3755
3755
  * @since 2.0.0
3756
3756
  */
3757
- function make$90(compare) {
3757
+ function make$91(compare) {
3758
3758
  return (self, that) => self === that ? 0 : compare(self, that);
3759
3759
  }
3760
3760
  /**
@@ -3785,7 +3785,7 @@ function make$90(compare) {
3785
3785
  * @category instances
3786
3786
  * @since 4.0.0
3787
3787
  */
3788
- const String$10 = /*#__PURE__*/ make$90((self, that) => self < that ? -1 : 1);
3788
+ const String$10 = /*#__PURE__*/ make$91((self, that) => self < that ? -1 : 1);
3789
3789
  /**
3790
3790
  * Order instance for numbers that compares them numerically.
3791
3791
  *
@@ -3818,7 +3818,7 @@ const String$10 = /*#__PURE__*/ make$90((self, that) => self < that ? -1 : 1);
3818
3818
  * @category instances
3819
3819
  * @since 4.0.0
3820
3820
  */
3821
- const Number$6 = /*#__PURE__*/ make$90((self, that) => {
3821
+ const Number$6 = /*#__PURE__*/ make$91((self, that) => {
3822
3822
  if (globalThis.Number.isNaN(self) && globalThis.Number.isNaN(that)) return 0;
3823
3823
  if (globalThis.Number.isNaN(self)) return -1;
3824
3824
  if (globalThis.Number.isNaN(that)) return 1;
@@ -3852,7 +3852,88 @@ const Number$6 = /*#__PURE__*/ make$90((self, that) => {
3852
3852
  * @category instances
3853
3853
  * @since 4.0.0
3854
3854
  */
3855
- const BigInt$5 = /*#__PURE__*/ make$90((self, that) => self < that ? -1 : 1);
3855
+ const BigInt$5 = /*#__PURE__*/ make$91((self, that) => self < that ? -1 : 1);
3856
+ /**
3857
+ * Creates a new `Order` that reverses the comparison order of the input `Order`.
3858
+ *
3859
+ * **When to use**
3860
+ *
3861
+ * Use when you need the reverse of an existing order.
3862
+ *
3863
+ * **Details**
3864
+ *
3865
+ * Returns a new order that swaps the arguments before comparison. If the
3866
+ * original order returns `-1`, the flipped order returns `1`, and vice versa.
3867
+ * Equal comparisons remain `0`.
3868
+ *
3869
+ * **Example** (Reversing an Order)
3870
+ *
3871
+ * ```ts import.meta.vitest
3872
+ * import { Order } from "effect"
3873
+ *
3874
+ * const flip = Order.flip(Order.Number)
3875
+ *
3876
+ * flip(1, 2) // => 1
3877
+ * flip(2, 1) // => -1
3878
+ * flip(1, 1) // => 0
3879
+ * ```
3880
+ *
3881
+ * @see {@link combine} to combine orders for multi-criteria comparison
3882
+ * @stability stable
3883
+ * @category combinators
3884
+ * @since 4.0.0
3885
+ */
3886
+ function flip$1(O) {
3887
+ return make$91((self, that) => O(that, self));
3888
+ }
3889
+ /**
3890
+ * Combines two `Order` instances to create a new `Order` that first compares using the first `Order`,
3891
+ * and if the values are equal, then compares using the second `Order`.
3892
+ *
3893
+ * **When to use**
3894
+ *
3895
+ * Use when you need tie-breaking with exactly two orders.
3896
+ *
3897
+ * **Details**
3898
+ *
3899
+ * First applies the first order. If the result is non-zero, that result is
3900
+ * returned; otherwise, the second order is applied. The result is the first
3901
+ * non-zero comparison result, or `0` if both orders return `0`.
3902
+ *
3903
+ * **Example** (Combining two Orders)
3904
+ *
3905
+ * ```ts import.meta.vitest
3906
+ * import { Order } from "effect"
3907
+ *
3908
+ * const byAge = Order.mapInput(
3909
+ * Order.Number,
3910
+ * (person: { name: string; age: number }) => person.age
3911
+ * )
3912
+ * const byName = Order.mapInput(
3913
+ * Order.String,
3914
+ * (person: { name: string; age: number }) => person.name
3915
+ * )
3916
+ * const byAgeAndName = Order.combine(byAge, byName)
3917
+ *
3918
+ * const person1 = { name: "Alice", age: 30 }
3919
+ * const person2 = { name: "Bob", age: 30 }
3920
+ * const person3 = { name: "Charlie", age: 25 }
3921
+ *
3922
+ * byAgeAndName(person1, person2) // => -1
3923
+ * byAgeAndName(person1, person3) // => 1
3924
+ * ```
3925
+ *
3926
+ * @see {@link combineAll} to combine multiple orders from a collection
3927
+ * @see {@link mapInput} to transform orders to work with different types
3928
+ * @stability stable
3929
+ * @category combining
3930
+ * @since 2.0.0
3931
+ */
3932
+ const combine$3 = /*#__PURE__*/ dual(2, (self, that) => make$91((a1, a2) => {
3933
+ const out = self(a1, a2);
3934
+ if (out !== 0) return out;
3935
+ return that(a1, a2);
3936
+ }));
3856
3937
  /**
3857
3938
  * Transforms an `Order` on type `A` into an `Order` on type `B` by providing a function that
3858
3939
  * maps values of type `B` to values of type `A`.
@@ -3886,7 +3967,7 @@ const BigInt$5 = /*#__PURE__*/ make$90((self, that) => self < that ? -1 : 1);
3886
3967
  * @category mapping
3887
3968
  * @since 2.0.0
3888
3969
  */
3889
- const mapInput = /*#__PURE__*/ dual(2, (self, f) => make$90((b1, b2) => self(f(b1), f(b2))));
3970
+ const mapInput = /*#__PURE__*/ dual(2, (self, f) => make$91((b1, b2) => self(f(b1), f(b2))));
3890
3971
  /**
3891
3972
  * Checks whether one value is strictly less than another according to the given order.
3892
3973
  *
@@ -4043,7 +4124,7 @@ const isGreaterThanOrEqualTo$2 = (O) => dual(2, (self, that) => O(self, that) !=
4043
4124
  * @category comparisons
4044
4125
  * @since 2.0.0
4045
4126
  */
4046
- const min$2 = (O) => dual(2, (self, that) => self === that || O(self, that) < 1 ? self : that);
4127
+ const min$3 = (O) => dual(2, (self, that) => self === that || O(self, that) < 1 ? self : that);
4047
4128
  /**
4048
4129
  * Returns the maximum of two values according to the given order. If they are equal, returns the first argument.
4049
4130
  *
@@ -4075,7 +4156,7 @@ const min$2 = (O) => dual(2, (self, that) => self === that || O(self, that) < 1
4075
4156
  * @category comparisons
4076
4157
  * @since 2.0.0
4077
4158
  */
4078
- const max$1 = (O) => dual(2, (self, that) => self === that || O(self, that) > -1 ? self : that);
4159
+ const max$2 = (O) => dual(2, (self, that) => self === that || O(self, that) > -1 ? self : that);
4079
4160
  // ../../node_modules/.pnpm/effect@4.1.7/node_modules/effect/dist/Option.js
4080
4161
  /**
4081
4162
  * Creates an `Option` representing the absence of a value.
@@ -4958,7 +5039,7 @@ const Service$1 = function() {
4958
5039
  const ServiceProto = /*#__PURE__*/ Object.assign({ [ServiceTypeId]: ServiceTypeId }, /*#__PURE__*/ Prototype({
4959
5040
  label: "Service",
4960
5041
  evaluate(fiber) {
4961
- return exitSucceed(get$12(fiber.context, this));
5042
+ return exitSucceed(get$13(fiber.context, this));
4962
5043
  }
4963
5044
  }), {
4964
5045
  toJSON() {
@@ -4971,13 +5052,13 @@ const ServiceProto = /*#__PURE__*/ Object.assign({ [ServiceTypeId]: ServiceTypeI
4971
5052
  return self;
4972
5053
  },
4973
5054
  context(self) {
4974
- return make$89(this, self);
5055
+ return make$90(this, self);
4975
5056
  },
4976
5057
  use(f) {
4977
- return withFiber$1((fiber) => f(get$12(fiber.context, this)));
5058
+ return withFiber$1((fiber) => f(get$13(fiber.context, this)));
4978
5059
  },
4979
5060
  useSync(f) {
4980
- return withFiber$1((fiber) => exitSucceed(f(get$12(fiber.context, this))));
5061
+ return withFiber$1((fiber) => exitSucceed(f(get$13(fiber.context, this))));
4981
5062
  }
4982
5063
  });
4983
5064
  const ReferenceTypeId = "~effect/Context/Reference";
@@ -5214,7 +5295,7 @@ const emptyContext = /*#__PURE__*/ makeUnsafe$9(/*#__PURE__*/ new Map());
5214
5295
  * @category constructors
5215
5296
  * @since 2.0.0
5216
5297
  */
5217
- const make$89 = (key, service) => makeUnsafe$9(/* @__PURE__ */ new Map([[key.key, service]]));
5298
+ const make$90 = (key, service) => makeUnsafe$9(/* @__PURE__ */ new Map([[key.key, service]]));
5218
5299
  /**
5219
5300
  * Adds a service to a given `Context`.
5220
5301
  *
@@ -5376,7 +5457,7 @@ const getUnsafe$1 = /*#__PURE__*/ dual(2, (self, service) => {
5376
5457
  * @category getters
5377
5458
  * @since 2.0.0
5378
5459
  */
5379
- const get$12 = getUnsafe$1;
5460
+ const get$13 = getUnsafe$1;
5380
5461
  const defaultValueCacheKey = "~effect/Context/defaultValue";
5381
5462
  const getDefaultValue = (ref) => {
5382
5463
  if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey];
@@ -5633,7 +5714,7 @@ const bigintNanosPerDay = /*#__PURE__*/ BigInt(864e11);
5633
5714
  const bigintNanosPerWeek = /*#__PURE__*/ BigInt(6048e11);
5634
5715
  const roundTiesAwayFromZero = (input) => BigInt(Math.sign(input) * Math.round(Math.abs(input)));
5635
5716
  const roundMillisToNanos = (millis) => Number.isInteger(millis) ? BigInt(millis) * bigint1e6 : roundTiesAwayFromZero(millis * 1e6);
5636
- const fromNanosNumber = (nanos) => make$88(Number.isFinite(nanos) ? roundTiesAwayFromZero(nanos) : nanos);
5717
+ const fromNanosNumber = (nanos) => make$89(Number.isFinite(nanos) ? roundTiesAwayFromZero(nanos) : nanos);
5637
5718
  const nanosToUnit = (nanos, divisor) => {
5638
5719
  const value = Number(nanos);
5639
5720
  if (Number.isFinite(value)) return value / divisor;
@@ -5656,9 +5737,9 @@ const divideTiesAwayFromZero = (numerator, denominator) => {
5656
5737
  };
5657
5738
  const fromMillisString = (input, scale) => {
5658
5739
  const millis = Number(input) * scale;
5659
- if (!Number.isFinite(millis)) return make$88(millis);
5740
+ if (!Number.isFinite(millis)) return make$89(millis);
5660
5741
  const nanos = parseNanos(input, BigInt(scale) * bigint1e6);
5661
- return make$88(Number.isInteger(millis) && BigInt(millis) * bigint1e6 === nanos ? millis : nanos);
5742
+ return make$89(Number.isInteger(millis) && BigInt(millis) * bigint1e6 === nanos ? millis : nanos);
5662
5743
  };
5663
5744
  const DURATION_REGEXP = /^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/;
5664
5745
  /**
@@ -5725,7 +5806,7 @@ const fromInputUnsafe$1 = (input) => {
5725
5806
  if (input[0] === -Infinity || input[1] === -Infinity) return negativeInfinity;
5726
5807
  if (input[0] === Infinity || input[1] === Infinity) return infinity$1;
5727
5808
  const nanos = input[0] * 1e9 + input[1];
5728
- return Number.isFinite(nanos) && Number.isInteger(input[0]) && Number.isInteger(input[1]) ? make$88(BigInt(input[0]) * bigint1e9 + BigInt(input[1])) : fromNanosNumber(nanos);
5809
+ return Number.isFinite(nanos) && Number.isInteger(input[0]) && Number.isInteger(input[1]) ? make$89(BigInt(input[0]) * bigint1e9 + BigInt(input[1])) : fromNanosNumber(nanos);
5729
5810
  }
5730
5811
  const obj = input;
5731
5812
  let millis = 0;
@@ -5736,13 +5817,13 @@ const fromInputUnsafe$1 = (input) => {
5736
5817
  if (obj.seconds) millis += obj.seconds * 1e3;
5737
5818
  if (obj.milliseconds) millis += obj.milliseconds;
5738
5819
  if (!obj.microseconds && !obj.nanoseconds) {
5739
- if (!Number.isFinite(millis)) return make$88(millis);
5820
+ if (!Number.isFinite(millis)) return make$89(millis);
5740
5821
  const exact = sumObjectNanos(obj);
5741
- return exact === void 0 || BigInt(millis) * bigint1e6 === exact ? make$88(millis) : make$88(exact);
5822
+ return exact === void 0 || BigInt(millis) * bigint1e6 === exact ? make$89(millis) : make$89(exact);
5742
5823
  }
5743
5824
  const nanos = millis * 1e6 + (obj.microseconds ?? 0) * 1e3 + (obj.nanoseconds ?? 0);
5744
5825
  const exact = Number.isFinite(nanos) ? sumObjectNanos(obj) : void 0;
5745
- return exact === void 0 ? fromNanosNumber(nanos) : make$88(exact);
5826
+ return exact === void 0 ? fromNanosNumber(nanos) : make$89(exact);
5746
5827
  }
5747
5828
  }
5748
5829
  return invalid$3(input);
@@ -5837,7 +5918,7 @@ const DurationProto = {
5837
5918
  return pipeArguments(this, arguments);
5838
5919
  }
5839
5920
  };
5840
- const make$88 = (input) => {
5921
+ const make$89 = (input) => {
5841
5922
  const duration = Object.create(DurationProto);
5842
5923
  if (typeof input === "number") {
5843
5924
  if (isNaN(input) || input === 0 || Object.is(input, -0)) duration.value = zeroDurationValue;
@@ -5960,8 +6041,8 @@ const abs = (self) => {
5960
6041
  switch (self.value._tag) {
5961
6042
  case "Infinity":
5962
6043
  case "NegativeInfinity": return infinity$1;
5963
- case "Millis": return self.value.millis < 0 ? make$88(-self.value.millis) : self;
5964
- case "Nanos": return self.value.nanos < bigint0$5 ? make$88(-self.value.nanos) : self;
6044
+ case "Millis": return self.value.millis < 0 ? make$89(-self.value.millis) : self;
6045
+ case "Nanos": return self.value.nanos < bigint0$5 ? make$89(-self.value.nanos) : self;
5965
6046
  }
5966
6047
  };
5967
6048
  /**
@@ -5979,7 +6060,7 @@ const abs = (self) => {
5979
6060
  * @category constructors
5980
6061
  * @since 2.0.0
5981
6062
  */
5982
- const zero$2 = /*#__PURE__*/ make$88(0);
6063
+ const zero$2 = /*#__PURE__*/ make$89(0);
5983
6064
  /**
5984
6065
  * A Duration representing infinite time.
5985
6066
  *
@@ -5995,7 +6076,7 @@ const zero$2 = /*#__PURE__*/ make$88(0);
5995
6076
  * @category constructors
5996
6077
  * @since 2.0.0
5997
6078
  */
5998
- const infinity$1 = /*#__PURE__*/ make$88(Infinity);
6079
+ const infinity$1 = /*#__PURE__*/ make$89(Infinity);
5999
6080
  /**
6000
6081
  * A Duration representing negative infinite time.
6001
6082
  *
@@ -6011,7 +6092,7 @@ const infinity$1 = /*#__PURE__*/ make$88(Infinity);
6011
6092
  * @category constructors
6012
6093
  * @since 4.0.0
6013
6094
  */
6014
- const negativeInfinity = /*#__PURE__*/ make$88(-Infinity);
6095
+ const negativeInfinity = /*#__PURE__*/ make$89(-Infinity);
6015
6096
  /**
6016
6097
  * Creates a Duration from nanoseconds.
6017
6098
  *
@@ -6027,7 +6108,7 @@ const negativeInfinity = /*#__PURE__*/ make$88(-Infinity);
6027
6108
  * @category constructors
6028
6109
  * @since 2.0.0
6029
6110
  */
6030
- const nanos = (nanos) => make$88(nanos);
6111
+ const nanos = (nanos) => make$89(nanos);
6031
6112
  /**
6032
6113
  * Creates a Duration from milliseconds.
6033
6114
  *
@@ -6043,7 +6124,7 @@ const nanos = (nanos) => make$88(nanos);
6043
6124
  * @category constructors
6044
6125
  * @since 2.0.0
6045
6126
  */
6046
- const millis = (millis) => make$88(millis);
6127
+ const millis = (millis) => make$89(millis);
6047
6128
  /**
6048
6129
  * Creates a Duration from seconds.
6049
6130
  *
@@ -6059,7 +6140,7 @@ const millis = (millis) => make$88(millis);
6059
6140
  * @category constructors
6060
6141
  * @since 2.0.0
6061
6142
  */
6062
- const seconds = (seconds) => make$88(seconds * 1e3);
6143
+ const seconds = (seconds) => make$89(seconds * 1e3);
6063
6144
  /**
6064
6145
  * Creates a Duration from minutes.
6065
6146
  *
@@ -6075,7 +6156,7 @@ const seconds = (seconds) => make$88(seconds * 1e3);
6075
6156
  * @category constructors
6076
6157
  * @since 2.0.0
6077
6158
  */
6078
- const minutes = (minutes) => make$88(minutes * 6e4);
6159
+ const minutes = (minutes) => make$89(minutes * 6e4);
6079
6160
  /**
6080
6161
  * Creates a Duration from hours.
6081
6162
  *
@@ -6091,7 +6172,7 @@ const minutes = (minutes) => make$88(minutes * 6e4);
6091
6172
  * @category constructors
6092
6173
  * @since 2.0.0
6093
6174
  */
6094
- const hours = (hours) => make$88(hours * 36e5);
6175
+ const hours = (hours) => make$89(hours * 36e5);
6095
6176
  /**
6096
6177
  * Converts a Duration to milliseconds.
6097
6178
  *
@@ -6258,7 +6339,7 @@ const matchPair = /*#__PURE__*/ dual(3, (self, that, options) => {
6258
6339
  * @category instances
6259
6340
  * @since 2.0.0
6260
6341
  */
6261
- const Order$6 = /*#__PURE__*/ make$90((self, that) => matchPair(self, that, {
6342
+ const Order$6 = /*#__PURE__*/ make$91((self, that) => matchPair(self, that, {
6262
6343
  onMillis: (self, that) => self < that ? -1 : self > that ? 1 : 0,
6263
6344
  onNanos: (self, that) => self < that ? -1 : self > that ? 1 : 0,
6264
6345
  onInfinity: (self, that) => {
@@ -6304,7 +6385,7 @@ const Equivalence$3 = (self, that) => matchPair(self, that, {
6304
6385
  * @category ordering
6305
6386
  * @since 2.0.0
6306
6387
  */
6307
- const min$1 = /*#__PURE__*/ min$2(Order$6);
6388
+ const min$2 = /*#__PURE__*/ min$3(Order$6);
6308
6389
  /**
6309
6390
  * Returns the larger of two Durations.
6310
6391
  *
@@ -6320,7 +6401,7 @@ const min$1 = /*#__PURE__*/ min$2(Order$6);
6320
6401
  * @category ordering
6321
6402
  * @since 2.0.0
6322
6403
  */
6323
- const max = /*#__PURE__*/ max$1(Order$6);
6404
+ const max$1 = /*#__PURE__*/ max$2(Order$6);
6324
6405
  /**
6325
6406
  * Adds two Durations together.
6326
6407
  *
@@ -6347,8 +6428,8 @@ const max = /*#__PURE__*/ max$1(Order$6);
6347
6428
  * @since 2.0.0
6348
6429
  */
6349
6430
  const sum = /*#__PURE__*/ dual(2, (self, that) => matchPair(self, that, {
6350
- onMillis: (self, that) => make$88(self + that),
6351
- onNanos: (self, that) => make$88(self + that),
6431
+ onMillis: (self, that) => make$89(self + that),
6432
+ onNanos: (self, that) => make$89(self + that),
6352
6433
  onInfinity: (self, that) => {
6353
6434
  const s = self.value._tag;
6354
6435
  const t = that.value._tag;
@@ -6968,6 +7049,34 @@ const all$4 = (input) => {
6968
7049
  };
6969
7050
  // ../../node_modules/.pnpm/effect@4.1.7/node_modules/effect/dist/Tuple.js
6970
7051
  /**
7052
+ * Creates a tuple from the provided arguments.
7053
+ *
7054
+ * **When to use**
7055
+ *
7056
+ * Use when you need a properly typed tuple without writing `[a, b, c] as const`
7057
+ * or another manual cast.
7058
+ *
7059
+ * **Details**
7060
+ *
7061
+ * The returned value has the exact tuple type, with each element's literal type
7062
+ * preserved.
7063
+ *
7064
+ * **Example** (Creating a tuple)
7065
+ *
7066
+ * ```ts import.meta.vitest
7067
+ * import { Tuple } from "effect"
7068
+ *
7069
+ * Tuple.make(10, 20, "red") // => [10, 20, "red"]
7070
+ * ```
7071
+ *
7072
+ * @see {@link get} – access a single element by index
7073
+ * @see {@link appendElement} – append an element to a tuple
7074
+ * @stability stable
7075
+ * @category constructors
7076
+ * @since 2.0.0
7077
+ */
7078
+ const make$88 = (...elements) => elements;
7079
+ /**
6971
7080
  * Creates an `Equivalence` for tuples by comparing corresponding elements
6972
7081
  * using the provided per-position `Equivalence`s. Two tuples are equivalent
6973
7082
  * when all their corresponding elements are equivalent.
@@ -7209,7 +7318,7 @@ const has$3 = /*#__PURE__*/ dual(2, (self, key) => Object.hasOwn(self, key));
7209
7318
  * @category getters
7210
7319
  * @since 2.0.0
7211
7320
  */
7212
- const get$11 = /*#__PURE__*/ dual(2, (self, key) => Object.hasOwn(self, key) ? some$1(self[key]) : none());
7321
+ const get$12 = /*#__PURE__*/ dual(2, (self, key) => Object.hasOwn(self, key) ? some$1(self[key]) : none());
7213
7322
  /**
7214
7323
  * Maps a record into another record by applying a transformation function to each of its values.
7215
7324
  *
@@ -7710,7 +7819,7 @@ function isOutOfBounds(i, as) {
7710
7819
  * @category getters
7711
7820
  * @since 2.0.0
7712
7821
  */
7713
- const get$10 = /*#__PURE__*/ dual(2, (self, index) => {
7822
+ const get$11 = /*#__PURE__*/ dual(2, (self, index) => {
7714
7823
  const i = Math.floor(index);
7715
7824
  return isOutOfBounds(i, self) ? none() : some$1(self[i]);
7716
7825
  });
@@ -7771,7 +7880,7 @@ const getUnsafe = /*#__PURE__*/ dual(2, (self, index) => {
7771
7880
  * @category getters
7772
7881
  * @since 2.0.0
7773
7882
  */
7774
- const head = /*#__PURE__*/ get$10(0);
7883
+ const head = /*#__PURE__*/ get$11(0);
7775
7884
  /**
7776
7885
  * Returns the first element of a `NonEmptyReadonlyArray` directly (no `Option`
7777
7886
  * wrapper).
@@ -8444,6 +8553,26 @@ const flatMapNullishOr = /*#__PURE__*/ dual(2, (self, f) => flatMap$6(self, (a)
8444
8553
  */
8445
8554
  const some = /*#__PURE__*/ dual(2, (self, predicate) => self.some(predicate));
8446
8555
  /**
8556
+ * Returns the minimum element of a non-empty array according to the given
8557
+ * `Order`.
8558
+ *
8559
+ * **Example** (Finding the minimum)
8560
+ *
8561
+ * ```ts import.meta.vitest
8562
+ * import { Array, Order } from "effect"
8563
+ *
8564
+ * Array.min([3, 1, 2], Order.Number) // => 1
8565
+ * ```
8566
+ *
8567
+ * @see {@link max} — find the maximum
8568
+ * @see {@link sort} — sort the entire array
8569
+ *
8570
+ * @stability stable
8571
+ * @category getters
8572
+ * @since 2.0.0
8573
+ */
8574
+ const min$1 = /*#__PURE__*/ dual(2, (self, O) => self.reduce(min$3(O)));
8575
+ /**
8447
8576
  * Creates an `Equivalence` for arrays based on an element `Equivalence`. Two
8448
8577
  * arrays are equivalent when they have the same length and all elements are
8449
8578
  * pairwise equivalent.
@@ -11441,6 +11570,8 @@ const makeLatchUnsafe = (open) => new Latch(open ?? false);
11441
11570
  /** @internal */
11442
11571
  const makeLatch = (open) => sync$2(() => makeLatchUnsafe(open));
11443
11572
  /** @internal */
11573
+ const tracer$2 = /*#__PURE__*/ withFiber$1((fiber) => succeed$9(fiber.getRef(Tracer)));
11574
+ /** @internal */
11444
11575
  const withTracerEnabled$1 = /*#__PURE__*/ provideService$3(TracerEnabled$1);
11445
11576
  const bigint0$4 = /*#__PURE__*/ BigInt(0);
11446
11577
  const NoopSpanProto = {
@@ -11467,11 +11598,11 @@ const noopSpan = (options) => Object.assign(Object.create(NoopSpanProto), option
11467
11598
  /** @internal */
11468
11599
  const filterDisablePropagation = (span) => {
11469
11600
  if (!span) return none();
11470
- return get$12(span.annotations, DisablePropagation) ? span._tag === "Span" ? filterDisablePropagation(getOrUndefined$2(span.parent)) : none() : some$1(span);
11601
+ return get$13(span.annotations, DisablePropagation) ? span._tag === "Span" ? filterDisablePropagation(getOrUndefined$2(span.parent)) : none() : some$1(span);
11471
11602
  };
11472
11603
  /** @internal */
11473
11604
  const makeSpanUnsafe = (fiber, name, options) => {
11474
- const disablePropagation = !fiber.cache.tracerEnabled || options?.annotations && get$12(options.annotations, DisablePropagation);
11605
+ const disablePropagation = !fiber.cache.tracerEnabled || options?.annotations && get$13(options.annotations, DisablePropagation);
11475
11606
  const parent = options?.parent !== void 0 ? some$1(options.parent) : options?.root ? none() : filterDisablePropagation(fiber.cache.span);
11476
11607
  let span;
11477
11608
  if (disablePropagation) span = noopSpan({
@@ -13534,8 +13665,8 @@ const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber$1((fiber
13534
13665
  * @since 2.0.0
13535
13666
  */
13536
13667
  const succeed$6 = function() {
13537
- if (arguments.length === 1) return (resource) => succeedContext(make$89(arguments[0], resource));
13538
- return succeedContext(make$89(arguments[0], arguments[1]));
13668
+ if (arguments.length === 1) return (resource) => succeedContext(make$90(arguments[0], resource));
13669
+ return succeedContext(make$90(arguments[0], arguments[1]));
13539
13670
  };
13540
13671
  /**
13541
13672
  * Constructs a layer that provides all services in an already available
@@ -13647,8 +13778,8 @@ const empty$11 = /*#__PURE__*/ succeedContext(/*#__PURE__*/ empty$14());
13647
13778
  * @since 2.0.0
13648
13779
  */
13649
13780
  const sync$1 = function() {
13650
- if (arguments.length === 1) return (evaluate) => syncContext(() => make$89(arguments[0], evaluate()));
13651
- return syncContext(() => make$89(arguments[0], arguments[1]()));
13781
+ if (arguments.length === 1) return (evaluate) => syncContext(() => make$90(arguments[0], evaluate()));
13782
+ return syncContext(() => make$90(arguments[0], arguments[1]()));
13652
13783
  };
13653
13784
  /**
13654
13785
  * Constructs a layer lazily that provides all services in a `Context`.
@@ -13732,7 +13863,7 @@ const effect = function() {
13732
13863
  if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect);
13733
13864
  return effectImpl(arguments[0], arguments[1]);
13734
13865
  };
13735
- const effectImpl = (service, effect) => effectContext(map$9(effect, (value) => make$89(service, value)));
13866
+ const effectImpl = (service, effect) => effectContext(map$9(effect, (value) => make$90(service, value)));
13736
13867
  /**
13737
13868
  * Constructs a layer from an effect that produces all services in a `Context`.
13738
13869
  *
@@ -13840,7 +13971,7 @@ const unwrapKey = /*#__PURE__*/ Service$1("effect/Layer/unwrap");
13840
13971
  * @category converting
13841
13972
  * @since 4.0.0
13842
13973
  */
13843
- const unwrap$7 = (self) => flatMap$4(effect(unwrapKey)(self), get$12(unwrapKey));
13974
+ const unwrap$7 = (self) => flatMap$4(effect(unwrapKey)(self), get$13(unwrapKey));
13844
13975
  const mergeAllEffect = (layers, memoMap, scope) => {
13845
13976
  const parentScope = forkUnsafe(scope, "parallel");
13846
13977
  return forEach$2(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map$9((context) => mergeAll$2(...context)));
@@ -15359,7 +15490,7 @@ const ProtoZoned = {
15359
15490
  ...Proto$19,
15360
15491
  _tag: "Zoned",
15361
15492
  [symbol$3]() {
15362
- return combine$3(number$2(this.epochMilliseconds))(hash(this.zone));
15493
+ return combine$4(number$2(this.epochMilliseconds))(hash(this.zone));
15363
15494
  },
15364
15495
  [symbol$2](that) {
15365
15496
  return isDateTime$1(that) && that._tag === "Zoned" && this.epochMilliseconds === that.epochMilliseconds && equals$1(this.zone, that.zone);
@@ -15467,7 +15598,7 @@ const isUtc$1 = (self) => self._tag === "Utc";
15467
15598
  /** @internal */
15468
15599
  const isZoned = (self) => self._tag === "Zoned";
15469
15600
  /** @internal */
15470
- const Order$5 = /*#__PURE__*/ make$90((self, that) => self.epochMilliseconds < that.epochMilliseconds ? -1 : self.epochMilliseconds > that.epochMilliseconds ? 1 : 0);
15601
+ const Order$5 = /*#__PURE__*/ make$91((self, that) => self.epochMilliseconds < that.epochMilliseconds ? -1 : self.epochMilliseconds > that.epochMilliseconds ? 1 : 0);
15471
15602
  const makeUtc = (epochMillis) => {
15472
15603
  const self = Object.create(ProtoUtc);
15473
15604
  self.epochMilliseconds = epochMillis;
@@ -15823,6 +15954,52 @@ const Number$5 = globalThis.Number;
15823
15954
  */
15824
15955
  const Order$4 = Number$6;
15825
15956
  /**
15957
+ * Returns the maximum between two `number`s.
15958
+ *
15959
+ * **When to use**
15960
+ *
15961
+ * Use to select the larger of two numbers.
15962
+ *
15963
+ * **Example** (Finding the maximum)
15964
+ *
15965
+ * ```ts import.meta.vitest
15966
+ * import { Number } from "effect"
15967
+ *
15968
+ * Number.max(2, 3) // => 3
15969
+ * ```
15970
+ *
15971
+ * @see {@link min} for selecting the smaller value
15972
+ *
15973
+ * @stability stable
15974
+ * @category math
15975
+ * @since 2.0.0
15976
+ */
15977
+ const max = /*#__PURE__*/ max$2(Order$4);
15978
+ /**
15979
+ * Returns the next power of 2 from the given number.
15980
+ *
15981
+ * **When to use**
15982
+ *
15983
+ * Use to round a number up to the next power of two.
15984
+ *
15985
+ * **Example** (Finding the next power of two)
15986
+ *
15987
+ * ```ts import.meta.vitest
15988
+ * import { Number } from "effect"
15989
+ *
15990
+ * Number.nextPow2(5) // => 8
15991
+ * Number.nextPow2(17) // => 32
15992
+ * ```
15993
+ *
15994
+ * @stability stable
15995
+ * @category math
15996
+ * @since 2.0.0
15997
+ */
15998
+ const nextPow2 = (n) => {
15999
+ const nextPow = Math.pow(2, Math.ceil(Math.log2(n)));
16000
+ return Math.max(nextPow < n ? nextPow * 2 : nextPow, 2);
16001
+ };
16002
+ /**
15826
16003
  * Parses a `number` from a `string` safely using the `Number()` function.
15827
16004
  * The following special string values are supported: "NaN", "Infinity", "-Infinity".
15828
16005
  *
@@ -16628,7 +16805,7 @@ const minDuration = (results) => {
16628
16805
  let min = void 0;
16629
16806
  for (let i = 0; i < results.length; i++) {
16630
16807
  const duration = results[i];
16631
- if (duration !== void 0) min = min === void 0 ? duration : min$1(min, duration);
16808
+ if (duration !== void 0) min = min === void 0 ? duration : min$2(min, duration);
16632
16809
  }
16633
16810
  return min;
16634
16811
  };
@@ -17069,7 +17246,7 @@ const fromIterable$5 = (entries) => {
17069
17246
  * @category getters
17070
17247
  * @since 2.0.0
17071
17248
  */
17072
- const get$9 = /*#__PURE__*/ dual(2, (self, key) => {
17249
+ const get$10 = /*#__PURE__*/ dual(2, (self, key) => {
17073
17250
  if (self.backing.has(key)) return some$1(self.backing.get(key));
17074
17251
  else if (isSimpleKey(key)) return none();
17075
17252
  const hash$4 = hash(key);
@@ -21499,6 +21676,27 @@ const schedule = /*#__PURE__*/ dual(2, (self, schedule) => scheduleFrom(self, vo
21499
21676
  */
21500
21677
  const scheduleFrom = scheduleFrom$1;
21501
21678
  /**
21679
+ * Returns the current tracer from the context.
21680
+ *
21681
+ * **Example** (Accessing the current tracer)
21682
+ *
21683
+ * ```ts import.meta.vitest
21684
+ * import { Effect } from "effect"
21685
+ *
21686
+ * const program = Effect.gen(function*() {
21687
+ * const currentTracer = yield* Effect.tracer
21688
+ * return typeof currentTracer.span
21689
+ * })
21690
+ *
21691
+ * Effect.runSync(program) // => "function"
21692
+ * ```
21693
+ *
21694
+ * @stability stable
21695
+ * @category tracing
21696
+ * @since 2.0.0
21697
+ */
21698
+ const tracer$1 = tracer$2;
21699
+ /**
21502
21700
  * Enables or disables tracing for spans created by the given effect.
21503
21701
  *
21504
21702
  * **Details**
@@ -22993,7 +23191,7 @@ const concat$3 = (chunks) => {
22993
23191
  * @category instances
22994
23192
  * @since 4.0.6
22995
23193
  */
22996
- const Order$2 = /*#__PURE__*/ make$90((self, that) => {
23194
+ const Order$2 = /*#__PURE__*/ make$91((self, that) => {
22997
23195
  const length = Math.min(self.length, that.length);
22998
23196
  for (let i = 0; i < length; i++) if (self[i] !== that[i]) return self[i] < that[i] ? -1 : 1;
22999
23197
  return self.length < that.length ? -1 : self.length > that.length ? 1 : 0;
@@ -23082,7 +23280,7 @@ const Ipv4Proto = {
23082
23280
  return isIpv4Address(that) && ipv4Value(this) === ipv4Value(that);
23083
23281
  },
23084
23282
  [symbol$3]() {
23085
- return optimize(combine$3(ipv4HashSeed, ipv4Value(this) | 0));
23283
+ return optimize(combine$4(ipv4HashSeed, ipv4Value(this) | 0));
23086
23284
  },
23087
23285
  toString() {
23088
23286
  return formatIp(this);
@@ -23103,10 +23301,10 @@ const Ipv6Proto = {
23103
23301
  },
23104
23302
  [symbol$3]() {
23105
23303
  const self = ipv6Words(this);
23106
- let h = combine$3(ipv6HashSeed, self.w0 | 0);
23107
- h = combine$3(h, self.w1 | 0);
23108
- h = combine$3(h, self.w2 | 0);
23109
- return optimize(combine$3(h, self.w3 | 0));
23304
+ let h = combine$4(ipv6HashSeed, self.w0 | 0);
23305
+ h = combine$4(h, self.w1 | 0);
23306
+ h = combine$4(h, self.w2 | 0);
23307
+ return optimize(combine$4(h, self.w3 | 0));
23110
23308
  },
23111
23309
  toString() {
23112
23310
  return formatIp(this);
@@ -23367,7 +23565,7 @@ const InetV4Proto = {
23367
23565
  return isInetAddressV4(that) && this.port === that.port && equals$1(this.address, that.address);
23368
23566
  },
23369
23567
  [symbol$3]() {
23370
- return combine$3(hash(this.address), number$2(this.port));
23568
+ return combine$4(hash(this.address), number$2(this.port));
23371
23569
  },
23372
23570
  toString() {
23373
23571
  return formatInet(this);
@@ -23384,7 +23582,7 @@ const InetV6Proto = {
23384
23582
  return isInetAddressV6(that) && this.port === that.port && this.scopeId === that.scopeId && equals$1(this.address, that.address);
23385
23583
  },
23386
23584
  [symbol$3]() {
23387
- return combine$3(combine$3(hash(this.address), number$2(this.port)), number$2(this.scopeId));
23585
+ return combine$4(combine$4(hash(this.address), number$2(this.port)), number$2(this.scopeId));
23388
23586
  },
23389
23587
  toString() {
23390
23588
  return formatInet(this);
@@ -23598,7 +23796,7 @@ const UnixPathProto = {
23598
23796
  return isUnixPathAddress(that) && this.path === that.path;
23599
23797
  },
23600
23798
  [symbol$3]() {
23601
- return combine$3(string$2("UnixPathAddress"), string$2(this.path));
23799
+ return combine$4(string$2("UnixPathAddress"), string$2(this.path));
23602
23800
  },
23603
23801
  toString() {
23604
23802
  return this.path;
@@ -24889,7 +25087,7 @@ const emptyArray = [];
24889
25087
  * @category instances
24890
25088
  * @since 4.0.0
24891
25089
  */
24892
- const makeEquivalence$1 = (isEquivalent) => make$91((self, that) => {
25090
+ const makeEquivalence$1 = (isEquivalent) => make$92((self, that) => {
24893
25091
  if (self.length !== that.length) return false;
24894
25092
  const as = toReadonlyArray(self);
24895
25093
  const bs = toReadonlyArray(that);
@@ -25168,6 +25366,44 @@ const make$79 = (value) => {
25168
25366
  return ref;
25169
25367
  };
25170
25368
  /**
25369
+ * Gets the current value of the MutableRef.
25370
+ *
25371
+ * **When to use**
25372
+ *
25373
+ * Use to read the current `MutableRef` value without mutating it.
25374
+ *
25375
+ * **Example** (Reading current values)
25376
+ *
25377
+ * ```ts import.meta.vitest
25378
+ * import { MutableRef } from "effect"
25379
+ *
25380
+ * const ref = MutableRef.make("hello")
25381
+ *
25382
+ * MutableRef.get(ref) // => "hello"
25383
+ *
25384
+ * MutableRef.set(ref, "world")
25385
+ *
25386
+ * MutableRef.get(ref) // => "world"
25387
+ *
25388
+ * // Reading complex objects
25389
+ * const config = MutableRef.make({ port: 3000, host: "localhost" })
25390
+ * const currentConfig = MutableRef.get(config)
25391
+ *
25392
+ * currentConfig // => { port: 3000, host: "localhost" }
25393
+ *
25394
+ * // Multiple reads return the same value
25395
+ * const value1 = MutableRef.get(ref)
25396
+ * const value2 = MutableRef.get(ref)
25397
+ *
25398
+ * value1 === value2 // => true
25399
+ * ```
25400
+ *
25401
+ * @stability stable
25402
+ * @category getters
25403
+ * @since 2.0.0
25404
+ */
25405
+ const get$9 = (self) => self.current;
25406
+ /**
25171
25407
  * Sets the MutableRef to a new value and returns the reference.
25172
25408
  *
25173
25409
  * **When to use**
@@ -25696,6 +25932,19 @@ const filter = (self, f) => {
25696
25932
  */
25697
25933
  const remove$3 = (self, value) => filter(self, (v) => v !== value);
25698
25934
  // ../../node_modules/.pnpm/effect@4.1.7/node_modules/effect/dist/PubSub.js
25935
+ /**
25936
+ * Broadcasts values from publishers to many subscribers.
25937
+ *
25938
+ * Publishers add messages with `publish` or `publishAll`, and each active
25939
+ * `Subscription` receives its own copy of every accepted message. Unlike a
25940
+ * queue, subscribers do not compete for messages. This module includes bounded,
25941
+ * dropping, sliding, and unbounded hubs, optional replay buffers for late
25942
+ * subscribers, message-taking helpers, capacity and shutdown operations, a
25943
+ * type guard, and low-level types for custom hub strategies.
25944
+ *
25945
+ * @stability stable
25946
+ * @since 2.0.0
25947
+ */
25699
25948
  const TypeId$59 = "~effect/PubSub";
25700
25949
  const SubscriptionTypeId = "~effect/PubSub/Subscription";
25701
25950
  /**
@@ -25729,6 +25978,137 @@ const SubscriptionTypeId = "~effect/PubSub/Subscription";
25729
25978
  */
25730
25979
  const make$77 = (options) => sync(() => makePubSubUnsafe(options.atomicPubSub(), /* @__PURE__ */ new Map(), makeUnsafe$7(), makeUnsafe$5(false), make$79(false), options.strategy(), make$79(none())));
25731
25980
  /**
25981
+ * Creates a bounded `PubSub` that applies backpressure when it reaches
25982
+ * capacity.
25983
+ *
25984
+ * **Details**
25985
+ *
25986
+ * Published messages are retained until all current subscribers have taken
25987
+ * them. When the capacity is full, publishers suspend until space is available.
25988
+ * Pass an options object to configure both `capacity` and an optional replay
25989
+ * buffer for late subscribers.
25990
+ * The capacity must be a positive integer or `Infinity` for unbounded storage.
25991
+ * Invalid capacities cause the effect to die.
25992
+ *
25993
+ * **Example** (Creating a bounded PubSub)
25994
+ *
25995
+ * ```ts import.meta.vitest
25996
+ * import { Effect, PubSub } from "effect"
25997
+ *
25998
+ * const program = Effect.gen(function*() {
25999
+ * // Create bounded PubSub with capacity 100
26000
+ * const pubsub = yield* PubSub.bounded<string>(100)
26001
+ *
26002
+ * // Create with replay buffer for late subscribers
26003
+ * const pubsubWithReplay = yield* PubSub.bounded<string>({
26004
+ * capacity: 100,
26005
+ * replay: 10 // Last 10 messages replayed to new subscribers
26006
+ * })
26007
+ *
26008
+ * const capacities = [PubSub.capacity(pubsub), PubSub.capacity(pubsubWithReplay)]
26009
+ * yield* PubSub.shutdown(pubsub)
26010
+ * yield* PubSub.shutdown(pubsubWithReplay)
26011
+ * return capacities
26012
+ * })
26013
+ *
26014
+ * const actual = await Effect.runPromise(program)
26015
+ * actual // => [100, 100]
26016
+ * ```
26017
+ *
26018
+ * @stability stable
26019
+ * @category constructors
26020
+ * @since 2.0.0
26021
+ */
26022
+ const bounded$1 = (capacity) => make$77({
26023
+ atomicPubSub: () => makeAtomicBounded(capacity),
26024
+ strategy: () => new BackPressureStrategy()
26025
+ });
26026
+ /**
26027
+ * Creates a bounded `PubSub` with the dropping strategy. The `PubSub` will drop new
26028
+ * messages if the `PubSub` is at capacity.
26029
+ *
26030
+ * **Details**
26031
+ *
26032
+ * The capacity must be a positive integer or `Infinity` for unbounded storage.
26033
+ * Invalid capacities cause the effect to die.
26034
+ * For best performance use capacities that are powers of two.
26035
+ *
26036
+ * **Example** (Dropping messages when full)
26037
+ *
26038
+ * ```ts import.meta.vitest
26039
+ * import { Effect, PubSub } from "effect"
26040
+ *
26041
+ * const program = Effect.scoped(Effect.gen(function*() {
26042
+ * // Create dropping PubSub that drops new messages when full
26043
+ * const pubsub = yield* PubSub.dropping<string>(3)
26044
+ *
26045
+ * const subscription = yield* PubSub.subscribe(pubsub)
26046
+ *
26047
+ * // Fill the PubSub and see dropping behavior
26048
+ * yield* PubSub.publish(pubsub, "msg1") // succeeds
26049
+ * yield* PubSub.publish(pubsub, "msg2") // succeeds
26050
+ * yield* PubSub.publish(pubsub, "msg3") // succeeds
26051
+ * const dropped = yield* PubSub.publish(pubsub, "msg4") // returns false (dropped)
26052
+ *
26053
+ * const messages = yield* PubSub.takeAll(subscription)
26054
+ * return { dropped: !dropped, messages }
26055
+ * }))
26056
+ *
26057
+ * const actual = await Effect.runPromise(program)
26058
+ * actual // => { dropped: true, messages: ["msg1", "msg2", "msg3"] }
26059
+ * ```
26060
+ *
26061
+ * @stability stable
26062
+ * @category constructors
26063
+ * @since 2.0.0
26064
+ */
26065
+ const dropping$1 = (capacity) => make$77({
26066
+ atomicPubSub: () => makeAtomicBounded(capacity),
26067
+ strategy: () => new DroppingStrategy()
26068
+ });
26069
+ /**
26070
+ * Creates a bounded `PubSub` with the sliding strategy. The `PubSub` will add new
26071
+ * messages and drop old messages if the `PubSub` is at capacity.
26072
+ *
26073
+ * **Details**
26074
+ *
26075
+ * The capacity must be a positive integer or `Infinity` for unbounded storage.
26076
+ * Invalid capacities cause the effect to die.
26077
+ * For best performance use capacities that are powers of two.
26078
+ *
26079
+ * **Example** (Sliding old messages when full)
26080
+ *
26081
+ * ```ts import.meta.vitest
26082
+ * import { Effect, PubSub } from "effect"
26083
+ *
26084
+ * const program = Effect.scoped(Effect.gen(function*() {
26085
+ * // Create sliding PubSub that evicts old messages when full
26086
+ * const pubsub = yield* PubSub.sliding<string>(3)
26087
+ *
26088
+ * const subscription = yield* PubSub.subscribe(pubsub)
26089
+ *
26090
+ * // Fill and overflow the PubSub
26091
+ * yield* PubSub.publish(pubsub, "msg1")
26092
+ * yield* PubSub.publish(pubsub, "msg2")
26093
+ * yield* PubSub.publish(pubsub, "msg3")
26094
+ * yield* PubSub.publish(pubsub, "msg4") // "msg1" is evicted
26095
+ *
26096
+ * return yield* PubSub.takeAll(subscription)
26097
+ * }))
26098
+ *
26099
+ * const actual = await Effect.runPromise(program)
26100
+ * actual // => ["msg2", "msg3", "msg4"]
26101
+ * ```
26102
+ *
26103
+ * @stability stable
26104
+ * @category constructors
26105
+ * @since 2.0.0
26106
+ */
26107
+ const sliding$1 = (capacity) => make$77({
26108
+ atomicPubSub: () => makeAtomicBounded(capacity),
26109
+ strategy: () => new SlidingStrategy()
26110
+ });
26111
+ /**
25732
26112
  * Creates an unbounded `PubSub`.
25733
26113
  *
25734
26114
  * **Example** (Creating an unbounded PubSub)
@@ -25763,6 +26143,45 @@ const unbounded = (options) => make$77({
25763
26143
  strategy: () => new DroppingStrategy()
25764
26144
  });
25765
26145
  /**
26146
+ * Creates a bounded atomic PubSub implementation with optional replay buffer.
26147
+ *
26148
+ * **When to use**
26149
+ *
26150
+ * Use to provide bounded message storage when building a custom `PubSub` with
26151
+ * `make` and an explicit delivery strategy.
26152
+ *
26153
+ * **Details**
26154
+ *
26155
+ * Pass either a capacity number or an options object with `capacity` and
26156
+ * optional `replay`. A positive `replay` value enables a replay buffer for late
26157
+ * subscribers, and fractional replay sizes are rounded up.
26158
+ *
26159
+ * **Gotchas**
26160
+ *
26161
+ * The capacity must be a positive integer or `Infinity` for unbounded storage;
26162
+ * invalid capacities throw synchronously before an atomic implementation is
26163
+ * created.
26164
+ *
26165
+ * @see {@link make} for constructing a `PubSub` from an atomic implementation and delivery strategy
26166
+ * @see {@link makeAtomicUnbounded} for an atomic implementation without a bounded capacity
26167
+ * @see {@link bounded} for the higher-level backpressure constructor
26168
+ * @see {@link dropping} for the higher-level dropping constructor
26169
+ * @see {@link sliding} for the higher-level sliding constructor
26170
+ *
26171
+ * @stability stable
26172
+ * @category constructors
26173
+ * @since 4.0.0
26174
+ */
26175
+ const makeAtomicBounded = (capacity) => {
26176
+ const options = typeof capacity === "number" ? { capacity } : capacity;
26177
+ ensureCapacity(options.capacity);
26178
+ if (options.capacity === Infinity) return makeAtomicUnbounded(options);
26179
+ const replayBuffer = options.replay && options.replay > 0 ? new ReplayBuffer(Math.ceil(options.replay)) : void 0;
26180
+ if (options.capacity === 1) return new BoundedPubSubSingle(replayBuffer);
26181
+ else if (nextPow2(options.capacity) === options.capacity) return new BoundedPubSubPow2(options.capacity, replayBuffer);
26182
+ else return new BoundedPubSubArb(options.capacity, replayBuffer);
26183
+ };
26184
+ /**
25766
26185
  * Creates an unbounded atomic PubSub implementation with optional replay buffer.
25767
26186
  *
25768
26187
  * **When to use**
@@ -25788,6 +26207,133 @@ const makeAtomicUnbounded = (options) => {
25788
26207
  return new UnboundedPubSub(replay && replay > 0 ? new ReplayBuffer(Math.ceil(replay)) : void 0);
25789
26208
  };
25790
26209
  /**
26210
+ * Shuts down the `PubSub`, interrupting suspended publishers and subscribers
26211
+ * and finalizing active subscriptions.
26212
+ *
26213
+ * **Details**
26214
+ *
26215
+ * After shutdown, `publish` and `publishAll` succeed with `false`,
26216
+ * `publishUnsafe` returns `false`, and subscription operations such as `take`
26217
+ * interrupt.
26218
+ *
26219
+ * **Example** (Shutting down a PubSub)
26220
+ *
26221
+ * ```ts import.meta.vitest
26222
+ * import { Effect, PubSub } from "effect"
26223
+ *
26224
+ * const program = Effect.gen(function*() {
26225
+ * const pubsub = yield* PubSub.bounded<string>(1)
26226
+ *
26227
+ * // Shutdown the PubSub
26228
+ * yield* PubSub.shutdown(pubsub)
26229
+ *
26230
+ * const isShutdown = yield* PubSub.isShutdown(pubsub)
26231
+ *
26232
+ * // Publishing after shutdown returns false
26233
+ * const published = yield* PubSub.publish(pubsub, "msg1")
26234
+ * return { isShutdown, published }
26235
+ * })
26236
+ *
26237
+ * const actual = await Effect.runPromise(program)
26238
+ * actual // => { isShutdown: true, published: false }
26239
+ * ```
26240
+ *
26241
+ * @stability stable
26242
+ * @category lifecycle
26243
+ * @since 2.0.0
26244
+ */
26245
+ const shutdown$1 = (self) => uninterruptible(withFiber((fiber) => {
26246
+ set$2(self.shutdownFlag, true);
26247
+ return close(self.scope, interrupt$2(fiber.id)).pipe(andThen(self.strategy.shutdown), when$2(self.shutdownHook.open), asVoid);
26248
+ }));
26249
+ /**
26250
+ * Ends the `PubSub` with a final message.
26251
+ *
26252
+ * **When to use**
26253
+ *
26254
+ * Use to tell every subscriber that no more messages will follow, without
26255
+ * losing the messages they have not consumed yet.
26256
+ *
26257
+ * **Details**
26258
+ *
26259
+ * Later publishes return `false`, as do publishers waiting for capacity when
26260
+ * `end` is called. Each subscriber receives the messages already buffered
26261
+ * for it, then the final message. Subscribers that arrive
26262
+ * after the end receive the replayed messages, if any, and then the final
26263
+ * message. The final message never occupies capacity, so a bounded `PubSub`
26264
+ * cannot drop it. Returns `false` if the `PubSub` was already ended or shut
26265
+ * down.
26266
+ *
26267
+ * `take`, `takeAll`, and `takeBetween` deliver the final message;
26268
+ * non-suspending `takeUpTo` does not.
26269
+ *
26270
+ * **Gotchas**
26271
+ *
26272
+ * The final message is sticky: subsequent takes return it again. Consumers
26273
+ * must treat it as terminal rather than continuing to take messages.
26274
+ *
26275
+ * **Example** (Ending a PubSub)
26276
+ *
26277
+ * ```ts import.meta.vitest
26278
+ * import { Effect, PubSub } from "effect"
26279
+ *
26280
+ * const program = Effect.scoped(Effect.gen(function*() {
26281
+ * const pubsub = yield* PubSub.bounded<string>(2)
26282
+ * const subscription = yield* PubSub.subscribe(pubsub)
26283
+ *
26284
+ * yield* PubSub.publish(pubsub, "Hello")
26285
+ * const ended = yield* PubSub.end(pubsub, "Bye")
26286
+ *
26287
+ * // Later publishes are rejected
26288
+ * const published = yield* PubSub.publish(pubsub, "World")
26289
+ *
26290
+ * // Buffered messages are delivered before the final message
26291
+ * const first = yield* PubSub.take(subscription)
26292
+ * const last = yield* PubSub.take(subscription)
26293
+ *
26294
+ * // Late subscribers receive the final message too
26295
+ * const late = yield* PubSub.subscribe(pubsub)
26296
+ * const lateMessage = yield* PubSub.take(late)
26297
+ * return [ended, published, first, last, lateMessage]
26298
+ * }))
26299
+ *
26300
+ * const actual = await Effect.runPromise(program)
26301
+ * actual // => [true, false, "Hello", "Bye", "Bye"]
26302
+ * ```
26303
+ *
26304
+ * @see {@link shutdown} for interrupting subscribers instead of delivering a final message
26305
+ *
26306
+ * @stability stable
26307
+ * @category lifecycle
26308
+ * @since 4.0.0
26309
+ */
26310
+ const end$2 = /*#__PURE__*/ dual(2, (self, value) => sync(() => endUnsafe$1(self, value)));
26311
+ /**
26312
+ * Ends the `PubSub` with a final message synchronously.
26313
+ *
26314
+ * **Details**
26315
+ *
26316
+ * See {@link end} for the semantics.
26317
+ *
26318
+ * @stability stable
26319
+ * @category lifecycle
26320
+ * @since 4.0.0
26321
+ */
26322
+ const endUnsafe$1 = /*#__PURE__*/ dual(2, (self, value) => {
26323
+ if (self.shutdownFlag.current || isSome(self.ended.current)) return false;
26324
+ set$2(self.ended, some$1(value));
26325
+ if (self.strategy instanceof BackPressureStrategy) {
26326
+ for (const [_, deferred, last] of takeAll$1(self.strategy.publishers)) if (last) doneUnsafe(deferred, succeed$8(false));
26327
+ }
26328
+ const exit = succeed$8(value);
26329
+ for (const pollersSet of self.subscribers.values()) for (const pollers of pollersSet) {
26330
+ let poller;
26331
+ while ((poller = take$2(pollers)) !== Empty$2) doneUnsafe(poller, exit);
26332
+ }
26333
+ self.subscribers.clear();
26334
+ return true;
26335
+ });
26336
+ /**
25791
26337
  * Publishes a message to the `PubSub` as an `Effect`, returning whether the
25792
26338
  * message was accepted.
25793
26339
  *
@@ -25891,7 +26437,7 @@ const publish = /*#__PURE__*/ dual(2, (self, value) => suspend$3(() => {
25891
26437
  * @since 2.0.0
25892
26438
  */
25893
26439
  const subscribe = (self) => uninterruptible(contextWith((services) => {
25894
- const localScope = get$12(services, Scope);
26440
+ const localScope = get$13(services, Scope);
25895
26441
  const scope = forkUnsafe(self.scope);
25896
26442
  const subscription = makeSubscriptionUnsafe(self.pubsub, self.subscribers, self.strategy, self.ended);
25897
26443
  return addFinalizer$1(scope, unsubscribe(subscription)).pipe(andThen(addFinalizerExit(localScope, (exit) => close(scope, exit))), as(subscription));
@@ -25988,6 +26534,406 @@ const removeSubscribers = (subscribers, subscription, pollers) => {
25988
26534
  if (set.size === 0) subscribers.delete(subscription);
25989
26535
  };
25990
26536
  const makeSubscriptionUnsafe = (pubsub, subscribers, strategy, ended) => new SubscriptionImpl(pubsub, subscribers, pubsub.subscribe(), make$78(), makeUnsafe$5(false), make$79(false), strategy, pubsub.replayWindow(), ended);
26537
+ var BoundedPubSubArb = class {
26538
+ array;
26539
+ replayIndices;
26540
+ publisherIndex = 0;
26541
+ subscribers;
26542
+ subscriberCount = 0;
26543
+ subscribersIndex = 0;
26544
+ capacity;
26545
+ replayBuffer;
26546
+ constructor(capacity, replayBuffer) {
26547
+ this.capacity = capacity;
26548
+ this.replayBuffer = replayBuffer;
26549
+ this.array = Array.from({ length: capacity });
26550
+ this.replayIndices = replayBuffer ? Array.from({ length: capacity }) : [];
26551
+ this.subscribers = Array.from({ length: capacity });
26552
+ }
26553
+ replayWindow() {
26554
+ return this.replayBuffer ? new ReplayWindowImpl(this.replayBuffer) : emptyReplayWindow;
26555
+ }
26556
+ isEmpty() {
26557
+ return this.publisherIndex === this.subscribersIndex;
26558
+ }
26559
+ isFull() {
26560
+ return this.publisherIndex === this.subscribersIndex + this.capacity;
26561
+ }
26562
+ size() {
26563
+ return this.publisherIndex - this.subscribersIndex;
26564
+ }
26565
+ publish(value) {
26566
+ if (this.isFull()) return false;
26567
+ const replayIndex = this.replayBuffer?.offer(value);
26568
+ if (this.subscriberCount !== 0) {
26569
+ const index = this.publisherIndex % this.capacity;
26570
+ this.array[index] = value;
26571
+ if (replayIndex !== void 0) this.replayIndices[index] = replayIndex;
26572
+ this.subscribers[index] = this.subscriberCount;
26573
+ this.publisherIndex += 1;
26574
+ }
26575
+ return true;
26576
+ }
26577
+ publishAll(elements) {
26578
+ if (this.subscriberCount === 0) {
26579
+ if (this.replayBuffer) this.replayBuffer.offerAll(elements);
26580
+ return [];
26581
+ }
26582
+ const chunk = fromIterable$6(elements);
26583
+ const n = chunk.length;
26584
+ const size = this.publisherIndex - this.subscribersIndex;
26585
+ const available = this.capacity - size;
26586
+ const forPubSub = Math.min(n, available);
26587
+ if (forPubSub === 0) return chunk;
26588
+ let iteratorIndex = 0;
26589
+ const publishAllIndex = this.publisherIndex + forPubSub;
26590
+ while (this.publisherIndex !== publishAllIndex) {
26591
+ const a = chunk[iteratorIndex++];
26592
+ const index = this.publisherIndex % this.capacity;
26593
+ this.array[index] = a;
26594
+ const replayIndex = this.replayBuffer?.offer(a);
26595
+ if (replayIndex !== void 0) this.replayIndices[index] = replayIndex;
26596
+ this.subscribers[index] = this.subscriberCount;
26597
+ this.publisherIndex += 1;
26598
+ }
26599
+ return chunk.slice(iteratorIndex);
26600
+ }
26601
+ slide() {
26602
+ if (this.subscribersIndex !== this.publisherIndex) {
26603
+ const index = this.subscribersIndex % this.capacity;
26604
+ const value = this.array[index];
26605
+ this.array[index] = AbsentValue;
26606
+ this.subscribers[index] = 0;
26607
+ this.subscribersIndex += 1;
26608
+ this.replayBuffer?.slide(value, this.replayIndices[index]);
26609
+ }
26610
+ }
26611
+ subscribe() {
26612
+ this.subscriberCount += 1;
26613
+ return new BoundedPubSubArbSubscription(this, this.publisherIndex, false);
26614
+ }
26615
+ };
26616
+ var BoundedPubSubArbSubscription = class {
26617
+ self;
26618
+ subscriberIndex;
26619
+ unsubscribed;
26620
+ constructor(self, subscriberIndex, unsubscribed) {
26621
+ this.self = self;
26622
+ this.subscriberIndex = subscriberIndex;
26623
+ this.unsubscribed = unsubscribed;
26624
+ }
26625
+ isEmpty() {
26626
+ return this.unsubscribed || this.self.publisherIndex === this.subscriberIndex || this.self.publisherIndex === this.self.subscribersIndex;
26627
+ }
26628
+ size() {
26629
+ if (this.unsubscribed) return 0;
26630
+ return this.self.publisherIndex - Math.max(this.subscriberIndex, this.self.subscribersIndex);
26631
+ }
26632
+ poll() {
26633
+ if (this.unsubscribed) return Empty$2;
26634
+ this.subscriberIndex = Math.max(this.subscriberIndex, this.self.subscribersIndex);
26635
+ if (this.subscriberIndex !== this.self.publisherIndex) {
26636
+ const index = this.subscriberIndex % this.self.capacity;
26637
+ const elem = this.self.array[index];
26638
+ this.self.subscribers[index] -= 1;
26639
+ if (this.self.subscribers[index] === 0) {
26640
+ this.self.array[index] = AbsentValue;
26641
+ this.self.subscribersIndex += 1;
26642
+ }
26643
+ this.subscriberIndex += 1;
26644
+ return elem;
26645
+ }
26646
+ return Empty$2;
26647
+ }
26648
+ pollUpTo(n) {
26649
+ n = normalize$2(n);
26650
+ if (this.unsubscribed) return [];
26651
+ this.subscriberIndex = Math.max(this.subscriberIndex, this.self.subscribersIndex);
26652
+ const size = this.self.publisherIndex - this.subscriberIndex;
26653
+ const toPoll = Math.min(n, size);
26654
+ if (toPoll <= 0) return [];
26655
+ const builder = [];
26656
+ const pollUpToIndex = this.subscriberIndex + toPoll;
26657
+ while (this.subscriberIndex !== pollUpToIndex) {
26658
+ const index = this.subscriberIndex % this.self.capacity;
26659
+ const a = this.self.array[index];
26660
+ this.self.subscribers[index] -= 1;
26661
+ if (this.self.subscribers[index] === 0) {
26662
+ this.self.array[index] = AbsentValue;
26663
+ this.self.subscribersIndex += 1;
26664
+ }
26665
+ builder.push(a);
26666
+ this.subscriberIndex += 1;
26667
+ }
26668
+ return builder;
26669
+ }
26670
+ unsubscribe() {
26671
+ if (!this.unsubscribed) {
26672
+ this.unsubscribed = true;
26673
+ this.self.subscriberCount -= 1;
26674
+ this.subscriberIndex = Math.max(this.subscriberIndex, this.self.subscribersIndex);
26675
+ while (this.subscriberIndex !== this.self.publisherIndex) {
26676
+ const index = this.subscriberIndex % this.self.capacity;
26677
+ this.self.subscribers[index] -= 1;
26678
+ if (this.self.subscribers[index] === 0) {
26679
+ this.self.array[index] = AbsentValue;
26680
+ this.self.subscribersIndex += 1;
26681
+ }
26682
+ this.subscriberIndex += 1;
26683
+ }
26684
+ }
26685
+ }
26686
+ };
26687
+ var BoundedPubSubPow2 = class {
26688
+ array;
26689
+ replayIndices;
26690
+ mask;
26691
+ publisherIndex = 0;
26692
+ subscribers;
26693
+ subscriberCount = 0;
26694
+ subscribersIndex = 0;
26695
+ capacity;
26696
+ replayBuffer;
26697
+ constructor(capacity, replayBuffer) {
26698
+ this.capacity = capacity;
26699
+ this.replayBuffer = replayBuffer;
26700
+ this.array = Array.from({ length: capacity });
26701
+ this.replayIndices = replayBuffer ? Array.from({ length: capacity }) : [];
26702
+ this.mask = capacity - 1;
26703
+ this.subscribers = Array.from({ length: capacity });
26704
+ }
26705
+ replayWindow() {
26706
+ return this.replayBuffer ? new ReplayWindowImpl(this.replayBuffer) : emptyReplayWindow;
26707
+ }
26708
+ isEmpty() {
26709
+ return this.publisherIndex === this.subscribersIndex;
26710
+ }
26711
+ isFull() {
26712
+ return this.publisherIndex === this.subscribersIndex + this.capacity;
26713
+ }
26714
+ size() {
26715
+ return this.publisherIndex - this.subscribersIndex;
26716
+ }
26717
+ publish(value) {
26718
+ if (this.isFull()) return false;
26719
+ const replayIndex = this.replayBuffer?.offer(value);
26720
+ if (this.subscriberCount !== 0) {
26721
+ const index = this.publisherIndex & this.mask;
26722
+ this.array[index] = value;
26723
+ if (replayIndex !== void 0) this.replayIndices[index] = replayIndex;
26724
+ this.subscribers[index] = this.subscriberCount;
26725
+ this.publisherIndex += 1;
26726
+ }
26727
+ return true;
26728
+ }
26729
+ publishAll(elements) {
26730
+ if (this.subscriberCount === 0) {
26731
+ if (this.replayBuffer) this.replayBuffer.offerAll(elements);
26732
+ return [];
26733
+ }
26734
+ const chunk = fromIterable$6(elements);
26735
+ const n = chunk.length;
26736
+ const size = this.publisherIndex - this.subscribersIndex;
26737
+ const available = this.capacity - size;
26738
+ const forPubSub = Math.min(n, available);
26739
+ if (forPubSub === 0) return chunk;
26740
+ let iteratorIndex = 0;
26741
+ const publishAllIndex = this.publisherIndex + forPubSub;
26742
+ while (this.publisherIndex !== publishAllIndex) {
26743
+ const elem = chunk[iteratorIndex++];
26744
+ const index = this.publisherIndex & this.mask;
26745
+ this.array[index] = elem;
26746
+ const replayIndex = this.replayBuffer?.offer(elem);
26747
+ if (replayIndex !== void 0) this.replayIndices[index] = replayIndex;
26748
+ this.subscribers[index] = this.subscriberCount;
26749
+ this.publisherIndex += 1;
26750
+ }
26751
+ return chunk.slice(iteratorIndex);
26752
+ }
26753
+ slide() {
26754
+ if (this.subscribersIndex !== this.publisherIndex) {
26755
+ const index = this.subscribersIndex & this.mask;
26756
+ const value = this.array[index];
26757
+ this.array[index] = AbsentValue;
26758
+ this.subscribers[index] = 0;
26759
+ this.subscribersIndex += 1;
26760
+ this.replayBuffer?.slide(value, this.replayIndices[index]);
26761
+ }
26762
+ }
26763
+ subscribe() {
26764
+ this.subscriberCount += 1;
26765
+ return new BoundedPubSubPow2Subscription(this, this.publisherIndex, false);
26766
+ }
26767
+ };
26768
+ var BoundedPubSubPow2Subscription = class {
26769
+ self;
26770
+ subscriberIndex;
26771
+ unsubscribed;
26772
+ constructor(self, subscriberIndex, unsubscribed) {
26773
+ this.self = self;
26774
+ this.subscriberIndex = subscriberIndex;
26775
+ this.unsubscribed = unsubscribed;
26776
+ }
26777
+ isEmpty() {
26778
+ return this.unsubscribed || this.self.publisherIndex === this.subscriberIndex || this.self.publisherIndex === this.self.subscribersIndex;
26779
+ }
26780
+ size() {
26781
+ if (this.unsubscribed) return 0;
26782
+ return this.self.publisherIndex - Math.max(this.subscriberIndex, this.self.subscribersIndex);
26783
+ }
26784
+ poll() {
26785
+ if (this.unsubscribed) return Empty$2;
26786
+ this.subscriberIndex = Math.max(this.subscriberIndex, this.self.subscribersIndex);
26787
+ if (this.subscriberIndex !== this.self.publisherIndex) {
26788
+ const index = this.subscriberIndex & this.self.mask;
26789
+ const elem = this.self.array[index];
26790
+ this.self.subscribers[index] -= 1;
26791
+ if (this.self.subscribers[index] === 0) {
26792
+ this.self.array[index] = AbsentValue;
26793
+ this.self.subscribersIndex += 1;
26794
+ }
26795
+ this.subscriberIndex += 1;
26796
+ return elem;
26797
+ }
26798
+ return Empty$2;
26799
+ }
26800
+ pollUpTo(n) {
26801
+ n = normalize$2(n);
26802
+ if (this.unsubscribed) return [];
26803
+ this.subscriberIndex = Math.max(this.subscriberIndex, this.self.subscribersIndex);
26804
+ const size = this.self.publisherIndex - this.subscriberIndex;
26805
+ const toPoll = Math.min(n, size);
26806
+ if (toPoll <= 0) return [];
26807
+ const builder = [];
26808
+ const pollUpToIndex = this.subscriberIndex + toPoll;
26809
+ while (this.subscriberIndex !== pollUpToIndex) {
26810
+ const index = this.subscriberIndex & this.self.mask;
26811
+ const elem = this.self.array[index];
26812
+ this.self.subscribers[index] -= 1;
26813
+ if (this.self.subscribers[index] === 0) {
26814
+ this.self.array[index] = AbsentValue;
26815
+ this.self.subscribersIndex += 1;
26816
+ }
26817
+ builder.push(elem);
26818
+ this.subscriberIndex += 1;
26819
+ }
26820
+ return builder;
26821
+ }
26822
+ unsubscribe() {
26823
+ if (!this.unsubscribed) {
26824
+ this.unsubscribed = true;
26825
+ this.self.subscriberCount -= 1;
26826
+ this.subscriberIndex = Math.max(this.subscriberIndex, this.self.subscribersIndex);
26827
+ while (this.subscriberIndex !== this.self.publisherIndex) {
26828
+ const index = this.subscriberIndex & this.self.mask;
26829
+ this.self.subscribers[index] -= 1;
26830
+ if (this.self.subscribers[index] === 0) {
26831
+ this.self.array[index] = AbsentValue;
26832
+ this.self.subscribersIndex += 1;
26833
+ }
26834
+ this.subscriberIndex += 1;
26835
+ }
26836
+ }
26837
+ }
26838
+ };
26839
+ var BoundedPubSubSingle = class {
26840
+ publisherIndex = 0;
26841
+ subscriberCount = 0;
26842
+ subscribers = 0;
26843
+ value = AbsentValue;
26844
+ replayIndex = 0;
26845
+ capacity = 1;
26846
+ replayBuffer;
26847
+ constructor(replayBuffer) {
26848
+ this.replayBuffer = replayBuffer;
26849
+ }
26850
+ replayWindow() {
26851
+ return this.replayBuffer ? new ReplayWindowImpl(this.replayBuffer) : emptyReplayWindow;
26852
+ }
26853
+ pipe() {
26854
+ return pipeArguments(this, arguments);
26855
+ }
26856
+ isEmpty() {
26857
+ return this.subscribers === 0;
26858
+ }
26859
+ isFull() {
26860
+ return !this.isEmpty();
26861
+ }
26862
+ size() {
26863
+ return this.isEmpty() ? 0 : 1;
26864
+ }
26865
+ publish(value) {
26866
+ if (this.isFull()) return false;
26867
+ const replayIndex = this.replayBuffer?.offer(value);
26868
+ if (this.subscriberCount !== 0) {
26869
+ this.value = value;
26870
+ if (replayIndex !== void 0) this.replayIndex = replayIndex;
26871
+ this.subscribers = this.subscriberCount;
26872
+ this.publisherIndex += 1;
26873
+ }
26874
+ return true;
26875
+ }
26876
+ publishAll(elements) {
26877
+ if (this.subscriberCount === 0) {
26878
+ if (this.replayBuffer) this.replayBuffer.offerAll(elements);
26879
+ return [];
26880
+ }
26881
+ const chunk = fromIterable$6(elements);
26882
+ if (chunk.length === 0) return chunk;
26883
+ if (this.publish(chunk[0])) return chunk.slice(1);
26884
+ else return chunk;
26885
+ }
26886
+ slide() {
26887
+ if (this.isFull()) {
26888
+ const value = this.value;
26889
+ this.subscribers = 0;
26890
+ this.value = AbsentValue;
26891
+ this.replayBuffer?.slide(value, this.replayIndex);
26892
+ }
26893
+ }
26894
+ subscribe() {
26895
+ this.subscriberCount += 1;
26896
+ return new BoundedPubSubSingleSubscription(this, this.publisherIndex, false);
26897
+ }
26898
+ };
26899
+ var BoundedPubSubSingleSubscription = class {
26900
+ self;
26901
+ subscriberIndex;
26902
+ unsubscribed;
26903
+ constructor(self, subscriberIndex, unsubscribed) {
26904
+ this.self = self;
26905
+ this.subscriberIndex = subscriberIndex;
26906
+ this.unsubscribed = unsubscribed;
26907
+ }
26908
+ isEmpty() {
26909
+ return this.unsubscribed || this.self.subscribers === 0 || this.subscriberIndex === this.self.publisherIndex;
26910
+ }
26911
+ size() {
26912
+ return this.isEmpty() ? 0 : 1;
26913
+ }
26914
+ poll() {
26915
+ if (this.isEmpty()) return Empty$2;
26916
+ const elem = this.self.value;
26917
+ this.self.subscribers -= 1;
26918
+ if (this.self.subscribers === 0) this.self.value = AbsentValue;
26919
+ this.subscriberIndex = this.self.publisherIndex;
26920
+ return elem;
26921
+ }
26922
+ pollUpTo(n) {
26923
+ if (normalize$2(n) < 1 || this.isEmpty()) return [];
26924
+ return [this.poll()];
26925
+ }
26926
+ unsubscribe() {
26927
+ if (!this.unsubscribed) {
26928
+ this.unsubscribed = true;
26929
+ this.self.subscriberCount -= 1;
26930
+ if (this.self.subscribers !== 0 && this.subscriberIndex !== this.self.publisherIndex) {
26931
+ this.self.subscribers -= 1;
26932
+ if (this.self.subscribers === 0) this.self.value = AbsentValue;
26933
+ }
26934
+ }
26935
+ }
26936
+ };
25991
26937
  var UnboundedPubSub = class {
25992
26938
  publisherHead = {
25993
26939
  value: AbsentValue,
@@ -26183,6 +27129,104 @@ var PubSubImpl = class {
26183
27129
  }
26184
27130
  };
26185
27131
  const makePubSubUnsafe = (pubsub, subscribers, scope, shutdownHook, shutdownFlag, strategy, ended) => new PubSubImpl(pubsub, subscribers, scope, shutdownHook, shutdownFlag, strategy, ended);
27132
+ const ensureCapacity = (capacity) => {
27133
+ if (capacity <= 0 || capacity !== Infinity && !Number.isInteger(capacity)) throw new Error(`Cannot construct PubSub with capacity of ${capacity}`);
27134
+ };
27135
+ /**
27136
+ * Represents the back-pressure strategy for bounded `PubSub` values.
27137
+ *
27138
+ * **When to use**
27139
+ *
27140
+ * Use to preserve every message for current subscribers when a bounded custom
27141
+ * `PubSub` should make publishers wait for capacity instead of dropping or
27142
+ * evicting messages.
27143
+ *
27144
+ * **Details**
27145
+ *
27146
+ * Publishers wait when the `PubSub` is at capacity, so all current subscribers
27147
+ * can receive every published message.
27148
+ *
27149
+ * **Gotchas**
27150
+ *
27151
+ * A slow subscriber can slow down publishers and other subscribers.
27152
+ *
27153
+ * @see {@link bounded} for creating bounded PubSubs with back pressure by default
27154
+ * @see {@link DroppingStrategy} for dropping new messages when capacity is full
27155
+ * @see {@link SlidingStrategy} for evicting old messages when capacity is full
27156
+ *
27157
+ * @stability stable
27158
+ * @category models
27159
+ * @since 4.0.0
27160
+ */
27161
+ var BackPressureStrategy = class {
27162
+ publishers = /*#__PURE__*/ make$78();
27163
+ get shutdown() {
27164
+ return withFiber((fiber) => forEach$1(takeAll$1(this.publishers), ([_, deferred, last]) => last ? interruptWith(deferred, fiber.id) : void_$2, {
27165
+ concurrency: "unbounded",
27166
+ discard: true
27167
+ }));
27168
+ }
27169
+ handleSurplus(pubsub, subscribers, elements, isShutdown, ended) {
27170
+ return callback$1((resume) => {
27171
+ if (isSome(ended.current)) return resume(succeed$5(false));
27172
+ const deferred = makeUnsafe$8();
27173
+ this.offerUnsafe(elements, deferred);
27174
+ this.onPubSubEmptySpaceUnsafe(pubsub, subscribers);
27175
+ this.completeSubscribersUnsafe(pubsub, subscribers);
27176
+ if (get$9(isShutdown)) {
27177
+ this.removeUnsafe(deferred);
27178
+ return resume(interrupt$1);
27179
+ }
27180
+ if (deferred.effect) return resume(deferred.effect);
27181
+ deferred.resumes = [resume];
27182
+ return sync(() => this.removeUnsafe(deferred));
27183
+ });
27184
+ }
27185
+ onPubSubEmptySpaceUnsafe(pubsub, subscribers) {
27186
+ let keepPolling = true;
27187
+ while (keepPolling && !pubsub.isFull()) {
27188
+ const publisher = take$2(this.publishers);
27189
+ if (publisher === Empty$2) keepPolling = false;
27190
+ else {
27191
+ const [value, deferred, last] = publisher;
27192
+ const published = pubsub.publish(value);
27193
+ if (!published) prepend(this.publishers, publisher);
27194
+ this.completeSubscribersUnsafe(pubsub, subscribers);
27195
+ if (published && last) doneUnsafe(deferred, succeed$8(true));
27196
+ }
27197
+ }
27198
+ }
27199
+ completePollersUnsafe(pubsub, subscribers, subscription, pollers) {
27200
+ return strategyCompletePollersUnsafe(this, pubsub, subscribers, subscription, pollers);
27201
+ }
27202
+ completeSubscribersUnsafe(pubsub, subscribers) {
27203
+ return strategyCompleteSubscribersUnsafe(this, pubsub, subscribers);
27204
+ }
27205
+ offerUnsafe(elements, deferred) {
27206
+ const iterator = elements[Symbol.iterator]();
27207
+ let next = iterator.next();
27208
+ if (!next.done) while (1) {
27209
+ const value = next.value;
27210
+ next = iterator.next();
27211
+ if (next.done) {
27212
+ append(this.publishers, [
27213
+ value,
27214
+ deferred,
27215
+ true
27216
+ ]);
27217
+ break;
27218
+ }
27219
+ append(this.publishers, [
27220
+ value,
27221
+ deferred,
27222
+ false
27223
+ ]);
27224
+ }
27225
+ }
27226
+ removeUnsafe(deferred) {
27227
+ filter(this.publishers, ([_, d]) => d !== deferred);
27228
+ }
27229
+ };
26186
27230
  /**
26187
27231
  * Represents the dropping strategy for bounded `PubSub` values.
26188
27232
  *
@@ -26247,6 +27291,89 @@ var DroppingStrategy = class {
26247
27291
  return strategyCompleteSubscribersUnsafe(this, pubsub, subscribers);
26248
27292
  }
26249
27293
  };
27294
+ /**
27295
+ * Represents the sliding strategy for bounded `PubSub` values.
27296
+ *
27297
+ * **When to use**
27298
+ *
27299
+ * Use to keep the most recent messages when the `PubSub` is at capacity.
27300
+ *
27301
+ * **Details**
27302
+ *
27303
+ * New messages are accepted by evicting older messages from the bounded
27304
+ * `PubSub`.
27305
+ *
27306
+ * **Gotchas**
27307
+ *
27308
+ * Slow subscribers may miss older messages that are evicted before they are
27309
+ * consumed.
27310
+ *
27311
+ * **Example** (Applying a sliding strategy)
27312
+ *
27313
+ * ```ts import.meta.vitest
27314
+ * import { Effect, PubSub } from "effect"
27315
+ *
27316
+ * const program = Effect.scoped(Effect.gen(function*() {
27317
+ * // Explicitly create a PubSub with a sliding strategy
27318
+ * const pubsub = yield* PubSub.make<string>({
27319
+ * atomicPubSub: () => PubSub.makeAtomicBounded(2),
27320
+ * strategy: () => new PubSub.SlidingStrategy()
27321
+ * })
27322
+ *
27323
+ * const subscription = yield* PubSub.subscribe(pubsub)
27324
+ *
27325
+ * // Publish messages that exceed capacity
27326
+ * yield* PubSub.publish(pubsub, "msg1") // stored
27327
+ * yield* PubSub.publish(pubsub, "msg2") // stored
27328
+ * yield* PubSub.publish(pubsub, "msg3") // "msg1" evicted, "msg3" stored
27329
+ * yield* PubSub.publish(pubsub, "msg4") // "msg2" evicted, "msg4" stored
27330
+ *
27331
+ * // Subscribers will see the most recent messages
27332
+ * return yield* PubSub.takeAll(subscription)
27333
+ * }))
27334
+ *
27335
+ * const actual = await Effect.runPromise(program)
27336
+ * actual // => ["msg3", "msg4"]
27337
+ * ```
27338
+ *
27339
+ * @stability stable
27340
+ * @category models
27341
+ * @since 4.0.0
27342
+ */
27343
+ var SlidingStrategy = class {
27344
+ get shutdown() {
27345
+ return void_$2;
27346
+ }
27347
+ handleSurplus(pubsub, subscribers, elements, _isShutdown, ended) {
27348
+ return sync(() => {
27349
+ if (isSome(ended.current)) return false;
27350
+ this.slidingPublishUnsafe(pubsub, elements);
27351
+ this.completeSubscribersUnsafe(pubsub, subscribers);
27352
+ return true;
27353
+ });
27354
+ }
27355
+ onPubSubEmptySpaceUnsafe(_pubsub, _subscribers) {}
27356
+ completePollersUnsafe(pubsub, subscribers, subscription, pollers) {
27357
+ return strategyCompletePollersUnsafe(this, pubsub, subscribers, subscription, pollers);
27358
+ }
27359
+ completeSubscribersUnsafe(pubsub, subscribers) {
27360
+ return strategyCompleteSubscribersUnsafe(this, pubsub, subscribers);
27361
+ }
27362
+ slidingPublishUnsafe(pubsub, elements) {
27363
+ const it = elements[Symbol.iterator]();
27364
+ let next = it.next();
27365
+ if (!next.done && pubsub.capacity > 0) {
27366
+ let a = next.value;
27367
+ let loop = true;
27368
+ while (loop) {
27369
+ pubsub.slide();
27370
+ const pub = pubsub.publish(a);
27371
+ if (pub && (next = it.next()) && !next.done) a = next.value;
27372
+ else if (pub) loop = false;
27373
+ }
27374
+ }
27375
+ }
27376
+ };
26250
27377
  const strategyCompletePollersUnsafe = (strategy, pubsub, subscribers, subscription, pollers) => {
26251
27378
  let keepPolling = true;
26252
27379
  while (keepPolling && !subscription.isEmpty()) {
@@ -27760,6 +28887,21 @@ const withPermit = (self, effect) => {
27760
28887
  if (!effect) return self.withPermit;
27761
28888
  return self.withPermit(effect);
27762
28889
  };
28890
+ // ../../node_modules/.pnpm/effect@4.1.7/node_modules/effect/dist/Take.js
28891
+ /**
28892
+ * Converts a `Take` into a `Pull`, succeeding with value batches, failing with
28893
+ * failure exits, and translating successful exits into pull completion.
28894
+ *
28895
+ * **When to use**
28896
+ *
28897
+ * Use to interpret a stored or transferred `Take` as a `Pull` step while
28898
+ * preserving emitted batches, ordinary failures, and completion values.
28899
+ *
28900
+ * @stability stable
28901
+ * @category converting
28902
+ * @since 4.0.0
28903
+ */
28904
+ const toPull = (take) => isExit(take) ? isSuccess$1(take) ? done(take.value) : take : succeed$5(take);
27763
28905
  // ../../node_modules/.pnpm/effect@4.1.7/node_modules/effect/dist/Channel.js
27764
28906
  /**
27765
28907
  * Provides low-level building blocks for streaming data through Effect.
@@ -28152,6 +29294,20 @@ const fromEffect$1 = (effect) => fromPull$1(sync(() => {
28152
29294
  */
28153
29295
  const fromEffectDrain = (effect) => fromPull$1(flatMap$3(effect, () => done()));
28154
29296
  /**
29297
+ * Creates a channel from an effect that produces a `Take`.
29298
+ *
29299
+ * **Details**
29300
+ *
29301
+ * A successful `Take` emits a non-empty array of output elements. A failed
29302
+ * `Take` fails the channel. A done `Take` completes the channel with its done
29303
+ * value.
29304
+ *
29305
+ * @stability stable
29306
+ * @category constructors
29307
+ * @since 4.0.0
29308
+ */
29309
+ const fromEffectTake = (effect) => fromPull$1(succeed$5(flatMap$3(effect, toPull)));
29310
+ /**
28155
29311
  * Creates a channel from a queue that emits arrays of elements.
28156
29312
  *
28157
29313
  * **Example** (Creating batched channels from queues)
@@ -28175,6 +29331,19 @@ const fromEffectDrain = (effect) => fromPull$1(flatMap$3(effect, () => done()));
28175
29331
  */
28176
29332
  const fromQueueArray = (queue) => fromPull$1(succeed$5(takeAll(queue)));
28177
29333
  /**
29334
+ * Subscribes to a `PubSub` of `Take` values and exposes them as a channel.
29335
+ *
29336
+ * **Details**
29337
+ *
29338
+ * Output `Take` values are emitted as non-empty arrays. Failed `Take` values
29339
+ * fail the channel. Done `Take` values complete the channel.
29340
+ *
29341
+ * @stability stable
29342
+ * @category constructors
29343
+ * @since 4.0.0
29344
+ */
29345
+ const fromPubSubTake$1 = (pubsub) => unwrap$6(map$7(subscribe(pubsub), (sub) => fromEffectTake(take$1(sub))));
29346
+ /**
28178
29347
  * Creates a channel from a lazily supplied Web `ReadableStream`.
28179
29348
  *
28180
29349
  * **Details**
@@ -29440,6 +30609,26 @@ const runFold = /*#__PURE__*/ dual(3, (self, initial, f) => suspend$3(() => {
29440
30609
  * @since 4.0.0
29441
30610
  */
29442
30611
  const toPullScoped = (self, scope) => toTransform(self)(done(), scope);
30612
+ const makePubSub = (options) => acquireRelease(options.capacity === "unbounded" ? unbounded(options) : options.strategy === "dropping" ? dropping$1(options) : options.strategy === "sliding" ? sliding$1(options) : bounded$1(options), shutdown$1);
30613
+ /**
30614
+ * Converts a channel to a scoped `PubSub` of `Take` values.
30615
+ *
30616
+ * **Details**
30617
+ *
30618
+ * Emitted non-empty arrays are published as output `Take` values. When the
30619
+ * channel ends, the `PubSub` is ended with its final `Exit`, so every
30620
+ * subscriber, including one that subscribes later, observes completion or
30621
+ * failure once it has consumed its buffered values.
30622
+ *
30623
+ * @stability stable
30624
+ * @category destructors
30625
+ * @since 4.0.0
30626
+ */
30627
+ const toPubSubTake$1 = /*#__PURE__*/ dual(2, /*#__PURE__*/ fnUntraced(function* (self, options) {
30628
+ const pubsub = yield* makePubSub(options);
30629
+ yield* runForEach$1(self, (value) => publish(pubsub, value)).pipe(onExit$1((exit) => end$2(pubsub, exit)), forkScoped);
30630
+ return pubsub;
30631
+ }));
29443
30632
  // ../../node_modules/.pnpm/effect@4.1.7/node_modules/effect/dist/internal/stream.js
29444
30633
  const TypeId$56 = "~effect/Stream";
29445
30634
  const streamVariance = {
@@ -29737,7 +30926,7 @@ const makeUnsafe$3 = (options) => ({
29737
30926
  */
29738
30927
  const make$74 = (options) => withFiber((fiber) => {
29739
30928
  const context = fiber.context;
29740
- const scope = get$12(context, Scope);
30929
+ const scope = get$13(context, Scope);
29741
30930
  const self = makeUnsafe$3({
29742
30931
  lookup: options.lookup,
29743
30932
  context,
@@ -29804,7 +30993,7 @@ const get$8 = /*#__PURE__*/ dual(2, (self, key) => uninterruptibleMask((restore)
29804
30993
  if (self.state._tag === "Closed") return interrupt$1;
29805
30994
  const state = self.state;
29806
30995
  const parent = getCurrent();
29807
- const o = get$9(state.map, key);
30996
+ const o = get$10(state.map, key);
29808
30997
  let entry;
29809
30998
  if (o._tag === "Some") {
29810
30999
  entry = o.value;
@@ -29838,7 +31027,7 @@ const get$8 = /*#__PURE__*/ dual(2, (self, key) => uninterruptibleMask((restore)
29838
31027
  }));
29839
31028
  const removeInterrupted = (self, key, entry, context) => {
29840
31029
  if (self.state._tag === "Closed") return;
29841
- const o = get$9(self.state.map, key);
31030
+ const o = get$10(self.state.map, key);
29842
31031
  if (o._tag === "None" || o.value !== entry) return;
29843
31032
  remove$4(self.state.map, key);
29844
31033
  if (entry.refCount > 0) return;
@@ -29855,13 +31044,13 @@ const release$1 = (self, key, entry) => suspend$3(() => {
29855
31044
  entry.refCount--;
29856
31045
  if (entry.refCount > 0) return void_$2;
29857
31046
  else if (self.state._tag === "Closed") return closeEntry(entry);
29858
- const o = get$9(self.state.map, key);
31047
+ const o = get$10(self.state.map, key);
29859
31048
  if (o._tag === "None" || o.value !== entry) return closeEntry(entry);
29860
31049
  else if (isZero$1(entry.idleTimeToLive)) {
29861
31050
  remove$4(self.state.map, key);
29862
31051
  return closeEntry(entry);
29863
31052
  } else if (!isFinite$1(entry.idleTimeToLive)) return void_$2;
29864
- const clock = get$12(self.context, Clock);
31053
+ const clock = get$13(self.context, Clock);
29865
31054
  resetExpiresAt(entry, clock);
29866
31055
  if (entry.fiber) return void_$2;
29867
31056
  entry.fiber = uninterruptibleMask(function loop(restore) {
@@ -29869,7 +31058,7 @@ const release$1 = (self, key, entry) => suspend$3(() => {
29869
31058
  const remaining = entry.expiresAt - now;
29870
31059
  if (remaining <= 0) {
29871
31060
  if (self.state._tag === "Closed" || entry.refCount > 0) return void_$2;
29872
- const o = get$9(self.state.map, key);
31061
+ const o = get$10(self.state.map, key);
29873
31062
  if (o._tag === "None" || o.value !== entry) return void_$2;
29874
31063
  remove$4(self.state.map, key);
29875
31064
  return ignoreCause(close(entry.scope, void_$3), {
@@ -29911,7 +31100,7 @@ var RcRefImpl = class {
29911
31100
  /** @internal */
29912
31101
  const make$73 = (options) => withFiber((fiber) => {
29913
31102
  const context = fiber.context;
29914
- const scope = get$12(context, Scope);
31103
+ const scope = get$13(context, Scope);
29915
31104
  const ref = new RcRefImpl(options.acquire, context, scope, options.idleTimeToLive !== void 0 ? fromInputUnsafe$1(options.idleTimeToLive) : void 0);
29916
31105
  return as(addFinalizerExit(scope, () => {
29917
31106
  const state = ref.state;
@@ -30544,6 +31733,39 @@ const fromArray = (array) => isReadonlyArrayNonEmpty(array) ? fromChannel(succee
30544
31733
  */
30545
31734
  const fromQueue = (queue) => fromChannel(fromQueueArray(queue));
30546
31735
  /**
31736
+ * Creates a stream from a PubSub of `Take` values.
31737
+ *
31738
+ * **Details**
31739
+ *
31740
+ * `Take` values include end and failure signals.
31741
+ *
31742
+ * **Example** (Creating a stream from PubSub takes)
31743
+ *
31744
+ * ```ts import.meta.vitest
31745
+ * import { Effect, Exit, PubSub, Stream, Take } from "effect"
31746
+ *
31747
+ * const program = Effect.gen(function*() {
31748
+ * const pubsub = yield* PubSub.unbounded<Take.Take<number, string>>({
31749
+ * replay: 3
31750
+ * })
31751
+ *
31752
+ * yield* PubSub.publish(pubsub, [1])
31753
+ * yield* PubSub.publish(pubsub, [2])
31754
+ * yield* PubSub.publish(pubsub, Exit.succeed<void>(undefined))
31755
+ *
31756
+ * const values = yield* Stream.fromPubSubTake(pubsub).pipe(Stream.runCollect)
31757
+ * values // => [1, 2]
31758
+ * })
31759
+ *
31760
+ * await Effect.runPromise(program)
31761
+ * ```
31762
+ *
31763
+ * @stability stable
31764
+ * @category constructors
31765
+ * @since 4.0.0
31766
+ */
31767
+ const fromPubSubTake = (pubsub) => fromChannel(fromPubSubTake$1(pubsub));
31768
+ /**
30547
31769
  * Creates a stream from a lazily supplied Web `ReadableStream`.
30548
31770
  *
30549
31771
  * **Details**
@@ -30587,6 +31809,41 @@ const fromQueue = (queue) => fromChannel(fromQueueArray(queue));
30587
31809
  */
30588
31810
  const fromReadableStream = (options) => fromChannel(fromReadableStream$1(options));
30589
31811
  /**
31812
+ * Creates a stream by repeatedly applying an effectful step function to a
31813
+ * state.
31814
+ *
31815
+ * **Details**
31816
+ *
31817
+ * Each `readonly [value, nextState]` result emits `value` and continues with
31818
+ * `nextState`; returning `undefined` ends the stream.
31819
+ *
31820
+ * **Example** (Unfolding stream state)
31821
+ *
31822
+ * ```ts import.meta.vitest
31823
+ * import { Effect, Stream } from "effect"
31824
+ *
31825
+ * const program = Effect.gen(function*() {
31826
+ * const stream = Stream.unfold(1, (n) => Effect.succeed([n, n + 1] as const))
31827
+ * const values = yield* Stream.runCollect(stream.pipe(Stream.take(5)))
31828
+ * values // => [ 1, 2, 3, 4, 5 ]
31829
+ * })
31830
+ *
31831
+ * await Effect.runPromise(program)
31832
+ * ```
31833
+ *
31834
+ * @stability stable
31835
+ * @category constructors
31836
+ * @since 2.0.0
31837
+ */
31838
+ const unfold = (s, f) => fromPull(sync(() => {
31839
+ let state = s;
31840
+ return flatMap$3(suspend$3(() => f(state)), (next) => {
31841
+ if (next === void 0) return done();
31842
+ state = next[1];
31843
+ return succeed$5(of(next[0]));
31844
+ });
31845
+ }));
31846
+ /**
30590
31847
  * Creates a stream produced from an `Effect`.
30591
31848
  *
30592
31849
  * **Details**
@@ -31248,6 +32505,94 @@ const transduce = /*#__PURE__*/ dual(2, (self, sink) => transformPull(self, (ups
31248
32505
  return suspend$3(() => done$8 ? done$8 : pull);
31249
32506
  })));
31250
32507
  /**
32508
+ * Creates a PubSub-backed stream that multicasts the source to all subscribers.
32509
+ *
32510
+ * **Details**
32511
+ *
32512
+ * The returned stream is scoped and uses the provided PubSub capacity and replay settings.
32513
+ *
32514
+ * **Example** (Broadcasting a stream)
32515
+ *
32516
+ * ```ts import.meta.vitest
32517
+ * import { Effect, Stream } from "effect"
32518
+ *
32519
+ * const program = Effect.scoped(
32520
+ * Effect.gen(function* () {
32521
+ * const broadcasted = yield* Stream.broadcast(Stream.fromArray([1, 2, 3]), {
32522
+ * capacity: 8,
32523
+ * replay: 3
32524
+ * })
32525
+ *
32526
+ * const [left, right] = yield* Effect.all([
32527
+ * Stream.runCollect(broadcasted),
32528
+ * Stream.runCollect(broadcasted)
32529
+ * ], { concurrency: "unbounded" })
32530
+ *
32531
+ * const result = [left, right] // => [[1, 2, 3], [1, 2, 3]]
32532
+ * })
32533
+ * )
32534
+ *
32535
+ * await Effect.runPromise(program)
32536
+ * ```
32537
+ *
32538
+ * @stability stable
32539
+ * @category broadcasting
32540
+ * @since 2.0.0
32541
+ */
32542
+ const broadcast = /*#__PURE__*/ dual(2, (self, options) => map$7(toPubSubTake(self, options), fromPubSubTake));
32543
+ /**
32544
+ * Returns a new Stream that multicasts the original stream, subscribing when the first consumer starts.
32545
+ *
32546
+ * **Details**
32547
+ *
32548
+ * The upstream continues running while there is at least one consumer and is finalized after the last one exits.
32549
+ * If `idleTimeToLive` is set, the upstream is kept alive for that duration so a later subscriber can continue from
32550
+ * the next element instead of restarting.
32551
+ *
32552
+ * **Example** (Sharing a stream)
32553
+ *
32554
+ * ```ts import.meta.vitest
32555
+ * import { Deferred, Effect, Ref, Stream } from "effect"
32556
+ *
32557
+ * const result = await Effect.runPromise(
32558
+ * Effect.scoped(
32559
+ * Effect.gen(function*() {
32560
+ * const firstReady = yield* Deferred.make<void>()
32561
+ * const secondReady = yield* Deferred.make<void>()
32562
+ * const acquisitions = yield* Ref.make(0)
32563
+ * const source = Stream.fromEffect(Ref.update(acquisitions, (n) => n + 1)).pipe(
32564
+ * Stream.drain,
32565
+ * Stream.concat(Stream.make(0)),
32566
+ * Stream.concat(
32567
+ * Stream.fromEffect(Effect.all([Deferred.await(firstReady), Deferred.await(secondReady)])).pipe(Stream.drain)
32568
+ * ),
32569
+ * Stream.concat(Stream.make(1, 2, 3))
32570
+ * )
32571
+ * const shared = yield* Stream.share(source, { capacity: 16, replay: 1 })
32572
+ * const consume = (ready: Deferred.Deferred<void>) =>
32573
+ * shared.pipe(
32574
+ * Stream.tap((value) => value === 0 ? Deferred.succeed(ready, void 0) : Effect.void),
32575
+ * Stream.filter((value) => value !== 0),
32576
+ * Stream.runCollect
32577
+ * )
32578
+ *
32579
+ * const values = yield* Effect.all([consume(firstReady), consume(secondReady)], { concurrency: "unbounded" })
32580
+ * return { values, acquisitions: yield* Ref.get(acquisitions) }
32581
+ * })
32582
+ * )
32583
+ * )
32584
+ * result // => { values: [[1, 2, 3], [1, 2, 3]], acquisitions: 1 }
32585
+ * ```
32586
+ *
32587
+ * @stability stable
32588
+ * @category broadcasting
32589
+ * @since 3.8.0
32590
+ */
32591
+ const share = /*#__PURE__*/ dual(2, (self, options) => map$7(make$72({
32592
+ acquire: broadcast(self, options),
32593
+ idleTimeToLive: options.idleTimeToLive
32594
+ }), (ref) => unwrap$4(get$6(ref))));
32595
+ /**
31251
32596
  * Pipes values through the provided channel while preserving this stream's
31252
32597
  * failures alongside any channel failures.
31253
32598
  *
@@ -31878,6 +33223,39 @@ const toReadableStream = /*#__PURE__*/ dual((args) => isStream(args[0]), (self,
31878
33223
  * @since 2.0.0
31879
33224
  */
31880
33225
  const toReadableStreamEffect = /*#__PURE__*/ dual((args) => isStream(args[0]), (self, options) => map$7(context(), (context) => toReadableStreamWith(self, context, options)));
33226
+ /**
33227
+ * Converts a stream to a PubSub of `Take` values for concurrent consumption.
33228
+ *
33229
+ * **Details**
33230
+ *
33231
+ * Chunks are published as `Take` values. When the stream ends, the PubSub is
33232
+ * ended with the stream's `Exit`, so every subscriber, including one that
33233
+ * subscribes later, observes completion or failure after its buffered chunks.
33234
+ *
33235
+ * **Example** (Converting to a PubSub of takes)
33236
+ *
33237
+ * ```ts import.meta.vitest
33238
+ * import { Effect, PubSub, Stream } from "effect"
33239
+ *
33240
+ * const program = Effect.gen(function* () {
33241
+ * const pubsub = yield* Stream.fromArray([1, 2, 3]).pipe(
33242
+ * Stream.toPubSubTake({ capacity: 8 })
33243
+ * )
33244
+ * const subscription = yield* PubSub.subscribe(pubsub)
33245
+ * const take = yield* PubSub.take(subscription)
33246
+ *
33247
+ * if (Array.isArray(take)) {
33248
+ * take // => [ 1, 2, 3 ]
33249
+ * }
33250
+ * })
33251
+ * await Effect.runPromise(Effect.scoped(program))
33252
+ * ```
33253
+ *
33254
+ * @stability stable
33255
+ * @category destructors
33256
+ * @since 4.0.0
33257
+ */
33258
+ const toPubSubTake = /*#__PURE__*/ dual(2, (self, options) => toPubSubTake$1(self.channel, options));
31881
33259
  // ../../node_modules/.pnpm/effect@4.1.7/node_modules/effect/dist/FileSystem.js
31882
33260
  /**
31883
33261
  * Defines the portable file system service for Effect programs.
@@ -34383,7 +35761,7 @@ const BigDecimalProto = {
34383
35761
  [TypeId$48]: TypeId$48,
34384
35762
  [symbol$3]() {
34385
35763
  const normalized = normalize(this);
34386
- return combine$3(string$2(String(normalized.value)), number$2(normalized.scale));
35764
+ return combine$4(string$2(String(normalized.value)), number$2(normalized.scale));
34387
35765
  },
34388
35766
  [symbol$2](that) {
34389
35767
  return isBigDecimal(that) && compare$1(this, that) === 0;
@@ -34568,7 +35946,7 @@ const compare$1 = (self, that) => {
34568
35946
  * @category instances
34569
35947
  * @since 2.0.0
34570
35948
  */
34571
- const Order$1 = /*#__PURE__*/ make$90(compare$1);
35949
+ const Order$1 = /*#__PURE__*/ make$91(compare$1);
34572
35950
  /**
34573
35951
  * Determines the sign of a given `BigDecimal`.
34574
35952
  *
@@ -37996,7 +39374,7 @@ const value$2 = value$3;
37996
39374
  * @category instances
37997
39375
  * @since 4.0.0
37998
39376
  */
37999
- const makeEquivalence = (isEquivalent) => make$91((x, y) => isEquivalent(value$2(x), value$2(y)));
39377
+ const makeEquivalence = (isEquivalent) => make$92((x, y) => isEquivalent(value$2(x), value$2(y)));
38000
39378
  // ../../node_modules/.pnpm/effect@4.1.7/node_modules/effect/dist/process/CommandLine.js
38001
39379
  /**
38002
39380
  * Builds command lines, the single strings that a shell or a Windows program
@@ -40127,7 +41505,7 @@ const TypeId$42 = /*#__PURE__*/ Symbol.for("~effect/http/Headers");
40127
41505
  const Proto$15 = /*#__PURE__*/ Object.defineProperties(/*#__PURE__*/ Object.create(null), {
40128
41506
  [TypeId$42]: { value: TypeId$42 },
40129
41507
  [symbolRedactable]: { value(context) {
40130
- return redact$1(this, get$12(context, CurrentRedactedNames$1));
41508
+ return redact$1(this, get$13(context, CurrentRedactedNames$1));
40131
41509
  } },
40132
41510
  toJSON: { value() {
40133
41511
  return redact$2(this);
@@ -43616,7 +44994,7 @@ function mergeLeaves(edit, shift, hash1, node1, hash2, node2) {
43616
44994
  return new IndexedNode(edit, bit1 | bit2, bit1 >>> 0 < bit2 >>> 0 ? [node1, node2] : [node2, node1]);
43617
44995
  }
43618
44996
  const hashMapSeed = /*#__PURE__*/ string$2("HashMap");
43619
- const entryHash = (key, value) => combine$3(hash(key), hash(value));
44997
+ const entryHash = (key, value) => combine$4(hash(key), hash(value));
43620
44998
  const childrenHash = (children) => {
43621
44999
  let h = 0;
43622
45000
  for (let i = 0; i < children.length; i++) {
@@ -44277,7 +45655,7 @@ const HashSetTypeId = "~effect/HashSet";
44277
45655
  const hashSetSeed = /*#__PURE__*/ string$2(HashSetTypeId);
44278
45656
  const HashSetProto = {
44279
45657
  [symbol$3]() {
44280
- return optimize(combine$3(hashSetSeed, hash(keyMap(this))));
45658
+ return optimize(combine$4(hashSetSeed, hash(keyMap(this))));
44281
45659
  },
44282
45660
  [symbol$2](that) {
44283
45661
  return isHashSet$1(that) && size(this) === size(that) && every(this, (value) => has$1(that, value));
@@ -44470,7 +45848,7 @@ const Proto$14 = {
44470
45848
  [symbolRedactable](context) {
44471
45849
  return {
44472
45850
  _id: "UrlParams",
44473
- params: Object.fromEntries(redact(this, get$12(context, CurrentRedactedNames)))
45851
+ params: Object.fromEntries(redact(this, get$13(context, CurrentRedactedNames)))
44474
45852
  };
44475
45853
  },
44476
45854
  toJSON() {
@@ -44546,7 +45924,7 @@ const coerce = (value) => isRedacted(value) ? value : String(value);
44546
45924
  * @category instances
44547
45925
  * @since 4.0.0
44548
45926
  */
44549
- const Equivalence = /*#__PURE__*/ make$91((a, b) => arrayEquivalence(a.params, b.params));
45927
+ const Equivalence = /*#__PURE__*/ make$92((a, b) => arrayEquivalence(a.params, b.params));
44550
45928
  const arrayEquivalence = /*#__PURE__*/ makeEquivalence$2(/*#__PURE__*/ makeEquivalence$4([/*#__PURE__*/ strictEqual(), /*#__PURE__*/ asEquivalence()]));
44551
45929
  /**
44552
45930
  * An empty `UrlParams` value.
@@ -44683,7 +46061,7 @@ const decodeQueryKey = (key) => {
44683
46061
  return key;
44684
46062
  }
44685
46063
  };
44686
- const currentRedactedNames = () => get$12(globalThis["~effect/Fiber/currentFiber"]?.context ?? empty$14(), CurrentRedactedNames);
46064
+ const currentRedactedNames = () => get$13(globalThis["~effect/Fiber/currentFiber"]?.context ?? empty$14(), CurrentRedactedNames);
44687
46065
  /**
44688
46066
  * Query parameter names or patterns to redact in inspection, spans and errors.
44689
46067
  *
@@ -46588,7 +47966,7 @@ const recur = /*#__PURE__*/ memoize((ast) => {
46588
47966
  const rest = ast.rest.map(recur);
46589
47967
  const [head, ...tail] = rest;
46590
47968
  const tailLength = tail.length;
46591
- return make$91((a, b) => {
47969
+ return make$92((a, b) => {
46592
47970
  if (!Array.isArray(a) || !Array.isArray(b)) return false;
46593
47971
  const len = a.length;
46594
47972
  if (len !== b.length) return false;
@@ -46605,7 +47983,7 @@ const recur = /*#__PURE__*/ memoize((ast) => {
46605
47983
  if (ast.propertySignatures.length === 0 && ast.indexSignatures.length === 0) return equals$1;
46606
47984
  const propertySignatures = ast.propertySignatures.map((ps) => recur(ps.type));
46607
47985
  const indexSignatures = ast.indexSignatures.map((is) => recur(is.type));
46608
- return make$91((a, b) => {
47986
+ return make$92((a, b) => {
46609
47987
  if (!isObject$2(a) || !isObject$2(b)) return false;
46610
47988
  for (let i = 0; i < propertySignatures.length; i++) {
46611
47989
  const ps = ast.propertySignatures[i];
@@ -46634,7 +48012,7 @@ const recur = /*#__PURE__*/ memoize((ast) => {
46634
48012
  const types = ast.types;
46635
48013
  const index = getCandidateIndex(types);
46636
48014
  const compiled = types.map((candidate) => [_is(candidate), recur(candidate)]);
46637
- return make$91((a, b) => {
48015
+ return make$92((a, b) => {
46638
48016
  const candidates = index(a, false);
46639
48017
  for (let i = 0; i < candidates.length; i++) {
46640
48018
  const [is, equivalence] = compiled[candidates[i]];
@@ -46645,7 +48023,7 @@ const recur = /*#__PURE__*/ memoize((ast) => {
46645
48023
  }
46646
48024
  case "Suspend": {
46647
48025
  let equivalence;
46648
- return make$91((a, b) => (equivalence ??= toEquivalence$1(ast.thunk()))(a, b));
48026
+ return make$92((a, b) => (equivalence ??= toEquivalence$1(ast.thunk()))(a, b));
46649
48027
  }
46650
48028
  }
46651
48029
  });
@@ -46900,7 +48278,7 @@ const IpInterfaceProto = {
46900
48278
  return isIpInterface(that) && this.prefixLength === that.prefixLength && equals$1(this.address, that.address);
46901
48279
  },
46902
48280
  [symbol$3]() {
46903
- return combine$3(hash(this.address), number$2(this.prefixLength));
48281
+ return combine$4(hash(this.address), number$2(this.prefixLength));
46904
48282
  },
46905
48283
  toString() {
46906
48284
  return format$2(this);
@@ -46988,7 +48366,7 @@ const IpNetworkProto = {
46988
48366
  return isIpNetwork(that) && this.prefixLength === that.prefixLength && equals$1(this.address, that.address);
46989
48367
  },
46990
48368
  [symbol$3]() {
46991
- return combine$3(hash(this.address), number$2(this.prefixLength));
48369
+ return combine$4(hash(this.address), number$2(this.prefixLength));
46992
48370
  },
46993
48371
  toString() {
46994
48372
  return format$1(this);
@@ -50842,7 +52220,7 @@ const stream$2 = (body, contentType, contentLength) => new Stream$1(body, conten
50842
52220
  /** @internal */
50843
52221
  const CurrentClientPath = /*#__PURE__*/ Reference("effect/http/internal/clientPath/CurrentClientPath", { defaultValue: () => void 0 });
50844
52222
  /** @internal */
50845
- const currentClientPath = () => get$12(globalThis["~effect/Fiber/currentFiber"]?.context ?? empty$14(), CurrentClientPath);
52223
+ const currentClientPath = () => get$13(globalThis["~effect/Fiber/currentFiber"]?.context ?? empty$14(), CurrentClientPath);
50846
52224
  /**
50847
52225
  * Replaces the path of a URL with its redacted form. A pathname that does not
50848
52226
  * match the expected sent pathname is replaced by `/REDACTED`.
@@ -52221,7 +53599,7 @@ const retryTransient = /*#__PURE__*/ dual(2, (self, options) => {
52221
53599
  const parseRetryAfter = (nowMillis, value) => {
52222
53600
  if (value === void 0) return;
52223
53601
  const retryAfter = parseRetryAfter$1(value);
52224
- return isSuccess$2(retryAfter) ? max(retryAfterDelay$1(retryAfter.success, nowMillis), millis(1)) : void 0;
53602
+ return isSuccess$2(retryAfter) ? max$1(retryAfterDelay$1(retryAfter.success, nowMillis), millis(1)) : void 0;
52225
53603
  };
52226
53604
  /**
52227
53605
  * Performs an additional effect after a successful request.
@@ -52457,7 +53835,7 @@ const retryAfterOf = (input, nowMillis) => {
52457
53835
  const withRetryAfter = (schedule) => fromStep(map$7(toStep(schedule), (step) => (now, input) => {
52458
53836
  const retryAfter = retryAfterOf(input, now);
52459
53837
  if (retryAfter === void 0) return step(now, input);
52460
- return map$7(step(now, input), ([output, delay]) => [output, max(delay, retryAfter)]);
53838
+ return map$7(step(now, input), ([output, delay]) => [output, max$1(delay, retryAfter)]);
52461
53839
  }));
52462
53840
  /**
52463
53841
  * Returns `true` for a response whose status `retryTransient` retries by
@@ -55959,7 +57337,7 @@ const isMultipartError = (u) => hasProperty(u, MultipartErrorTypeId);
55959
57337
  * @since 4.0.0
55960
57338
  */
55961
57339
  const makeConfig = (headers) => withFiber((fiber) => {
55962
- const mimeTypes = get$12(fiber.context, FieldMimeTypes);
57340
+ const mimeTypes = get$13(fiber.context, FieldMimeTypes);
55963
57341
  return succeed$5({
55964
57342
  headers,
55965
57343
  maxParts: fiber.getRef(MaxParts),
@@ -57352,7 +58730,7 @@ var MiddlewareImpl = class MiddlewareImpl {
57352
58730
  const stack = [getOrUndefinedUnsafe(context$4, fnContextKey)];
57353
58731
  if (this.dependencies) {
57354
58732
  const memoMap = yield* CurrentMemoMap;
57355
- const scope = get$12(context$4, Scope);
58733
+ const scope = get$13(context$4, Scope);
57356
58734
  const depsContext = yield* buildWithMemoMap(this.dependencies, memoMap, scope);
57357
58735
  stack.push(...getMiddleware$1(depsContext));
57358
58736
  }
@@ -57407,9 +58785,9 @@ const serve = (appLayer, options) => {
57407
58785
  const layerWithRouter = provideMerge(appLayer, options?.routerConfig ? provide$2(layer$21, succeed$6(RouterConfig)(options.routerConfig)) : layer$21);
57408
58786
  return contextWith((context) => {
57409
58787
  const memoMap = CurrentMemoMap.forkOrCreate(context);
57410
- return buildWithMemoMap(layerWithRouter, memoMap, get$12(context, Scope));
58788
+ return buildWithMemoMap(layerWithRouter, memoMap, get$13(context, Scope));
57411
58789
  }).pipe(map$7((context) => {
57412
- const handler = get$12(context, HttpRouter).asHttpEffect();
58790
+ const handler = get$13(context, HttpRouter).asHttpEffect();
57413
58791
  return provideMerge(middleware ? serve$1(handler, middleware) : serve$1(handler), succeedContext(context));
57414
58792
  }), unwrap$7, options?.disableListenLog ? identity : withLogAddress);
57415
58793
  };
@@ -62311,7 +63689,7 @@ const makeNoSerialization$1 = /*#__PURE__*/ fnUntraced(function* (group, options
62311
63689
  const disableTracing = options?.disableTracing ?? false;
62312
63690
  const generateRequestId = options?.generateRequestId ?? (() => requestIdCounter++);
62313
63691
  const services = yield* context();
62314
- const scope = get$12(services, Scope);
63692
+ const scope = get$13(services, Scope);
62315
63693
  const entries = /* @__PURE__ */ new Map();
62316
63694
  let isShutdown = false;
62317
63695
  yield* addFinalizer$1(scope, withFiber((parent) => {
@@ -62327,7 +63705,7 @@ const makeNoSerialization$1 = /*#__PURE__*/ fnUntraced(function* (group, options
62327
63705
  const traceFields = (fiber, clientSpan) => {
62328
63706
  if (disableTracing || !fiber.cache.tracerEnabled || fiber.getRef(DisablePropagation)) return void 0;
62329
63707
  const span = clientSpan ?? fiber.cache.span;
62330
- if (!span || get$12(span.annotations, DisablePropagation)) return void 0;
63708
+ if (!span || get$13(span.annotations, DisablePropagation)) return void 0;
62331
63709
  return {
62332
63710
  traceId: span.traceId,
62333
63711
  spanId: span.spanId,
@@ -62337,7 +63715,7 @@ const makeNoSerialization$1 = /*#__PURE__*/ fnUntraced(function* (group, options
62337
63715
  const onRequest = (rpc) => {
62338
63716
  const isStream = isStreamSchema(rpc.successSchema);
62339
63717
  const middleware = getRpcClientMiddleware(rpc);
62340
- const tracing = get$12(rpc.annotations, TracingEnabled);
63718
+ const tracing = get$13(rpc.annotations, TracingEnabled);
62341
63719
  const createSpan = !disableTracing && (tracing === "both" || tracing === "client");
62342
63720
  return (payload, opts) => {
62343
63721
  const headers = opts?.headers ? fromInput$1(opts.headers) : empty$6;
@@ -62667,7 +64045,7 @@ const makeRpcSchemas = (codecFor) => {
62667
64045
  let entry = cache.get(rpc);
62668
64046
  if (entry !== void 0) return entry;
62669
64047
  const streamSchemas = getStreamSchemas(rpc.successSchema);
62670
- const parseOptions = get$12(rpc.annotations, ParseOptions);
64048
+ const parseOptions = get$13(rpc.annotations, ParseOptions);
62671
64049
  const exitSchema$2 = exitSchema(rpc);
62672
64050
  let decodeDiscardExit;
62673
64051
  entry = {
@@ -63379,7 +64757,7 @@ const makeNoSerialization = /*#__PURE__*/ fnUntraced(function* (group, options)
63379
64757
  const concurrency = options.concurrency ?? "unbounded";
63380
64758
  const disableFatalDefects = options.disableFatalDefects ?? false;
63381
64759
  const services = yield* context();
63382
- const scope = get$12(services, Scope);
64760
+ const scope = get$13(services, Scope);
63383
64761
  const trackFiber = runIn(forkUnsafe(scope, "parallel"));
63384
64762
  const concurrencySemaphore = concurrency === "unbounded" ? void 0 : yield* make$75(concurrency);
63385
64763
  const clients = /* @__PURE__ */ new Map();
@@ -63526,7 +64904,7 @@ const makeNoSerialization = /*#__PURE__*/ fnUntraced(function* (group, options)
63526
64904
  return close ? ensuring$2(write, close) : write;
63527
64905
  });
63528
64906
  if (opts?.onRequest) effect = opts.onRequest(effect, request);
63529
- const tracing = get$12(rpc.annotations, TracingEnabled);
64907
+ const tracing = get$13(rpc.annotations, TracingEnabled);
63530
64908
  if (enableTracing && (tracing === "both" || tracing === "server")) {
63531
64909
  const parentSpan = getOrUndefined$1(requestFiber.context, ParentSpan);
63532
64910
  effect = withSpan(effect, spanName$1(spanPrefix, request.tag), {
@@ -63622,7 +65000,7 @@ const rpcCodecs = (codecFor, rpc) => {
63622
65000
  let codecs = shared ? sharedRpcCodecs.get(rpc) : void 0;
63623
65001
  if (codecs === void 0) {
63624
65002
  const streamSchemas = getStreamSchemas(rpc.successSchema);
63625
- const parseOptions = get$12(rpc.annotations, ParseOptions);
65003
+ const parseOptions = get$13(rpc.annotations, ParseOptions);
63626
65004
  codecs = {
63627
65005
  decode: decodeUnknownEffect(codecFor(rpc.payloadSchema), parseOptions),
63628
65006
  encodeChunk: encodeUnknownEffect(codecFor(NonEmptyArray(isSome(streamSchemas) ? streamSchemas.value.success : Any)), parseOptions),
@@ -63760,7 +65138,7 @@ const make$33 = /*#__PURE__*/ fnUntraced(function* (group, options) {
63760
65138
  const exitSchema$1 = exitSchema(rpc);
63761
65139
  discardSchemas = {
63762
65140
  ...schemas,
63763
- encodeExit: encodeUnknownEffect(codecFor(Exit(Void, exitSchema$1.error, exitSchema$1.defect)), get$12(rpc.annotations, ParseOptions))
65141
+ encodeExit: encodeUnknownEffect(codecFor(Exit(Void, exitSchema$1.error, exitSchema$1.defect)), get$13(rpc.annotations, ParseOptions))
63764
65142
  };
63765
65143
  discardSchemasCache.set(rpc, discardSchemas);
63766
65144
  }
@@ -64225,7 +65603,7 @@ const RpcGroupProto = {
64225
65603
  });
64226
65604
  },
64227
65605
  annotateRpcs(service, value) {
64228
- return this.annotateRpcsMerge(make$89(service, value));
65606
+ return this.annotateRpcsMerge(make$90(service, value));
64229
65607
  },
64230
65608
  annotateMerge(context) {
64231
65609
  return makeProto$1({
@@ -65500,7 +66878,7 @@ const make$29 = /*#__PURE__*/ sync(() => {
65500
66878
  };
65501
66879
  const query = (keys, effect) => gen(function* () {
65502
66880
  const services = yield* context();
65503
- const scope = get$12(services, Scope);
66881
+ const scope = get$13(services, Scope);
65504
66882
  const results = yield* make$76();
65505
66883
  const runFork = flow(runForkWith(services), runIn(scope));
65506
66884
  let running = false;
@@ -67293,7 +68671,7 @@ const migrationsTableExists = (sql, table) => {
67293
68671
  const quotedTable = sql`${sql(table)}`.compile(true)[0];
67294
68672
  return map$7(sql`SELECT 1 AS found WHERE to_regclass(${quotedTable}) IS NOT NULL`.withoutTransform, (rows) => rows.length > 0);
67295
68673
  };
67296
- const migrationOrder = /*#__PURE__*/ make$90(([a], [b]) => Number$6(a, b));
68674
+ const migrationOrder = /*#__PURE__*/ make$91(([a], [b]) => Number$6(a, b));
67297
68675
  const isConstraintConflict = (error) => error.reason._tag === "ConstraintError" || error.reason._tag === "UniqueViolation";
67298
68676
  /**
67299
68677
  * Creates a migration loader from a record of migration effects keyed by
@@ -74418,7 +75796,7 @@ const defaultTimeToLive = (_, _key) => infinity$1;
74418
75796
  * @since 4.0.0
74419
75797
  */
74420
75798
  const get = /*#__PURE__*/ dual(2, (self, key) => withFiber$1((fiber) => {
74421
- const oentry = get$9(self.map, key);
75799
+ const oentry = get$10(self.map, key);
74422
75800
  if (isSome(oentry)) {
74423
75801
  remove$4(self.map, key);
74424
75802
  if (!hasExpired(oentry.value, fiber)) {
@@ -74472,7 +75850,7 @@ var EntryImpl = class {
74472
75850
  }
74473
75851
  };
74474
75852
  const removeEntry = (self, key, entry) => {
74475
- const current = get$9(self.map, key);
75853
+ const current = get$10(self.map, key);
74476
75854
  if (isSome(current) && current.value === entry) remove$4(self.map, key);
74477
75855
  };
74478
75856
  const hasExpired = (entry, fiber) => {
@@ -80393,7 +81771,7 @@ const Strict = /*#__PURE__*/ Reference("effect/ai/Tool/Strict", { defaultValue:
80393
81771
  * @category getters
80394
81772
  * @since 4.0.0
80395
81773
  */
80396
- const getStrictMode = (tool) => get$12(tool.annotations, Strict);
81774
+ const getStrictMode = (tool) => get$13(tool.annotations, Strict);
80397
81775
  /**
80398
81776
  * Schema for denied or interrupted tool calls.
80399
81777
  *
@@ -80614,7 +81992,7 @@ const stringifyToolArguments = (params) => {
80614
81992
  return String(params);
80615
81993
  }
80616
81994
  };
80617
- const failureCause = (error, origin) => annotate$2(fail$8(error), make$89(FailureOrigin, origin));
81995
+ const failureCause = (error, origin) => annotate$2(fail$8(error), make$90(FailureOrigin, origin));
80618
81996
  const failureOrigin = (error) => isSchemaError(error) ? "result" : "handler";
80619
81997
  const Proto$3 = {
80620
81998
  .../*#__PURE__*/ Prototype({
@@ -80721,7 +82099,7 @@ const Proto$3 = {
80721
82099
  reason: error
80722
82100
  }) : error;
80723
82101
  };
80724
- return fromQueue(queue).pipe(tool.failureMode === "error" ? catchCause((cause) => failCause(map$8(fromReasons(cause.reasons.map((reason) => isFailReason(reason) ? reason.annotate(make$89(FailureOrigin, failureOrigin(reason.error)), { overwrite: true }) : reason)), normalizeError))) : catch_((error) => succeed$3({
82102
+ return fromQueue(queue).pipe(tool.failureMode === "error" ? catchCause((cause) => failCause(map$8(fromReasons(cause.reasons.map((reason) => isFailReason(reason) ? reason.annotate(make$90(FailureOrigin, failureOrigin(reason.error)), { overwrite: true }) : reason)), normalizeError))) : catch_((error) => succeed$3({
80725
82103
  result: normalizeError(error),
80726
82104
  isFailure: true,
80727
82105
  failureOrigin: failureOrigin(error),
@@ -87260,7 +88638,7 @@ const getMiddleware = (context) => {
87260
88638
  };
87261
88639
  const isMcpError = (error) => hasProperty(error, "code") && typeof error.code === "number" && hasProperty(error, "message") && typeof error.message === "string";
87262
88640
  const HandlerFailure = /*#__PURE__*/ Reference("effect/ai/McpServer/HandlerFailure", { defaultValue: () => false });
87263
- const handlerFailure = /*#__PURE__*/ make$89(HandlerFailure, true);
88641
+ const handlerFailure = /*#__PURE__*/ make$90(HandlerFailure, true);
87264
88642
  const internalError = /*#__PURE__*/ new InternalError({ message: "Internal error" });
87265
88643
  const rejectWith = (error) => fail$7(new RequestRejected({
87266
88644
  code: error.code,
@@ -87306,7 +88684,7 @@ const runMiddleware = (handler, middleware, invocation, request) => {
87306
88684
  if (isSuccess$2(failure) && !hasDies(cause)) {
87307
88685
  const error = failure.success.error;
87308
88686
  if (isHidden(error)) return fail$7(error);
87309
- if (middleware.length === 0 || get$12(reasonAnnotations(failure.success), HandlerFailure)) return failCause$3(cause);
88687
+ if (middleware.length === 0 || get$13(reasonAnnotations(failure.success), HandlerFailure)) return failCause$3(cause);
87310
88688
  if (isMcpError(error)) return rejectWith(error);
87311
88689
  }
87312
88690
  return logError(cause).pipe(andThen(report(cause)), andThen(rejectWith(internalError)));
@@ -87389,7 +88767,7 @@ var McpServer = class McpServer extends (/*#__PURE__*/ Service$1()("effect/ai/Mc
87389
88767
  const queued = {
87390
88768
  notification,
87391
88769
  delivered,
87392
- requestLiveness: get$12(fiber.context, RequestLiveness),
88770
+ requestLiveness: get$13(fiber.context, RequestLiveness),
87393
88771
  requestContext: getOrUndefined$1(fiber.context, McpRequestContext),
87394
88772
  requestHeaders: getOrUndefined$1(fiber.context, HttpServerRequest)?.headers
87395
88773
  };
@@ -87399,7 +88777,7 @@ var McpServer = class McpServer extends (/*#__PURE__*/ Service$1()("effect/ai/Mc
87399
88777
  _tag: "Exit",
87400
88778
  exit: void_$3
87401
88779
  }));
87402
- const requestQueue = get$12(fiber.context, RequestNotificationQueue);
88780
+ const requestQueue = get$13(fiber.context, RequestNotificationQueue);
87403
88781
  if (requestQueue !== void 0 && queued.requestContext !== void 0 && isRequestNotification(notification)) {
87404
88782
  offerUnsafe(requestQueue, queued);
87405
88783
  return andThen(_await(delivered), acknowledge);
@@ -88526,7 +89904,7 @@ const registerToolkit = /*#__PURE__*/ fnUntraced(function* (toolkit, options) {
88526
89904
  const failure = findFail(cause);
88527
89905
  if (isSuccess$2(failure)) {
88528
89906
  const error = failure.success.error;
88529
- const origin = get$12(reasonAnnotations(failure.success), FailureOrigin);
89907
+ const origin = get$13(reasonAnnotations(failure.success), FailureOrigin);
88530
89908
  if (origin === "parameters" && isParameterValidationError(error)) return fail$7(new InvalidParams({ message: error.reason.message }));
88531
89909
  if (origin === "handler" && isInvalidParams(error)) return fail$7(error);
88532
89910
  if (origin === "handler" && isDeclaredFailure(error)) return catchCause$2(declaredFailureResult(error), internalToolError);
@@ -88537,7 +89915,7 @@ const registerToolkit = /*#__PURE__*/ fnUntraced(function* (toolkit, options) {
88537
89915
  const mapper = content && Object.hasOwn(content, tool.name) ? content[tool.name] : void 0;
88538
89916
  const inputSchema = rawJsonSchema === void 0 ? toolJsonSchema(tool.parametersSchema, strict) : yield* catch_$2(decodeUnknownEffect(ToolJson)(rawJsonSchema), (cause) => die$2(`McpServer cannot register tool '${tool.name}': its raw JSON Schema must have an object root (type: "object").\n\n${cause.message}`));
88539
89917
  const title = getOrUndefined$1(tool.annotations, Title);
88540
- const readOnlyHint = get$12(tool.annotations, Readonly);
89918
+ const readOnlyHint = get$13(tool.annotations, Readonly);
88541
89919
  const fields = {
88542
89920
  name: tool.name,
88543
89921
  title,
@@ -88548,8 +89926,8 @@ const registerToolkit = /*#__PURE__*/ fnUntraced(function* (toolkit, options) {
88548
89926
  ...title !== void 0 ? { title } : void 0,
88549
89927
  readOnlyHint,
88550
89928
  destructiveHint: getOrUndefined$1(tool.annotations, Destructive) ?? !readOnlyHint,
88551
- idempotentHint: get$12(tool.annotations, Idempotent),
88552
- openWorldHint: get$12(tool.annotations, OpenWorld)
89929
+ idempotentHint: get$13(tool.annotations, Idempotent),
89930
+ openWorldHint: get$13(tool.annotations, OpenWorld)
88553
89931
  },
88554
89932
  _meta: isReadonlyObject(toolMeta) ? { ...toolMeta } : toolMeta
88555
89933
  };
@@ -88584,7 +89962,7 @@ const registerToolkit = /*#__PURE__*/ fnUntraced(function* (toolkit, options) {
88584
89962
  content: []
88585
89963
  }) : successResult(result.encodedResult));
88586
89964
  }
88587
- return result.failureOrigin === "handler" ? succeed$5(failureResult(result.encodedResult)) : failCause$3(annotate$2(fail$8(result.result), make$89(FailureOrigin, result.failureOrigin ?? "result")));
89965
+ return result.failureOrigin === "handler" ? succeed$5(failureResult(result.encodedResult)) : failCause$3(annotate$2(fail$8(result.result), make$90(FailureOrigin, result.failureOrigin ?? "result")));
88588
89966
  }), catchCause$2(handleCause));
88589
89967
  },
88590
89968
  services
@@ -89040,9 +90418,11 @@ function upgradeOnlyHeaders(headers) {
89040
90418
  ], toLowerCase(entry[0])));
89041
90419
  }
89042
90420
  const IDENTIFY_PATH = "/api/identify";
90421
+ const IdentifyPurpose = Literals(["use", "verify"]);
89043
90422
  const IdentifyRequest = Struct$2({
89044
90423
  address: OptionFromOptionalKey(NonEmptyString),
89045
90424
  onBehalfOf: OptionFromOptionalKey(UserId),
90425
+ purpose: IdentifyPurpose,
89046
90426
  session: OptionFromOptionalKey(NonEmptyString)
89047
90427
  });
89048
90428
  const DEVELOPER = {
@@ -89143,10 +90523,11 @@ function requireAdmin(user, message) {
89143
90523
  message
89144
90524
  }));
89145
90525
  }
89146
- function identifyRequestOf(headers) {
90526
+ function identifyRequestOf(headers, purpose) {
89147
90527
  return IdentifyRequest.make({
89148
90528
  address: fromNullishOr$1(headers[CLIENT_HEADER]),
89149
90529
  onBehalfOf: flatMap$8(fromNullishOr$1(headers[ON_BEHALF_HEADER]), decodeOption(UserId)),
90530
+ purpose,
89150
90531
  session: fromNullishOr$1(parseHeader(headers["cookie"] ?? "")[SESSION_COOKIE])
89151
90532
  });
89152
90533
  }
@@ -89166,21 +90547,29 @@ function refusalOf(status, message) {
89166
90547
  });
89167
90548
  return AuthError.make({ message });
89168
90549
  }
90550
+ function purposeOf(success) {
90551
+ if (isStreamSchema(success)) return "verify";
90552
+ return "use";
90553
+ }
89169
90554
  var Auth = class Auth extends Service$1()("@deslop/runtime/server/auth") {
89170
- static makeContext = (account, recheck = account) => {
89171
- function user(headers, options) {
89172
- return pipe(suspend$3(() => account(headers)), map$7((found) => ({
90555
+ static makeContext = (identify, refresh = identify) => {
90556
+ function user(headers, purpose, options) {
90557
+ return pipe(suspend$3(() => identify(headers, purpose)), map$7((found) => ({
89173
90558
  admin: found.admin,
89174
90559
  id: found.id,
89175
90560
  name: found.name
89176
90561
  })), withSpan("Auth.user", options));
89177
90562
  }
89178
- return pipe(make$89(Auth, Auth.of({
89179
- account,
89180
- recheck,
89181
- user
89182
- })), add$3(RpcAuth, RpcAuth.of((effect, request) => flatMap$3(user(request.headers), (found) => pipe(effect, provideService$2(CurrentUser, found), raceFirst(recheckUser(user(request.headers, { root: true }), found)))))), add$3(RpcAdmin, RpcAdmin.of((effect, request) => gen(function* () {
89183
- return yield* provideService$2(effect, CurrentAdmin, yield* requireAdmin(yield* user(request.headers), "Only an admin may perform this action"));
90563
+ return pipe(make$90(Auth, Auth.of({
90564
+ account: (headers) => identify(headers, "verify"),
90565
+ recheck: (headers) => refresh(headers, "verify"),
90566
+ user: (headers) => user(headers, "use")
90567
+ })), add$3(RpcAuth, RpcAuth.of((effect, request) => flatMap$3(user(request.headers, purposeOf(request.rpc.successSchema)), (found) => pipe(effect, provideService$2(CurrentUser, found), raceFirst(recheckUser(user(request.headers, "verify", { root: true }), found)))))), add$3(RpcAdmin, RpcAdmin.of((effect, request) => gen(function* () {
90568
+ const caller = yield* match$8(yield* serviceOption(CurrentUser), {
90569
+ onNone: () => user(request.headers, purposeOf(request.rpc.successSchema)),
90570
+ onSome: succeed$5
90571
+ });
90572
+ return yield* provideService$2(effect, CurrentAdmin, yield* requireAdmin(caller, "Only an admin may perform this action"));
89184
90573
  }))));
89185
90574
  };
89186
90575
  static layer = unwrap$7(gen(function* () {
@@ -89191,11 +90580,12 @@ var Auth = class Auth extends Service$1()("@deslop/runtime/server/auth") {
89191
90580
  return effectContext(gen(function* () {
89192
90581
  const issuer = yield* String$5("AUTH_URL");
89193
90582
  const client = yield* HttpClient;
89194
- const answers = yield* makeWith(fnUntraced(function* (body) {
90583
+ const identify = fnUntraced(function* (body) {
89195
90584
  const response = yield* pipe(post(new URL(IDENTIFY_PATH, issuer).href), bodyText(body, "application/json"), client.execute);
89196
90585
  if (response.status === 401 || response.status === 403) return yield* refusalOf(response.status, getOrElse$1(yield* option$1(response.text), constant$1("Sign in first")));
89197
90586
  return yield* schemaBodyJson$1(Account$1)(yield* filterStatusOk$1(response));
89198
- }, outageUnlessRefused("The authorization service is temporarily unavailable")), {
90587
+ }, outageUnlessRefused("The authorization service is temporarily unavailable"));
90588
+ const answers = yield* makeWith(identify, {
89199
90589
  capacity: 1024,
89200
90590
  timeToLive: match$3({
89201
90591
  onFailure: constant$1(0),
@@ -89203,8 +90593,10 @@ var Auth = class Auth extends Service$1()("@deslop/runtime/server/auth") {
89203
90593
  })
89204
90594
  });
89205
90595
  function lookup(refresh) {
89206
- return fn("Auth.account")(function* (headers) {
89207
- const key = yield* encodeEffect(fromJsonString(IdentifyRequest))(identifyRequestOf(headers));
90596
+ return fn("Auth.account")(function* (headers, purpose) {
90597
+ const request = identifyRequestOf(headers, purpose);
90598
+ const key = yield* encodeEffect(fromJsonString(IdentifyRequest))(request);
90599
+ if (purpose === "use" && isSome(request.session)) return yield* identify(key);
89208
90600
  if (refresh) yield* invalidate(answers, key);
89209
90601
  return yield* get(answers, key);
89210
90602
  }, asAuthError("The request could not be read"));
@@ -92576,7 +93968,7 @@ const Formatter = /*#__PURE__*/ Reference("effect/cli/CliOutput", { defaultValue
92576
93968
  */
92577
93969
  const defaultPresenter = { present: /*#__PURE__*/ fnUntraced(function* (event) {
92578
93970
  const context$2 = yield* context();
92579
- const formatter = getOrUndefined$1(context$2, Formatter) ?? defaultFormatter({ colors: get$12(context$2, TerminalCapabilities).canColor });
93971
+ const formatter = getOrUndefined$1(context$2, Formatter) ?? defaultFormatter({ colors: get$13(context$2, TerminalCapabilities).canColor });
92580
93972
  switch (event._tag) {
92581
93973
  case "Help": return yield* log(formatter.formatHelpDoc(event.helpDoc));
92582
93974
  case "InvalidInvocation":
@@ -94995,7 +96387,7 @@ const defaults = { builtIns: BuiltIns };
94995
96387
  *
94996
96388
  * @internal
94997
96389
  */
94998
- const resolveFormatter = /*#__PURE__*/ contextWith((context) => succeed$5(getOrUndefined$1(context, Formatter) ?? defaultFormatter({ colors: get$12(context, TerminalCapabilities).canColor })));
96390
+ const resolveFormatter = /*#__PURE__*/ contextWith((context) => succeed$5(getOrUndefined$1(context, Formatter) ?? defaultFormatter({ colors: get$13(context, TerminalCapabilities).canColor })));
94999
96391
  // ../../node_modules/.pnpm/effect@4.1.7/node_modules/effect/dist/cli/internal/lexer.js
95000
96392
  /**
95001
96393
  * @internal
@@ -96498,7 +97890,7 @@ const runWith = (command, config) => {
96498
97890
  }
96499
97891
  const services = match$8(logLevel, {
96500
97892
  onNone: () => empty$14(),
96501
- onSome: (level) => make$89(MinimumLogLevel, level)
97893
+ onSome: (level) => make$90(MinimumLogLevel, level)
96502
97894
  });
96503
97895
  yield* provideContext$2(program, services);
96504
97896
  }, catchFilter((error) => isCliError(error) && error._tag === "ShowHelp" ? succeed$10(error) : fail$12(error), (error) => andThen(showHelp(command, error, config.renderErrors !== false), fail$7(error))), catchFilter((error) => {
@@ -96802,6 +98194,8 @@ const publicAccess = [
96802
98194
  },
96803
98195
  ...map$10([
96804
98196
  "chapters.events",
98197
+ "chapters.manifest",
98198
+ "chapters.progress",
96805
98199
  "push.register",
96806
98200
  "chapters.write"
96807
98201
  ], (name) => ({
@@ -96836,7 +98230,11 @@ const publicAccess = [
96836
98230
  }),
96837
98231
  surface: "http POST /v1/github"
96838
98232
  },
96839
- ...map$10(["telemetry.watch", "telemetry.trace"], (name) => ({
98233
+ ...map$10([
98234
+ "telemetry.watch",
98235
+ "telemetry.trace",
98236
+ "telemetry.diagnostic"
98237
+ ], (name) => ({
96840
98238
  app: "scope",
96841
98239
  callers: ["member"],
96842
98240
  surface: `rpc ${name}`
@@ -96894,7 +98292,6 @@ const publicAccess = [
96894
98292
  "flights.events",
96895
98293
  "flights.save",
96896
98294
  "flights.remove",
96897
- "travel.list",
96898
98295
  "travel.set",
96899
98296
  "push.register"
96900
98297
  ], (name) => ({
@@ -97244,7 +98641,7 @@ function recordToolContracts(contracts) {
97244
98641
  }
97245
98642
  function sample(schema$4, name) {
97246
98643
  return mapError$2(gen(function* () {
97247
- const input = yield* pipe(FIXED_INPUTS, get$11(name), match$8({
98644
+ const input = yield* pipe(FIXED_INPUTS, get$12(name), match$8({
97248
98645
  onNone: () => flatMap$3(sampleEffect(schema(toEncoded(schema$4)), {
97249
98646
  count: 1,
97250
98647
  seed: 1,
@@ -97328,7 +98725,7 @@ function probeServer(start) {
97328
98725
  HOME: probe.directory,
97329
98726
  HOST: "127.0.0.1"
97330
98727
  }))), build);
97331
- const origin = formatAddress(get$12(context, HttpServer).address);
98728
+ const origin = formatAddress(get$13(context, HttpServer).address);
97332
98729
  for (const identity of ["member", "admin"]) {
97333
98730
  const response = yield* pipe(get$2(`${origin}/api/account`), setHeader$1("x-probe-caller", identity), execute);
97334
98731
  const account = yield* schemaBodyJson$1(Account$1)(response);
@@ -97441,11 +98838,13 @@ function probeServer(start) {
97441
98838
  }
97442
98839
  // ../../packages/runtime/src/shared/rpc.ts
97443
98840
  var RpcStream = class extends Service()("@deslop/runtime/shared/rpc/RpcStream") {};
98841
+ const ReadMethod = Reference("@deslop/runtime/shared/rpc/ReadMethod", { defaultValue: none });
97444
98842
  const layerRpcStream = succeed$6(RpcStream, RpcStream.of((effect, options) => {
97445
98843
  if (!isStreamSchema(options.rpc.successSchema)) return effect;
97446
98844
  return andThen(annotateCurrentSpan("rpc.stream", true), effect);
97447
98845
  }));
97448
98846
  layerClient(RpcStream, (options) => gen(function* () {
98847
+ map$13(yield* ReadMethod, (note) => note(options.rpc._tag));
97449
98848
  if (isStreamSchema(options.rpc.successSchema)) yield* annotateCurrentSpan("rpc.stream", true);
97450
98849
  return yield* options.next(options.request);
97451
98850
  }));
@@ -97559,13 +98958,13 @@ const layerFlusher = /*#__PURE__*/ sync$1(Flusher, () => {
97559
98958
  */
97560
98959
  const make$5 = /*#__PURE__*/ fnUntraced(function* (options) {
97561
98960
  const services = yield* context();
97562
- const clock = get$12(services, Clock);
97563
- const scope = get$12(services, Scope);
97564
- const exportInterval = max(fromInputUnsafe$1(options.exportInterval), zero$2);
98961
+ const clock = get$13(services, Clock);
98962
+ const scope = get$13(services, Scope);
98963
+ const exportInterval = max$1(fromInputUnsafe$1(options.exportInterval), zero$2);
97565
98964
  const batchLimit = options.maxBatchSize === "disabled" ? Infinity : normalizeNonEmpty(options.maxBatchSize);
97566
98965
  const maxQueueSize = options.maxQueueSize === void 0 || Number.isNaN(options.maxQueueSize) ? Number.isFinite(batchLimit) ? Math.max(2048, batchLimit) : 2048 : normalize$2(options.maxQueueSize);
97567
98966
  const concurrency = options.concurrency === "unbounded" ? Infinity : options.concurrency === void 0 || Number.isNaN(options.concurrency) ? 4 : normalizeNonEmpty(options.concurrency);
97568
- const client = get$12(services, HttpClient).pipe(tap((response) => ignore$1(response.arrayBuffer)), tapError((error) => error.response ? ignore$1(error.response.arrayBuffer) : void_$2), filterStatusOk, transformResponse(provideService$2(TracerPropagationEnabled, false)), retryTransient({
98967
+ const client = get$13(services, HttpClient).pipe(tap((response) => ignore$1(response.arrayBuffer)), tapError((error) => error.response ? ignore$1(error.response.arrayBuffer) : void_$2), filterStatusOk, transformResponse(provideService$2(TracerPropagationEnabled, false)), retryTransient({
97569
98968
  schedule: policy,
97570
98969
  times: 3
97571
98970
  }));
@@ -98200,10 +99599,40 @@ Literals([
98200
99599
  "mobile",
98201
99600
  "server"
98202
99601
  ]);
98203
- function layerOtlp(serviceName, url, runtime, version) {
98204
- return catchCause$3(unwrap$7(gen(function* () {
98205
- const start = `${yield* currentTimeNanos}`;
98206
- const redacted = yield* CurrentRedactedNames;
99602
+ function emitFirstValue(tracer, value) {
99603
+ const span = tracer.span({
99604
+ annotations: empty$14(),
99605
+ kind: "client",
99606
+ links: [],
99607
+ name: "Read.firstValue",
99608
+ parent: none(),
99609
+ root: true,
99610
+ sampled: true,
99611
+ startTime: value.start
99612
+ });
99613
+ map$13(value.method, (method) => span.attribute("rpc.method", method));
99614
+ span.end(value.end, void_$3);
99615
+ }
99616
+ Reference("@deslop/runtime/shared/telemetry/FirstValueSink", { defaultValue: () => (value) => map$7(tracer$1, (tracer) => emitFirstValue(tracer, value)) });
99617
+ const layerTelemetryRedaction = effect(CurrentRedactedNames, map$7(CurrentRedactedNames, (redacted) => dedupe([
99618
+ ...redacted,
99619
+ "code",
99620
+ "state",
99621
+ "request",
99622
+ "access_token",
99623
+ "refresh_token",
99624
+ "id_token",
99625
+ "client_secret",
99626
+ "client_assertion",
99627
+ "code_verifier",
99628
+ "session",
99629
+ "token",
99630
+ "api_key",
99631
+ "key"
99632
+ ])));
99633
+ function layerOtlp(serviceName, url, runtime, version, started) {
99634
+ return pipe(unwrap$7(gen(function* () {
99635
+ const start = `${started ?? (yield* currentTimeNanos)}`;
98207
99636
  const resource = {
98208
99637
  attributes: {
98209
99638
  "scope.run.started_unix_nano": start,
@@ -98219,26 +99648,11 @@ function layerOtlp(serviceName, url, runtime, version) {
98219
99648
  }), layer$2({
98220
99649
  resource,
98221
99650
  url: new URL("/v1/logs", url).href
98222
- }), succeed$6(CurrentRedactedNames, [
98223
- ...redacted,
98224
- "code",
98225
- "state",
98226
- "request",
98227
- "access_token",
98228
- "refresh_token",
98229
- "id_token",
98230
- "client_secret",
98231
- "client_assertion",
98232
- "code_verifier",
98233
- "session",
98234
- "token",
98235
- "api_key",
98236
- "key"
98237
- ])), [layerJson, layer$15]);
98238
- })), (cause) => {
99651
+ })), [layerJson, layer$15]);
99652
+ })), catchCause$3((cause) => {
98239
99653
  if (hasInterrupts(cause)) return effectDiscard(interrupt$1);
98240
99654
  return effectDiscard(logWarning("Telemetry is unavailable"));
98241
- });
99655
+ }), provideMerge(layerTelemetryRedaction));
98242
99656
  }
98243
99657
  // ../../packages/runtime/src/server/http.ts
98244
99658
  const LOOPBACK = /^(?:localhost|\d{1,3}(?:\.\d{1,3}){3}|\[[\da-f:.]+\])$/iu;
@@ -98489,7 +99903,7 @@ const make$1 = (options) => gen(function* () {
98489
99903
  timeToLive: (exit) => isSuccess$1(exit) ? prepareCacheTTL : zero$2
98490
99904
  });
98491
99905
  const runStatement = (statement, params, raw) => withFiber((fiber) => {
98492
- const useSafeIntegers = get$12(fiber.context, SafeIntegers);
99906
+ const useSafeIntegers = get$13(fiber.context, SafeIntegers);
98493
99907
  return try_({
98494
99908
  try: () => {
98495
99909
  statement.setReadBigInts(useSafeIntegers);
@@ -98504,7 +99918,7 @@ const make$1 = (options) => gen(function* () {
98504
99918
  });
98505
99919
  });
98506
99920
  const runStatementValues = (statement, params) => withFiber((fiber) => {
98507
- const useSafeIntegers = get$12(fiber.context, SafeIntegers);
99921
+ const useSafeIntegers = get$13(fiber.context, SafeIntegers);
98508
99922
  return try_({
98509
99923
  try: () => {
98510
99924
  statement.setReadBigInts(useSafeIntegers);
@@ -98514,7 +99928,7 @@ const make$1 = (options) => gen(function* () {
98514
99928
  });
98515
99929
  });
98516
99930
  const runStatementValuesUnprepared = (statement, params) => withFiber((fiber) => {
98517
- const useSafeIntegers = get$12(fiber.context, SafeIntegers);
99931
+ const useSafeIntegers = get$13(fiber.context, SafeIntegers);
98518
99932
  return try_({
98519
99933
  try: () => {
98520
99934
  statement.setReadBigInts(useSafeIntegers);
@@ -98604,7 +100018,7 @@ const make$1 = (options) => gen(function* () {
98604
100018
  * @category layers
98605
100019
  * @since 4.0.0
98606
100020
  */
98607
- const layer = (config) => effectContext(map$7(make$1(config), (client) => make$89(SqliteClient, client).pipe(add$3(SqlClient, client)))).pipe(provide$2(layer$19));
100021
+ const layer = (config) => effectContext(map$7(make$1(config), (client) => make$90(SqliteClient, client).pipe(add$3(SqlClient, client)))).pipe(provide$2(layer$19));
98608
100022
  const classifyError = (cause, message, operation) => classifySqliteError(sqliteCauseWithErrno(cause), {
98609
100023
  message,
98610
100024
  operation
@@ -99494,8 +100908,12 @@ const AdmitParams = Struct$2({
99494
100908
  allow: Boolean$5,
99495
100909
  id: UserId
99496
100910
  });
100911
+ var PeopleReadError = class extends TaggedError()("PeopleReadError", {
100912
+ cause: optional$8(Defect()),
100913
+ message: String$6
100914
+ }) {};
99497
100915
  const PeopleRpcs = make$32(make$36("people.watch", {
99498
- error: AuthError,
100916
+ error: PeopleReadError,
99499
100917
  stream: true,
99500
100918
  success: ArraySchema(Person)
99501
100919
  }).middleware(RpcAdmin), make$36("people.admit", {
@@ -99533,8 +100951,9 @@ const IdentityRpcs = make$32(make$36("people.account", {
99533
100951
  var ListedSession = class extends Class("ListedSession")({
99534
100952
  address: FieldOption(String$6),
99535
100953
  browser: String$6,
100954
+ expiresAt: DateTimeUtcFromMillis,
99536
100955
  id: String$6,
99537
- lastSeenAt: DateTimeUtcFromMillis,
100956
+ lastActivityAt: FieldOption(DateTimeUtcFromMillis),
99538
100957
  current: Boolean$5
99539
100958
  }) {};
99540
100959
  const SessionsRpcs = make$32(make$36("sessions.watch", {
@@ -99547,6 +100966,7 @@ var CookieSession = class extends Class("CookieSession")({
99547
100966
  browser: String$6,
99548
100967
  createdAt: DateTimeUtcFromMillis,
99549
100968
  id: String$6,
100969
+ lastActivityAt: FieldOption(DateTimeUtcFromMillis),
99550
100970
  lastSeenAt: DateTimeUtcFromMillis,
99551
100971
  userId: UserId
99552
100972
  }) {
@@ -99803,11 +101223,22 @@ const peopleMigrations = effectDiscard(make$26({})({
99803
101223
  const sessionsMigrations = effectDiscard(make$26({})({
99804
101224
  loader: fromRecord({
99805
101225
  "0001_cookie_sessions": flatMap$3(SqlClient, (sql) => sql`CREATE TABLE cookie_sessions (id TEXT PRIMARY KEY, userId TEXT NOT NULL, address TEXT, browser TEXT NOT NULL, createdAt INTEGER NOT NULL, lastSeenAt INTEGER NOT NULL) STRICT`),
99806
- "0002_user_sessions": flatMap$3(SqlClient, (sql) => sql`CREATE INDEX cookie_sessions_user ON cookie_sessions (userId, lastSeenAt)`)
101226
+ "0002_user_sessions": flatMap$3(SqlClient, (sql) => sql`CREATE INDEX cookie_sessions_user ON cookie_sessions (userId, lastSeenAt)`),
101227
+ "0003_meaningful_session_activity": flatMap$3(SqlClient, (sql) => sql`ALTER TABLE cookie_sessions ADD COLUMN lastActivityAt INTEGER`)
99807
101228
  }),
99808
101229
  table: "cookie_sessions_migrations"
99809
101230
  }));
99810
101231
  // src/sessions/server.ts
101232
+ const IDLE_DAYS = 30;
101233
+ function cutoff(now) {
101234
+ return toEpochMillis(subtract(now, { days: IDLE_DAYS }));
101235
+ }
101236
+ function expiresAt(row) {
101237
+ return add$1(row.lastSeenAt, { days: IDLE_DAYS });
101238
+ }
101239
+ function sessionRows(user) {
101240
+ return `sessionRows:${user}`;
101241
+ }
99811
101242
  var Sessions = class Sessions extends Service$1()("@deslop/auth/sessions/server/Sessions") {
99812
101243
  static migrations = sessionsMigrations;
99813
101244
  static layer = provide$2(effect(Sessions, gen(function* () {
@@ -99819,36 +101250,65 @@ var Sessions = class Sessions extends Service$1()("@deslop/auth/sessions/server/
99819
101250
  return map$7(digest.digest(sha256, new TextEncoder().encode(secret)), encode$1);
99820
101251
  }
99821
101252
  const table = sql(CookieSession.table);
99822
- function mutate(effect) {
99823
- return pipe(effect, mutation(["sessions"]), provideService$2(Reactivity, reactivity));
101253
+ function changed(user, identity) {
101254
+ const keys = match(identity, {
101255
+ onFalse: () => [sessionRows(user)],
101256
+ onTrue: () => ["sessions", sessionRows(user)]
101257
+ });
101258
+ return sql.afterCommit(sync(() => reactivity.invalidateUnsafe(keys)));
99824
101259
  }
99825
- const cutoff = map$7(now, (now) => subtract(now, { days: 30 }));
99826
101260
  const insert = void_({
99827
101261
  Request: CookieSession.insert,
99828
101262
  execute: (row) => sql`INSERT INTO ${table} ${sql.insert(row)}`
99829
101263
  });
99830
- yield* pipe(cutoff, flatMap$3((since) => sql`DELETE FROM ${table} WHERE lastSeenAt <= ${toEpochMillis(since)}`), withSpan("Sessions.sweep"), ignore$1({
101264
+ yield* pipe(now, flatMap$3((now) => sql`DELETE FROM ${table} WHERE lastSeenAt <= ${cutoff(now)}`), withSpan("Sessions.sweep"), ignore$1({
99831
101265
  log: "Warn",
99832
101266
  message: "Expired sessions could not be deleted"
99833
101267
  }), repeat(spaced(hours(1))), forkScoped);
99834
- const current = fn("Sessions.current")(function* (secret) {
101268
+ const current = fn("Sessions.current")(function* (secret, purpose) {
99835
101269
  const id = yield* hash(secret);
99836
- const now$3 = toEpochMillis(yield* now);
99837
- const since = toEpochMillis(yield* cutoff);
99838
- return yield* findOneOption({
101270
+ const at = yield* now;
101271
+ const now$3 = toEpochMillis(at);
101272
+ const since = cutoff(at);
101273
+ const use = purpose === "use";
101274
+ const touched = yield* findOneOption({
99839
101275
  Request: Void,
99840
101276
  Result: CookieSession,
99841
- execute: () => sql`UPDATE ${table} SET lastSeenAt = ${now$3} WHERE id = ${id} AND lastSeenAt > ${since} RETURNING *`
101277
+ execute: () => sql`UPDATE ${table}
101278
+ SET lastSeenAt = ${now$3},
101279
+ lastActivityAt = CASE WHEN ${use} THEN max(coalesce(lastActivityAt, ${now$3}), ${now$3}) ELSE lastActivityAt END
101280
+ WHERE id = ${id} AND lastSeenAt > ${since}
101281
+ AND (lastSeenAt <> ${now$3} OR (${use} AND (lastActivityAt IS NULL OR lastActivityAt < ${now$3})))
101282
+ RETURNING *`
99842
101283
  })();
99843
- }, asAuthError("Cannot read the session"));
101284
+ return yield* match$8(touched, {
101285
+ onNone: () => findOneOption({
101286
+ Request: Void,
101287
+ Result: CookieSession,
101288
+ execute: () => sql`SELECT * FROM ${table} WHERE id = ${id} AND lastSeenAt > ${since}`
101289
+ })(),
101290
+ onSome: (row) => as(changed(row.userId, false), touched)
101291
+ });
101292
+ }, sql.withTransaction, asAuthError("Cannot read the session"));
99844
101293
  const list = fn("Sessions.list")(function* (user) {
99845
- const since = toEpochMillis(yield* cutoff);
101294
+ const since = cutoff(yield* now);
99846
101295
  return yield* findAll({
99847
101296
  Request: Void,
99848
101297
  Result: CookieSession,
99849
- execute: () => sql`SELECT * FROM ${table} WHERE userId = ${user} AND lastSeenAt > ${since} ORDER BY lastSeenAt DESC`
101298
+ execute: () => sql`SELECT * FROM ${table} WHERE userId = ${user} AND lastSeenAt > ${since}
101299
+ ORDER BY lastActivityAt DESC, createdAt DESC`
99850
101300
  })();
99851
101301
  }, asAuthError("Cannot list sessions"));
101302
+ const liveRows = yield* make$74({ lookup: (user) => pipe(sql.reactive([sessionRows(user)], list(user)), switchMap((rows) => concat$2(succeed$3(rows), unfold(rows, fnUntraced(function* (live) {
101303
+ if (!isReadonlyArrayNonEmpty(live)) return void 0;
101304
+ const due = pipe(live, map$10((row) => toEpochMillis(expiresAt(row))), min$1(Order$4));
101305
+ yield* sleep(max(0, due - toEpochMillis(yield* now)));
101306
+ return yield* map$7(list(user), (next) => make$88(next, next));
101307
+ })))), share({
101308
+ capacity: 1,
101309
+ replay: 1,
101310
+ strategy: "sliding"
101311
+ })) });
99852
101312
  return Sessions.of({
99853
101313
  create: fn("Sessions.create")(function* (user, address, browser) {
99854
101314
  const secret = encode$1(yield* random.randomBytes(32));
@@ -99858,35 +101318,48 @@ var Sessions = class Sessions extends Service$1()("@deslop/auth/sessions/server/
99858
101318
  browser,
99859
101319
  createdAt: now$4,
99860
101320
  id: yield* hash(secret),
101321
+ lastActivityAt: some$1(now$4),
99861
101322
  lastSeenAt: now$4,
99862
101323
  userId: user
99863
101324
  });
101325
+ yield* changed(user, true);
99864
101326
  return secret;
99865
- }, mutate, asAuthError("Cannot create the session")),
101327
+ }, asAuthError("Cannot create the session")),
99866
101328
  current,
99867
101329
  forget: fn("Sessions.forget")(function* (secret) {
99868
- yield* sql`DELETE FROM ${table} WHERE id = ${yield* hash(secret)}`;
99869
- }, mutate, asAuthError("Cannot sign out; no changes committed")),
101330
+ const id = yield* hash(secret);
101331
+ const deleted = yield* findOneOption({
101332
+ Request: Void,
101333
+ Result: Struct$2({ userId: UserId }),
101334
+ execute: () => sql`DELETE FROM ${table} WHERE id = ${id} RETURNING userId`
101335
+ })();
101336
+ yield* match$8(deleted, {
101337
+ onNone: () => void_$2,
101338
+ onSome: (row) => changed(row.userId, true)
101339
+ });
101340
+ }, asAuthError("Cannot sign out; no changes committed")),
99870
101341
  forgetPerson: fn("Sessions.forgetPerson")(function* (user) {
99871
101342
  yield* sql`DELETE FROM ${table} WHERE userId = ${user}`;
99872
- }, mutate, asAuthError("Cannot sign out the person; no changes committed")),
101343
+ yield* changed(user, true);
101344
+ }, asAuthError("Cannot sign out the person; no changes committed")),
99873
101345
  list,
99874
101346
  remove: fn("Sessions.remove")(function* (id, user) {
99875
101347
  yield* sql`DELETE FROM ${table} WHERE id = ${id} AND userId = ${user}`;
99876
- }, mutate, asAuthError("Cannot sign out the session; no changes committed")),
101348
+ yield* changed(user, true);
101349
+ }, asAuthError("Cannot sign out the session; no changes committed")),
99877
101350
  watch: (user, secret) => unwrap$4(gen(function* () {
99878
101351
  const own = yield* match$8(secret, {
99879
101352
  onNone: () => succeedNone,
99880
- onSome: current
101353
+ onSome: (value) => asSome(hash(value))
99881
101354
  });
99882
- const listed = map$7(list(user), map$10((row) => ListedSession.make({
101355
+ return pipe(yield* get$8(liveRows, user), map$5(map$10((row) => ListedSession.make({
99883
101356
  address: row.address,
99884
101357
  browser: row.browser,
99885
- current: exists(own, (found) => found.id === row.id),
101358
+ current: contains$2(own, row.id),
101359
+ expiresAt: expiresAt(row),
99886
101360
  id: row.id,
99887
- lastSeenAt: row.lastSeenAt
99888
- })));
99889
- return pipe(tick("1 minute"), switchMap(() => sql.reactive(["sessions"], listed)), changesWith(toEquivalence(ArraySchema(ListedSession))), buffer$1({
101361
+ lastActivityAt: row.lastActivityAt
101362
+ }))), changesWith(toEquivalence(ArraySchema(ListedSession))), buffer$1({
99890
101363
  capacity: 1,
99891
101364
  strategy: "sliding"
99892
101365
  }));
@@ -99952,6 +101425,8 @@ function personOf(admins, row) {
99952
101425
  since: row.since
99953
101426
  });
99954
101427
  }
101428
+ const roleOrder = mapInput(Order$4, (person) => ROLE_ORDER[person.role]);
101429
+ const newestRequest = mapInput(flip$1(Order$4), (person) => pipe(person.requestedAt, orElse$3(() => person.since), map$13(toEpochMillis), getOrElse$1(() => -Infinity)));
99955
101430
  function listPeople(rows, admins) {
99956
101431
  const known = map$10(rows, (row) => personOf(admins, row));
99957
101432
  const knownIds = fromIterable(map$10(known, (person) => person.id));
@@ -99963,7 +101438,10 @@ function listPeople(rows, admins) {
99963
101438
  requestedAt: none(),
99964
101439
  role: "Admin",
99965
101440
  since: none()
99966
- }))), ...known], mapInput(Order$4, (person) => ROLE_ORDER[person.role]));
101441
+ }))), ...known], combine$3(roleOrder, (a, b) => {
101442
+ if (a.role !== "Waiting") return 0;
101443
+ return newestRequest(a, b);
101444
+ }));
99967
101445
  }
99968
101446
  var People = class People extends Service$1()("@deslop/auth/people/server/People") {
99969
101447
  static migrations = peopleMigrations;
@@ -100007,7 +101485,10 @@ var People = class People extends Service$1()("@deslop/auth/people/server/People
100007
101485
  });
100008
101486
  const list = fn("People.list")(function* (_admin) {
100009
101487
  return listPeople(yield* all(), admins);
100010
- }, asAuthError("Cannot read people"));
101488
+ }, mapError$2((cause) => PeopleReadError.make({
101489
+ cause,
101490
+ message: "Cannot read people"
101491
+ })));
100011
101492
  return People.of({
100012
101493
  admit: fn("People.admit")(function* (params) {
100013
101494
  const row = yield* existing(params.id);
@@ -100094,8 +101575,7 @@ function unavailable(message) {
100094
101575
  }
100095
101576
  var Tailnet = class Tailnet extends Service$1()("@deslop/auth/tailnet/server/Tailnet") {
100096
101577
  static layer = effect(Tailnet, gen(function* () {
100097
- const spawner = yield* ChildProcessSpawner;
100098
- const status = yield* makeWith(() => pipe(executeProcess("tailscale", ["status", "--json"], { timeout: "10 seconds" }), flatMap$3(decodeUnknownEffect(StatusJson)), provideService$2(ChildProcessSpawner, spawner), unavailable("Cannot read the tailnet owner")), {
101578
+ const status = yield* makeWith(() => pipe(executeProcess("tailscale", ["status", "--json"], { timeout: "10 seconds" }), flatMap$3((text) => withSpan(decodeEffect(StatusJson)(text), "Tailnet.decodeStatus")), unavailable("Cannot read the tailnet owner"), withSpan("Tailnet.status")), {
100099
101579
  capacity: 1,
100100
101580
  timeToLive: match$3({
100101
101581
  onFailure: constant$1(0),
@@ -100106,7 +101586,7 @@ var Tailnet = class Tailnet extends Service$1()("@deslop/auth/tailnet/server/Tai
100106
101586
  "whois",
100107
101587
  "--json",
100108
101588
  address
100109
- ], { timeout: "10 seconds" }), flatMap$3(decodeUnknownEffect(WhoisJson)), provideService$2(ChildProcessSpawner, spawner), unavailable("Cannot identify the tailnet caller")), {
101589
+ ], { timeout: "10 seconds" }), flatMap$3((text) => withSpan(decodeEffect(WhoisJson)(text), "Tailnet.decodeWhois")), unavailable("Cannot identify the tailnet caller"), withSpan("Tailnet.whois")), {
100110
101590
  capacity: 1024,
100111
101591
  timeToLive: match$3({
100112
101592
  onFailure: constant$1(0),
@@ -100167,7 +101647,7 @@ var Identity = class Identity extends Service$1()("@deslop/auth/identity/server/
100167
101647
  };
100168
101648
  const identified = yield* match$8(yield* match$8(request.session, {
100169
101649
  onNone: () => succeedNone,
100170
- onSome: sessions.current
101650
+ onSome: (secret) => sessions.current(secret, request.purpose)
100171
101651
  }), {
100172
101652
  onNone: () => pipe(request.address, match$8({
100173
101653
  onNone: () => fail$7(AuthError.make({ message: "Sign in first" })),
@@ -100176,7 +101656,7 @@ var Identity = class Identity extends Service$1()("@deslop/auth/identity/server/
100176
101656
  onNone: () => gen(function* () {
100177
101657
  const found = yield* owners.status;
100178
101658
  if ((found.Self.Tags?.length ?? 0) > 0) return yield* AuthError.make({ message: "Sign in first" });
100179
- return yield* pipe(found.User, get$11(found.Self.UserID), match$8({
101659
+ return yield* pipe(found.User, get$12(found.Self.UserID), match$8({
100180
101660
  onNone: () => fail$7(AuthError.make({ message: "Sign in first" })),
100181
101661
  onSome: tailnet
100182
101662
  }));
@@ -100231,7 +101711,7 @@ const watchIdentity = gen(function* () {
100231
101711
  function authResponse(effect) {
100232
101712
  return pipe(effect, catchIf(is$2(AuthError), (error) => succeed$5(text(error.message, failureOptions(error, 401)))), map$7(setHeader("cache-control", "no-store")));
100233
101713
  }
100234
- const identityHandlers = IdentityRpcs.toLayer(map$7(watchIdentity, (watch) => ({ "people.account": (_, options) => watch(identifyRequestOf(options.headers)) })));
101714
+ const identityHandlers = IdentityRpcs.toLayer(map$7(watchIdentity, (watch) => ({ "people.account": (_, options) => watch(identifyRequestOf(options.headers, "verify")) })));
100235
101715
  const identityHttp = use((router) => gen(function* () {
100236
101716
  const identity = yield* Identity;
100237
101717
  yield* router.add("POST", IDENTIFY_PATH, authResponse(gen(function* () {
@@ -100247,7 +101727,7 @@ const identityHttp = use((router) => gen(function* () {
100247
101727
  const peopleTools = make$13(make$14("list_people", {
100248
101728
  dependencies: [CurrentUser],
100249
101729
  description: "List people and access requests. Only admins may list people.",
100250
- failure: AuthError,
101730
+ failure: Union$2([AuthError, PeopleReadError]),
100251
101731
  parameters: EmptyParams,
100252
101732
  success: Struct$2({ people: ArraySchema(Person) })
100253
101733
  }).annotate(Readonly, true).annotate(Destructive, false).annotate(Strict, true), make$14("remove_person", {
@@ -100297,7 +101777,7 @@ const sessionsToolHandlers = sessionsTools.toLayer(map$7(Sessions, (sessions) =>
100297
101777
  return { id: input.id };
100298
101778
  })
100299
101779
  })));
100300
- const sessionsHandlers = SessionsRpcs.toLayer(map$7(Sessions, (sessions) => ({ "sessions.watch": (_, options) => unwrap$4(map$7(CurrentUser, (user) => sessions.watch(user.id, identifyRequestOf(options.headers).session))) })));
101780
+ const sessionsHandlers = SessionsRpcs.toLayer(map$7(Sessions, (sessions) => ({ "sessions.watch": (_, options) => unwrap$4(map$7(CurrentUser, (user) => sessions.watch(user.id, identifyRequestOf(options.headers, "verify").session))) })));
100301
101781
  // ../../packages/components/src/shared/styles.ts
100302
101782
  const black = "#000";
100303
101783
  const ink = "#f4f4f4";
@@ -100517,10 +101997,11 @@ var SignIns = class SignIns extends Service$1()("@deslop/auth/sign-ins/server/Si
100517
101997
  function nativeCallback(app, answer) {
100518
101998
  return new URL(`/signed-in/${app}?${answer}`, canonical).href;
100519
101999
  }
100520
- function accountFor(session) {
102000
+ function accountFor(session, purpose) {
100521
102001
  return identity.resolve(IdentifyRequest.make({
100522
102002
  address: none(),
100523
102003
  onBehalfOf: none(),
102004
+ purpose,
100524
102005
  session: some$1(session)
100525
102006
  }), true);
100526
102007
  }
@@ -100551,7 +102032,7 @@ var SignIns = class SignIns extends Service$1()("@deslop/auth/sign-ins/server/Si
100551
102032
  name: profile.login
100552
102033
  }, profile.name, false)).id, fromNullishOr$1(headers[CLIENT_HEADER]), headers["user-agent"] ?? "Browser");
100553
102034
  return {
100554
- role: (yield* accountFor(secret)).role,
102035
+ role: (yield* accountFor(secret, "use")).role,
100555
102036
  secret
100556
102037
  };
100557
102038
  }))), asAuthError("Cannot finish the sign-in"), flatMap$3(fnUntraced(function* (signed) {
@@ -100640,7 +102121,7 @@ var SignIns = class SignIns extends Service$1()("@deslop/auth/sign-ins/server/Si
100640
102121
  message: "Invalid waiting sign-in"
100641
102122
  });
100642
102123
  return yield* pipe(sql.withTransaction(gen(function* () {
100643
- const account = yield* accountFor(pending.session);
102124
+ const account = yield* accountFor(pending.session, "verify");
100644
102125
  if (!isGreaterThan$1(pending.expires, yield* now)) {
100645
102126
  if (account.role === "Waiting") yield* sessions.forget(pending.session);
100646
102127
  return ended("The sign-in expired; sign in again");
@@ -100724,7 +102205,7 @@ var icon_default = "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 64 6
100724
102205
  const layerServices = pipe(SignIns.layer, provideMerge(Identity.layer), provide$2(Tailnet.layer), provideMerge(People.layer), provideMerge(mergeAll$1(Sessions.layer, GitHub.layer)), provide$2(succeed$6(RequestInit, { redirect: "error" })));
100725
102206
  const toolkit = merge(peopleTools, sessionsTools);
100726
102207
  runApp({
100727
- auth: provide$2(effectContext(map$7(Identity, (identity) => Auth.makeContext((headers) => withSpan(identity.resolve(identifyRequestOf(headers)), "Identity.account")))), layerServices),
102208
+ auth: provide$2(effectContext(map$7(Identity, (identity) => Auth.makeContext((headers, purpose) => withSpan(identity.resolve(identifyRequestOf(headers, purpose)), "Identity.account")))), layerServices),
100728
102209
  icon: icon_default,
100729
102210
  middleware: (app) => map$7(app, setHeader("content-security-policy", "frame-ancestors 'none'")),
100730
102211
  routes: provide$2(mergeAll$1(identityHttp, signInsHttp, layerRpc({