@arcote.tech/arc-host 0.1.9 → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -554,8 +554,8 @@ var require_sign_stream = __commonJS((exports, module) => {
554
554
  var Stream = __require("node:stream");
555
555
  var toString = require_tostring();
556
556
  var util = __require("node:util");
557
- function base64url(string2, encoding) {
558
- return Buffer2.from(string2, encoding).toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
557
+ function base64url(string, encoding) {
558
+ return Buffer2.from(string, encoding).toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
559
559
  }
560
560
  function jwsSecuredInput(header, payload, encoding) {
561
561
  encoding = encoding || "utf8";
@@ -623,11 +623,11 @@ var require_verify_stream = __commonJS((exports, module) => {
623
623
  var toString = require_tostring();
624
624
  var util = __require("node:util");
625
625
  var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;
626
- function isObject2(thing) {
626
+ function isObject(thing) {
627
627
  return Object.prototype.toString.call(thing) === "[object Object]";
628
628
  }
629
629
  function safeJsonParse(thing) {
630
- if (isObject2(thing))
630
+ if (isObject(thing))
631
631
  return thing;
632
632
  try {
633
633
  return JSON.parse(thing);
@@ -650,8 +650,8 @@ var require_verify_stream = __commonJS((exports, module) => {
650
650
  var payload = jwsSig.split(".")[1];
651
651
  return Buffer2.from(payload, "base64").toString(encoding);
652
652
  }
653
- function isValidJws(string2) {
654
- return JWS_REGEX.test(string2) && !!headerFromJWS(string2);
653
+ function isValidJws(string) {
654
+ return JWS_REGEX.test(string) && !!headerFromJWS(string);
655
655
  }
656
656
  function jwsVerify(jwsSig, algorithm, secretOrKey) {
657
657
  if (!algorithm) {
@@ -1155,14 +1155,14 @@ var require_semver = __commonJS((exports, module) => {
1155
1155
  if (!m[4]) {
1156
1156
  this.prerelease = [];
1157
1157
  } else {
1158
- this.prerelease = m[4].split(".").map((id2) => {
1159
- if (/^[0-9]+$/.test(id2)) {
1160
- const num = +id2;
1158
+ this.prerelease = m[4].split(".").map((id) => {
1159
+ if (/^[0-9]+$/.test(id)) {
1160
+ const num = +id;
1161
1161
  if (num >= 0 && num < MAX_SAFE_INTEGER) {
1162
1162
  return num;
1163
1163
  }
1164
1164
  }
1165
- return id2;
1165
+ return id;
1166
1166
  });
1167
1167
  }
1168
1168
  this.build = m[5] ? m[5].split(".") : [];
@@ -1883,7 +1883,7 @@ var require_range = __commonJS((exports, module) => {
1883
1883
  debug("stars", comp);
1884
1884
  return comp;
1885
1885
  };
1886
- var isX = (id2) => !id2 || id2.toLowerCase() === "x" || id2 === "*";
1886
+ var isX = (id) => !id || id.toLowerCase() === "x" || id === "*";
1887
1887
  var replaceTildes = (comp, options) => {
1888
1888
  return comp.trim().split(/\s+/).map((c) => replaceTilde(c, options)).join(" ");
1889
1889
  };
@@ -2049,20 +2049,20 @@ var require_range = __commonJS((exports, module) => {
2049
2049
  }
2050
2050
  return `${from} ${to}`.trim();
2051
2051
  };
2052
- var testSet = (set2, version, options) => {
2053
- for (let i = 0;i < set2.length; i++) {
2054
- if (!set2[i].test(version)) {
2052
+ var testSet = (set, version, options) => {
2053
+ for (let i = 0;i < set.length; i++) {
2054
+ if (!set[i].test(version)) {
2055
2055
  return false;
2056
2056
  }
2057
2057
  }
2058
2058
  if (version.prerelease.length && !options.includePrerelease) {
2059
- for (let i = 0;i < set2.length; i++) {
2060
- debug(set2[i].semver);
2061
- if (set2[i].semver === Comparator.ANY) {
2059
+ for (let i = 0;i < set.length; i++) {
2060
+ debug(set[i].semver);
2061
+ if (set[i].semver === Comparator.ANY) {
2062
2062
  continue;
2063
2063
  }
2064
- if (set2[i].semver.prerelease.length > 0) {
2065
- const allowed = set2[i].semver;
2064
+ if (set[i].semver.prerelease.length > 0) {
2065
+ const allowed = set[i].semver;
2066
2066
  if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) {
2067
2067
  return true;
2068
2068
  }
@@ -2421,7 +2421,7 @@ var require_simplify = __commonJS((exports, module) => {
2421
2421
  var satisfies = require_satisfies();
2422
2422
  var compare = require_compare();
2423
2423
  module.exports = (versions, range, options) => {
2424
- const set2 = [];
2424
+ const set = [];
2425
2425
  let first = null;
2426
2426
  let prev = null;
2427
2427
  const v = versions.sort((a, b) => compare(a, b, options));
@@ -2434,17 +2434,17 @@ var require_simplify = __commonJS((exports, module) => {
2434
2434
  }
2435
2435
  } else {
2436
2436
  if (prev) {
2437
- set2.push([first, prev]);
2437
+ set.push([first, prev]);
2438
2438
  }
2439
2439
  prev = null;
2440
2440
  first = null;
2441
2441
  }
2442
2442
  }
2443
2443
  if (first) {
2444
- set2.push([first, null]);
2444
+ set.push([first, null]);
2445
2445
  }
2446
2446
  const ranges = [];
2447
- for (const [min, max] of set2) {
2447
+ for (const [min, max] of set) {
2448
2448
  if (min === max) {
2449
2449
  ranges.push(min);
2450
2450
  } else if (!max && min === v[0]) {
@@ -3121,13 +3121,13 @@ var require_lodash = __commonJS((exports, module) => {
3121
3121
  return isObjectLike(value) && isArrayLike(value);
3122
3122
  }
3123
3123
  function isFunction(value) {
3124
- var tag = isObject2(value) ? objectToString.call(value) : "";
3124
+ var tag = isObject(value) ? objectToString.call(value) : "";
3125
3125
  return tag == funcTag || tag == genTag;
3126
3126
  }
3127
3127
  function isLength(value) {
3128
3128
  return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
3129
3129
  }
3130
- function isObject2(value) {
3130
+ function isObject(value) {
3131
3131
  var type = typeof value;
3132
3132
  return !!value && (type == "object" || type == "function");
3133
3133
  }
@@ -3162,9 +3162,9 @@ var require_lodash = __commonJS((exports, module) => {
3162
3162
  if (isSymbol(value)) {
3163
3163
  return NAN;
3164
3164
  }
3165
- if (isObject2(value)) {
3165
+ if (isObject(value)) {
3166
3166
  var other = typeof value.valueOf == "function" ? value.valueOf() : value;
3167
- value = isObject2(other) ? other + "" : other;
3167
+ value = isObject(other) ? other + "" : other;
3168
3168
  }
3169
3169
  if (typeof value != "string") {
3170
3170
  return value === 0 ? value : +value;
@@ -3212,7 +3212,7 @@ var require_lodash3 = __commonJS((exports, module) => {
3212
3212
  function isInteger(value) {
3213
3213
  return typeof value == "number" && value == toInteger(value);
3214
3214
  }
3215
- function isObject2(value) {
3215
+ function isObject(value) {
3216
3216
  var type = typeof value;
3217
3217
  return !!value && (type == "object" || type == "function");
3218
3218
  }
@@ -3244,9 +3244,9 @@ var require_lodash3 = __commonJS((exports, module) => {
3244
3244
  if (isSymbol(value)) {
3245
3245
  return NAN;
3246
3246
  }
3247
- if (isObject2(value)) {
3247
+ if (isObject(value)) {
3248
3248
  var other = typeof value.valueOf == "function" ? value.valueOf() : value;
3249
- value = isObject2(other) ? other + "" : other;
3249
+ value = isObject(other) ? other + "" : other;
3250
3250
  }
3251
3251
  if (typeof value != "string") {
3252
3252
  return value === 0 ? value : +value;
@@ -3361,7 +3361,7 @@ var require_lodash7 = __commonJS((exports, module) => {
3361
3361
  function once(func) {
3362
3362
  return before(2, func);
3363
3363
  }
3364
- function isObject2(value) {
3364
+ function isObject(value) {
3365
3365
  var type = typeof value;
3366
3366
  return !!value && (type == "object" || type == "function");
3367
3367
  }
@@ -3393,9 +3393,9 @@ var require_lodash7 = __commonJS((exports, module) => {
3393
3393
  if (isSymbol(value)) {
3394
3394
  return NAN;
3395
3395
  }
3396
- if (isObject2(value)) {
3396
+ if (isObject(value)) {
3397
3397
  var other = typeof value.valueOf == "function" ? value.valueOf() : value;
3398
- value = isObject2(other) ? other + "" : other;
3398
+ value = isObject(other) ? other + "" : other;
3399
3399
  }
3400
3400
  if (typeof value != "string") {
3401
3401
  return value === 0 ? value : +value;
@@ -3641,3192 +3641,13 @@ var require_jsonwebtoken = __commonJS((exports, module) => {
3641
3641
  };
3642
3642
  });
3643
3643
 
3644
- // ../../node_modules/mutative/dist/mutative.esm.mjs
3645
- var Operation = {
3646
- Remove: "remove",
3647
- Replace: "replace",
3648
- Add: "add"
3649
- };
3650
- var PROXY_DRAFT = Symbol.for("__MUTATIVE_PROXY_DRAFT__");
3651
- var RAW_RETURN_SYMBOL = Symbol("__MUTATIVE_RAW_RETURN_SYMBOL__");
3652
- var iteratorSymbol = Symbol.iterator;
3653
- var dataTypes = {
3654
- mutable: "mutable",
3655
- immutable: "immutable"
3656
- };
3657
- var internal = {};
3658
- function latest(proxyDraft) {
3659
- var _a;
3660
- return (_a = proxyDraft.copy) !== null && _a !== undefined ? _a : proxyDraft.original;
3661
- }
3662
- function isDraft(target) {
3663
- return !!getProxyDraft(target);
3664
- }
3665
- function getProxyDraft(value) {
3666
- if (typeof value !== "object")
3667
- return null;
3668
- return value === null || value === undefined ? undefined : value[PROXY_DRAFT];
3669
- }
3670
- function getValue(value) {
3671
- var _a;
3672
- const proxyDraft = getProxyDraft(value);
3673
- return proxyDraft ? (_a = proxyDraft.copy) !== null && _a !== undefined ? _a : proxyDraft.original : value;
3674
- }
3675
- function isDraftable(value, options) {
3676
- if (!value || typeof value !== "object")
3677
- return false;
3678
- let markResult;
3679
- return Object.getPrototypeOf(value) === Object.prototype || Array.isArray(value) || value instanceof Map || value instanceof Set || !!(options === null || options === undefined ? undefined : options.mark) && ((markResult = options.mark(value, dataTypes)) === dataTypes.immutable || typeof markResult === "function");
3680
- }
3681
- function getPath(target, path = []) {
3682
- if (Object.hasOwnProperty.call(target, "key")) {
3683
- const proxyDraft = getProxyDraft(get(target.parent.copy, target.key));
3684
- if (proxyDraft !== null && (proxyDraft === null || proxyDraft === undefined ? undefined : proxyDraft.original) !== target.original) {
3685
- return null;
3686
- }
3687
- path.push(target.parent.type === 3 ? Array.from(target.parent.setMap.keys()).indexOf(target.key) : target.key);
3688
- }
3689
- if (target.parent) {
3690
- return getPath(target.parent, path);
3691
- }
3692
- return path.reverse();
3693
- }
3694
- function getType(target) {
3695
- if (Array.isArray(target))
3696
- return 1;
3697
- if (target instanceof Map)
3698
- return 2;
3699
- if (target instanceof Set)
3700
- return 3;
3701
- return 0;
3702
- }
3703
- function get(target, key) {
3704
- return getType(target) === 2 ? target.get(key) : target[key];
3705
- }
3706
- function set(target, key, value) {
3707
- const type = getType(target);
3708
- if (type === 2) {
3709
- target.set(key, value);
3710
- } else {
3711
- target[key] = value;
3712
- }
3713
- }
3714
- function peek(target, key) {
3715
- const state = getProxyDraft(target);
3716
- const source = state ? latest(state) : target;
3717
- return source[key];
3718
- }
3719
- function isEqual(x, y) {
3720
- if (x === y) {
3721
- return x !== 0 || 1 / x === 1 / y;
3722
- } else {
3723
- return x !== x && y !== y;
3724
- }
3725
- }
3726
- function revokeProxy(proxyDraft) {
3727
- if (!proxyDraft)
3728
- return;
3729
- while (proxyDraft.finalities.revoke.length > 0) {
3730
- const revoke = proxyDraft.finalities.revoke.pop();
3731
- revoke();
3732
- }
3733
- }
3734
- function escapePath(path, pathAsArray) {
3735
- return pathAsArray ? path : [""].concat(path).map((_item) => {
3736
- const item = `${_item}`;
3737
- if (item.indexOf("/") === -1 && item.indexOf("~") === -1)
3738
- return item;
3739
- return item.replace(/~/g, "~0").replace(/\//g, "~1");
3740
- }).join("/");
3741
- }
3742
- function unescapePath(path) {
3743
- if (Array.isArray(path))
3744
- return path;
3745
- return path.split("/").map((_item) => _item.replace(/~1/g, "/").replace(/~0/g, "~")).slice(1);
3746
- }
3747
- function strictCopy(target) {
3748
- const copy = Object.create(Object.getPrototypeOf(target));
3749
- Reflect.ownKeys(target).forEach((key) => {
3750
- let desc = Reflect.getOwnPropertyDescriptor(target, key);
3751
- if (desc.enumerable && desc.configurable && desc.writable) {
3752
- copy[key] = target[key];
3753
- return;
3754
- }
3755
- if (!desc.writable) {
3756
- desc.writable = true;
3757
- desc.configurable = true;
3758
- }
3759
- if (desc.get || desc.set)
3760
- desc = {
3761
- configurable: true,
3762
- writable: true,
3763
- enumerable: desc.enumerable,
3764
- value: target[key]
3765
- };
3766
- Reflect.defineProperty(copy, key, desc);
3767
- });
3768
- return copy;
3769
- }
3770
- var propIsEnum = Object.prototype.propertyIsEnumerable;
3771
- function shallowCopy(original, options) {
3772
- let markResult;
3773
- if (Array.isArray(original)) {
3774
- return Array.prototype.concat.call(original);
3775
- } else if (original instanceof Set) {
3776
- return new Set(original.values());
3777
- } else if (original instanceof Map) {
3778
- return new Map(original);
3779
- } else if ((options === null || options === undefined ? undefined : options.mark) && (markResult = options.mark(original, dataTypes), markResult !== undefined) && markResult !== dataTypes.mutable) {
3780
- if (markResult === dataTypes.immutable) {
3781
- return strictCopy(original);
3782
- } else if (typeof markResult === "function") {
3783
- if (options.enablePatches || options.enableAutoFreeze) {
3784
- throw new Error(`You can't use mark and patches or auto freeze together.`);
3785
- }
3786
- return markResult();
3787
- }
3788
- throw new Error(`Unsupported mark result: ${markResult}`);
3789
- } else if (typeof original === "object" && Object.getPrototypeOf(original) === Object.prototype) {
3790
- const copy = {};
3791
- Object.keys(original).forEach((key) => {
3792
- copy[key] = original[key];
3793
- });
3794
- Object.getOwnPropertySymbols(original).forEach((key) => {
3795
- if (propIsEnum.call(original, key)) {
3796
- copy[key] = original[key];
3797
- }
3798
- });
3799
- return copy;
3800
- } else {
3801
- throw new Error(`Please check mark() to ensure that it is a stable marker draftable function.`);
3802
- }
3803
- }
3804
- function ensureShallowCopy(target) {
3805
- if (target.copy)
3806
- return;
3807
- target.copy = shallowCopy(target.original, target.options);
3808
- }
3809
- function deepClone(target) {
3810
- if (!isDraftable(target))
3811
- return getValue(target);
3812
- if (Array.isArray(target))
3813
- return target.map(deepClone);
3814
- if (target instanceof Map)
3815
- return new Map(Array.from(target.entries()).map(([k, v]) => [k, deepClone(v)]));
3816
- if (target instanceof Set)
3817
- return new Set(Array.from(target).map(deepClone));
3818
- const copy = Object.create(Object.getPrototypeOf(target));
3819
- for (const key in target)
3820
- copy[key] = deepClone(target[key]);
3821
- return copy;
3822
- }
3823
- function cloneIfNeeded(target) {
3824
- return isDraft(target) ? deepClone(target) : target;
3825
- }
3826
- function markChanged(proxyDraft) {
3827
- var _a;
3828
- proxyDraft.assignedMap = (_a = proxyDraft.assignedMap) !== null && _a !== undefined ? _a : new Map;
3829
- if (!proxyDraft.operated) {
3830
- proxyDraft.operated = true;
3831
- if (proxyDraft.parent) {
3832
- markChanged(proxyDraft.parent);
3833
- }
3834
- }
3835
- }
3836
- function throwFrozenError() {
3837
- throw new Error("Cannot modify frozen object");
3838
- }
3839
- function deepFreeze(target, subKey, updatedValues, stack, keys) {
3840
- {
3841
- updatedValues = updatedValues !== null && updatedValues !== undefined ? updatedValues : new WeakMap;
3842
- stack = stack !== null && stack !== undefined ? stack : [];
3843
- keys = keys !== null && keys !== undefined ? keys : [];
3844
- const value = updatedValues.has(target) ? updatedValues.get(target) : target;
3845
- if (stack.length > 0) {
3846
- const index = stack.indexOf(value);
3847
- if (value && typeof value === "object" && index !== -1) {
3848
- if (stack[0] === value) {
3849
- throw new Error(`Forbids circular reference`);
3850
- }
3851
- throw new Error(`Forbids circular reference: ~/${keys.slice(0, index).map((key, index2) => {
3852
- if (typeof key === "symbol")
3853
- return `[${key.toString()}]`;
3854
- const parent = stack[index2];
3855
- if (typeof key === "object" && (parent instanceof Map || parent instanceof Set))
3856
- return Array.from(parent.keys()).indexOf(key);
3857
- return key;
3858
- }).join("/")}`);
3859
- }
3860
- stack.push(value);
3861
- keys.push(subKey);
3862
- } else {
3863
- stack.push(value);
3864
- }
3865
- }
3866
- if (Object.isFrozen(target) || isDraft(target)) {
3867
- {
3868
- stack.pop();
3869
- keys.pop();
3870
- }
3871
- return;
3872
- }
3873
- const type = getType(target);
3874
- switch (type) {
3875
- case 2:
3876
- for (const [key, value] of target) {
3877
- deepFreeze(key, key, updatedValues, stack, keys);
3878
- deepFreeze(value, key, updatedValues, stack, keys);
3879
- }
3880
- target.set = target.clear = target.delete = throwFrozenError;
3881
- break;
3882
- case 3:
3883
- for (const value of target) {
3884
- deepFreeze(value, value, updatedValues, stack, keys);
3885
- }
3886
- target.add = target.clear = target.delete = throwFrozenError;
3887
- break;
3888
- case 1:
3889
- Object.freeze(target);
3890
- let index = 0;
3891
- for (const value of target) {
3892
- deepFreeze(value, index, updatedValues, stack, keys);
3893
- index += 1;
3894
- }
3895
- break;
3896
- default:
3897
- Object.freeze(target);
3898
- Object.keys(target).forEach((name) => {
3899
- const value = target[name];
3900
- deepFreeze(value, name, updatedValues, stack, keys);
3901
- });
3902
- }
3903
- {
3904
- stack.pop();
3905
- keys.pop();
3906
- }
3907
- }
3908
- function has(target, key) {
3909
- return target instanceof Map ? target.has(key) : Object.prototype.hasOwnProperty.call(target, key);
3910
- }
3911
- function getDescriptor(target, key) {
3912
- if (key in target) {
3913
- let prototype = Reflect.getPrototypeOf(target);
3914
- while (prototype) {
3915
- const descriptor = Reflect.getOwnPropertyDescriptor(prototype, key);
3916
- if (descriptor)
3917
- return descriptor;
3918
- prototype = Reflect.getPrototypeOf(prototype);
3919
- }
3920
- }
3921
- return;
3922
- }
3923
- function forEach(target, iter) {
3924
- const type = getType(target);
3925
- if (type === 0) {
3926
- Reflect.ownKeys(target).forEach((key) => {
3927
- iter(key, target[key], target);
3928
- });
3929
- } else if (type === 1) {
3930
- let index = 0;
3931
- for (const entry of target) {
3932
- iter(index, entry, target);
3933
- index += 1;
3934
- }
3935
- } else {
3936
- target.forEach((entry, index) => iter(index, entry, target));
3937
- }
3938
- }
3939
- function handleValue(target, handledSet, options) {
3940
- if (isDraft(target) || !isDraftable(target, options) || handledSet.has(target) || Object.isFrozen(target))
3941
- return;
3942
- const isSet = target instanceof Set;
3943
- const setMap = isSet ? new Map : undefined;
3944
- handledSet.add(target);
3945
- forEach(target, (key, value) => {
3946
- var _a;
3947
- if (isDraft(value)) {
3948
- const proxyDraft = getProxyDraft(value);
3949
- ensureShallowCopy(proxyDraft);
3950
- const updatedValue = ((_a = proxyDraft.assignedMap) === null || _a === undefined ? undefined : _a.size) || proxyDraft.operated ? proxyDraft.copy : proxyDraft.original;
3951
- set(isSet ? setMap : target, key, updatedValue);
3952
- } else {
3953
- handleValue(value, handledSet, options);
3954
- }
3955
- });
3956
- if (setMap) {
3957
- const set2 = target;
3958
- const values = Array.from(set2);
3959
- set2.clear();
3960
- values.forEach((value) => {
3961
- set2.add(setMap.has(value) ? setMap.get(value) : value);
3962
- });
3963
- }
3964
- }
3965
- function finalizeAssigned(proxyDraft, key) {
3966
- const copy = proxyDraft.type === 3 ? proxyDraft.setMap : proxyDraft.copy;
3967
- if (proxyDraft.finalities.revoke.length > 1 && proxyDraft.assignedMap.get(key) && copy) {
3968
- handleValue(get(copy, key), proxyDraft.finalities.handledSet, proxyDraft.options);
3969
- }
3970
- }
3971
- function finalizeSetValue(target) {
3972
- if (target.type === 3 && target.copy) {
3973
- target.copy.clear();
3974
- target.setMap.forEach((value) => {
3975
- target.copy.add(getValue(value));
3976
- });
3977
- }
3978
- }
3979
- function finalizePatches(target, generatePatches, patches, inversePatches) {
3980
- const shouldFinalize = target.operated && target.assignedMap && target.assignedMap.size > 0 && !target.finalized;
3981
- if (shouldFinalize) {
3982
- if (patches && inversePatches) {
3983
- const basePath = getPath(target);
3984
- if (basePath) {
3985
- generatePatches(target, basePath, patches, inversePatches);
3986
- }
3987
- }
3988
- target.finalized = true;
3989
- }
3990
- }
3991
- function markFinalization(target, key, value, generatePatches) {
3992
- const proxyDraft = getProxyDraft(value);
3993
- if (proxyDraft) {
3994
- if (!proxyDraft.callbacks) {
3995
- proxyDraft.callbacks = [];
3996
- }
3997
- proxyDraft.callbacks.push((patches, inversePatches) => {
3998
- var _a;
3999
- const copy = target.type === 3 ? target.setMap : target.copy;
4000
- if (isEqual(get(copy, key), value)) {
4001
- let updatedValue = proxyDraft.original;
4002
- if (proxyDraft.copy) {
4003
- updatedValue = proxyDraft.copy;
4004
- }
4005
- finalizeSetValue(target);
4006
- finalizePatches(target, generatePatches, patches, inversePatches);
4007
- if (target.options.enableAutoFreeze) {
4008
- target.options.updatedValues = (_a = target.options.updatedValues) !== null && _a !== undefined ? _a : new WeakMap;
4009
- target.options.updatedValues.set(updatedValue, proxyDraft.original);
4010
- }
4011
- set(copy, key, updatedValue);
4012
- }
4013
- });
4014
- if (target.options.enableAutoFreeze) {
4015
- if (proxyDraft.finalities !== target.finalities) {
4016
- target.options.enableAutoFreeze = false;
4017
- }
4018
- }
4019
- }
4020
- if (isDraftable(value, target.options)) {
4021
- target.finalities.draft.push(() => {
4022
- const copy = target.type === 3 ? target.setMap : target.copy;
4023
- if (isEqual(get(copy, key), value)) {
4024
- finalizeAssigned(target, key);
4025
- }
4026
- });
4027
- }
4028
- }
4029
- function generateArrayPatches(proxyState, basePath, patches, inversePatches, pathAsArray) {
4030
- let { original, assignedMap, options } = proxyState;
4031
- let copy = proxyState.copy;
4032
- if (copy.length < original.length) {
4033
- [original, copy] = [copy, original];
4034
- [patches, inversePatches] = [inversePatches, patches];
4035
- }
4036
- for (let index = 0;index < original.length; index += 1) {
4037
- if (assignedMap.get(index.toString()) && copy[index] !== original[index]) {
4038
- const _path = basePath.concat([index]);
4039
- const path = escapePath(_path, pathAsArray);
4040
- patches.push({
4041
- op: Operation.Replace,
4042
- path,
4043
- value: cloneIfNeeded(copy[index])
4044
- });
4045
- inversePatches.push({
4046
- op: Operation.Replace,
4047
- path,
4048
- value: cloneIfNeeded(original[index])
4049
- });
4050
- }
4051
- }
4052
- for (let index = original.length;index < copy.length; index += 1) {
4053
- const _path = basePath.concat([index]);
4054
- const path = escapePath(_path, pathAsArray);
4055
- patches.push({
4056
- op: Operation.Add,
4057
- path,
4058
- value: cloneIfNeeded(copy[index])
4059
- });
4060
- }
4061
- if (original.length < copy.length) {
4062
- const { arrayLengthAssignment = true } = options.enablePatches;
4063
- if (arrayLengthAssignment) {
4064
- const _path = basePath.concat(["length"]);
4065
- const path = escapePath(_path, pathAsArray);
4066
- inversePatches.push({
4067
- op: Operation.Replace,
4068
- path,
4069
- value: original.length
4070
- });
4071
- } else {
4072
- for (let index = copy.length;original.length < index; index -= 1) {
4073
- const _path = basePath.concat([index - 1]);
4074
- const path = escapePath(_path, pathAsArray);
4075
- inversePatches.push({
4076
- op: Operation.Remove,
4077
- path
4078
- });
4079
- }
4080
- }
4081
- }
4082
- }
4083
- function generatePatchesFromAssigned({ original, copy, assignedMap }, basePath, patches, inversePatches, pathAsArray) {
4084
- assignedMap.forEach((assignedValue, key) => {
4085
- const originalValue = get(original, key);
4086
- const value = cloneIfNeeded(get(copy, key));
4087
- const op = !assignedValue ? Operation.Remove : has(original, key) ? Operation.Replace : Operation.Add;
4088
- if (isEqual(originalValue, value) && op === Operation.Replace)
4089
- return;
4090
- const _path = basePath.concat(key);
4091
- const path = escapePath(_path, pathAsArray);
4092
- patches.push(op === Operation.Remove ? { op, path } : { op, path, value });
4093
- inversePatches.push(op === Operation.Add ? { op: Operation.Remove, path } : op === Operation.Remove ? { op: Operation.Add, path, value: originalValue } : { op: Operation.Replace, path, value: originalValue });
4094
- });
4095
- }
4096
- function generateSetPatches({ original, copy }, basePath, patches, inversePatches, pathAsArray) {
4097
- let index = 0;
4098
- original.forEach((value) => {
4099
- if (!copy.has(value)) {
4100
- const _path = basePath.concat([index]);
4101
- const path = escapePath(_path, pathAsArray);
4102
- patches.push({
4103
- op: Operation.Remove,
4104
- path,
4105
- value
4106
- });
4107
- inversePatches.unshift({
4108
- op: Operation.Add,
4109
- path,
4110
- value
4111
- });
4112
- }
4113
- index += 1;
4114
- });
4115
- index = 0;
4116
- copy.forEach((value) => {
4117
- if (!original.has(value)) {
4118
- const _path = basePath.concat([index]);
4119
- const path = escapePath(_path, pathAsArray);
4120
- patches.push({
4121
- op: Operation.Add,
4122
- path,
4123
- value
4124
- });
4125
- inversePatches.unshift({
4126
- op: Operation.Remove,
4127
- path,
4128
- value
4129
- });
4130
- }
4131
- index += 1;
4132
- });
4133
- }
4134
- function generatePatches(proxyState, basePath, patches, inversePatches) {
4135
- const { pathAsArray = true } = proxyState.options.enablePatches;
4136
- switch (proxyState.type) {
4137
- case 0:
4138
- case 2:
4139
- return generatePatchesFromAssigned(proxyState, basePath, patches, inversePatches, pathAsArray);
4140
- case 1:
4141
- return generateArrayPatches(proxyState, basePath, patches, inversePatches, pathAsArray);
4142
- case 3:
4143
- return generateSetPatches(proxyState, basePath, patches, inversePatches, pathAsArray);
4144
- }
4145
- }
4146
- var readable = false;
4147
- var checkReadable = (value, options, ignoreCheckDraftable = false) => {
4148
- if (typeof value === "object" && value !== null && (!isDraftable(value, options) || ignoreCheckDraftable) && !readable) {
4149
- throw new Error(`Strict mode: Mutable data cannot be accessed directly, please use 'unsafe(callback)' wrap.`);
4150
- }
4151
- };
4152
- var mapHandler = {
4153
- get size() {
4154
- const current = latest(getProxyDraft(this));
4155
- return current.size;
4156
- },
4157
- has(key) {
4158
- return latest(getProxyDraft(this)).has(key);
4159
- },
4160
- set(key, value) {
4161
- const target = getProxyDraft(this);
4162
- const source = latest(target);
4163
- if (!source.has(key) || !isEqual(source.get(key), value)) {
4164
- ensureShallowCopy(target);
4165
- markChanged(target);
4166
- target.assignedMap.set(key, true);
4167
- target.copy.set(key, value);
4168
- markFinalization(target, key, value, generatePatches);
4169
- }
4170
- return this;
4171
- },
4172
- delete(key) {
4173
- if (!this.has(key)) {
4174
- return false;
4175
- }
4176
- const target = getProxyDraft(this);
4177
- ensureShallowCopy(target);
4178
- markChanged(target);
4179
- if (target.original.has(key)) {
4180
- target.assignedMap.set(key, false);
4181
- } else {
4182
- target.assignedMap.delete(key);
4183
- }
4184
- target.copy.delete(key);
4185
- return true;
4186
- },
4187
- clear() {
4188
- const target = getProxyDraft(this);
4189
- if (!this.size)
4190
- return;
4191
- ensureShallowCopy(target);
4192
- markChanged(target);
4193
- target.assignedMap = new Map;
4194
- for (const [key] of target.original) {
4195
- target.assignedMap.set(key, false);
4196
- }
4197
- target.copy.clear();
4198
- },
4199
- forEach(callback, thisArg) {
4200
- const target = getProxyDraft(this);
4201
- latest(target).forEach((_value, _key) => {
4202
- callback.call(thisArg, this.get(_key), _key, this);
4203
- });
4204
- },
4205
- get(key) {
4206
- var _a, _b;
4207
- const target = getProxyDraft(this);
4208
- const value = latest(target).get(key);
4209
- const mutable = ((_b = (_a = target.options).mark) === null || _b === undefined ? undefined : _b.call(_a, value, dataTypes)) === dataTypes.mutable;
4210
- if (target.options.strict) {
4211
- checkReadable(value, target.options, mutable);
4212
- }
4213
- if (mutable) {
4214
- return value;
4215
- }
4216
- if (target.finalized || !isDraftable(value, target.options)) {
4217
- return value;
4218
- }
4219
- if (value !== target.original.get(key)) {
4220
- return value;
4221
- }
4222
- const draft = internal.createDraft({
4223
- original: value,
4224
- parentDraft: target,
4225
- key,
4226
- finalities: target.finalities,
4227
- options: target.options
4228
- });
4229
- ensureShallowCopy(target);
4230
- target.copy.set(key, draft);
4231
- return draft;
4232
- },
4233
- keys() {
4234
- return latest(getProxyDraft(this)).keys();
4235
- },
4236
- values() {
4237
- const iterator = this.keys();
4238
- return {
4239
- [iteratorSymbol]: () => this.values(),
4240
- next: () => {
4241
- const result = iterator.next();
4242
- if (result.done)
4243
- return result;
4244
- const value = this.get(result.value);
4245
- return {
4246
- done: false,
4247
- value
4248
- };
4249
- }
4250
- };
4251
- },
4252
- entries() {
4253
- const iterator = this.keys();
4254
- return {
4255
- [iteratorSymbol]: () => this.entries(),
4256
- next: () => {
4257
- const result = iterator.next();
4258
- if (result.done)
4259
- return result;
4260
- const value = this.get(result.value);
4261
- return {
4262
- done: false,
4263
- value: [result.value, value]
4264
- };
4265
- }
4266
- };
4267
- },
4268
- [iteratorSymbol]() {
4269
- return this.entries();
4270
- }
4271
- };
4272
- var mapHandlerKeys = Reflect.ownKeys(mapHandler);
4273
- var getNextIterator = (target, iterator, { isValuesIterator }) => () => {
4274
- var _a, _b;
4275
- const result = iterator.next();
4276
- if (result.done)
4277
- return result;
4278
- const key = result.value;
4279
- let value = target.setMap.get(key);
4280
- const currentDraft = getProxyDraft(value);
4281
- const mutable = ((_b = (_a = target.options).mark) === null || _b === undefined ? undefined : _b.call(_a, value, dataTypes)) === dataTypes.mutable;
4282
- if (target.options.strict) {
4283
- checkReadable(key, target.options, mutable);
4284
- }
4285
- if (!mutable && !currentDraft && isDraftable(key, target.options) && !target.finalized && target.original.has(key)) {
4286
- const proxy = internal.createDraft({
4287
- original: key,
4288
- parentDraft: target,
4289
- key,
4290
- finalities: target.finalities,
4291
- options: target.options
4292
- });
4293
- target.setMap.set(key, proxy);
4294
- value = proxy;
4295
- } else if (currentDraft) {
4296
- value = currentDraft.proxy;
4297
- }
4298
- return {
4299
- done: false,
4300
- value: isValuesIterator ? value : [value, value]
4301
- };
4302
- };
4303
- var setHandler = {
4304
- get size() {
4305
- const target = getProxyDraft(this);
4306
- return target.setMap.size;
4307
- },
4308
- has(value) {
4309
- const target = getProxyDraft(this);
4310
- if (target.setMap.has(value))
4311
- return true;
4312
- ensureShallowCopy(target);
4313
- const valueProxyDraft = getProxyDraft(value);
4314
- if (valueProxyDraft && target.setMap.has(valueProxyDraft.original))
4315
- return true;
4316
- return false;
4317
- },
4318
- add(value) {
4319
- const target = getProxyDraft(this);
4320
- if (!this.has(value)) {
4321
- ensureShallowCopy(target);
4322
- markChanged(target);
4323
- target.assignedMap.set(value, true);
4324
- target.setMap.set(value, value);
4325
- markFinalization(target, value, value, generatePatches);
4326
- }
4327
- return this;
4328
- },
4329
- delete(value) {
4330
- if (!this.has(value)) {
4331
- return false;
4332
- }
4333
- const target = getProxyDraft(this);
4334
- ensureShallowCopy(target);
4335
- markChanged(target);
4336
- const valueProxyDraft = getProxyDraft(value);
4337
- if (valueProxyDraft && target.setMap.has(valueProxyDraft.original)) {
4338
- target.assignedMap.set(valueProxyDraft.original, false);
4339
- return target.setMap.delete(valueProxyDraft.original);
4340
- }
4341
- if (!valueProxyDraft && target.setMap.has(value)) {
4342
- target.assignedMap.set(value, false);
4343
- } else {
4344
- target.assignedMap.delete(value);
4345
- }
4346
- return target.setMap.delete(value);
4347
- },
4348
- clear() {
4349
- if (!this.size)
4350
- return;
4351
- const target = getProxyDraft(this);
4352
- ensureShallowCopy(target);
4353
- markChanged(target);
4354
- for (const value of target.original) {
4355
- target.assignedMap.set(value, false);
4356
- }
4357
- target.setMap.clear();
4358
- },
4359
- values() {
4360
- const target = getProxyDraft(this);
4361
- ensureShallowCopy(target);
4362
- const iterator = target.setMap.keys();
4363
- return {
4364
- [Symbol.iterator]: () => this.values(),
4365
- next: getNextIterator(target, iterator, { isValuesIterator: true })
4366
- };
4367
- },
4368
- entries() {
4369
- const target = getProxyDraft(this);
4370
- ensureShallowCopy(target);
4371
- const iterator = target.setMap.keys();
4372
- return {
4373
- [Symbol.iterator]: () => this.entries(),
4374
- next: getNextIterator(target, iterator, {
4375
- isValuesIterator: false
4376
- })
4377
- };
4378
- },
4379
- keys() {
4380
- return this.values();
4381
- },
4382
- [iteratorSymbol]() {
4383
- return this.values();
4384
- },
4385
- forEach(callback, thisArg) {
4386
- const iterator = this.values();
4387
- let result = iterator.next();
4388
- while (!result.done) {
4389
- callback.call(thisArg, result.value, result.value, this);
4390
- result = iterator.next();
4391
- }
4392
- }
4393
- };
4394
- var setHandlerKeys = Reflect.ownKeys(setHandler);
4395
- var draftsCache = new WeakSet;
4396
- var proxyHandler = {
4397
- get(target, key, receiver) {
4398
- var _a, _b;
4399
- const copy = (_a = target.copy) === null || _a === undefined ? undefined : _a[key];
4400
- if (copy && draftsCache.has(copy)) {
4401
- return copy;
4402
- }
4403
- if (key === PROXY_DRAFT)
4404
- return target;
4405
- let markResult;
4406
- if (target.options.mark) {
4407
- const value2 = key === "size" && (target.original instanceof Map || target.original instanceof Set) ? Reflect.get(target.original, key) : Reflect.get(target.original, key, receiver);
4408
- markResult = target.options.mark(value2, dataTypes);
4409
- if (markResult === dataTypes.mutable) {
4410
- if (target.options.strict) {
4411
- checkReadable(value2, target.options, true);
4412
- }
4413
- return value2;
4414
- }
4415
- }
4416
- const source = latest(target);
4417
- if (source instanceof Map && mapHandlerKeys.includes(key)) {
4418
- if (key === "size") {
4419
- return Object.getOwnPropertyDescriptor(mapHandler, "size").get.call(target.proxy);
4420
- }
4421
- const handle = mapHandler[key];
4422
- if (handle) {
4423
- return handle.bind(target.proxy);
4424
- }
4425
- }
4426
- if (source instanceof Set && setHandlerKeys.includes(key)) {
4427
- if (key === "size") {
4428
- return Object.getOwnPropertyDescriptor(setHandler, "size").get.call(target.proxy);
4429
- }
4430
- const handle = setHandler[key];
4431
- if (handle) {
4432
- return handle.bind(target.proxy);
4433
- }
4434
- }
4435
- if (!has(source, key)) {
4436
- const desc = getDescriptor(source, key);
4437
- return desc ? `value` in desc ? desc.value : (_b = desc.get) === null || _b === undefined ? undefined : _b.call(target.proxy) : undefined;
4438
- }
4439
- const value = source[key];
4440
- if (target.options.strict) {
4441
- checkReadable(value, target.options);
4442
- }
4443
- if (target.finalized || !isDraftable(value, target.options)) {
4444
- return value;
4445
- }
4446
- if (value === peek(target.original, key)) {
4447
- ensureShallowCopy(target);
4448
- target.copy[key] = createDraft({
4449
- original: target.original[key],
4450
- parentDraft: target,
4451
- key: target.type === 1 ? Number(key) : key,
4452
- finalities: target.finalities,
4453
- options: target.options
4454
- });
4455
- if (typeof markResult === "function") {
4456
- const subProxyDraft = getProxyDraft(target.copy[key]);
4457
- ensureShallowCopy(subProxyDraft);
4458
- markChanged(subProxyDraft);
4459
- return subProxyDraft.copy;
4460
- }
4461
- return target.copy[key];
4462
- }
4463
- return value;
4464
- },
4465
- set(target, key, value) {
4466
- var _a;
4467
- if (target.type === 3 || target.type === 2) {
4468
- throw new Error(`Map/Set draft does not support any property assignment.`);
4469
- }
4470
- let _key;
4471
- if (target.type === 1 && key !== "length" && !(Number.isInteger(_key = Number(key)) && _key >= 0 && (key === 0 || _key === 0 || String(_key) === String(key)))) {
4472
- throw new Error(`Only supports setting array indices and the 'length' property.`);
4473
- }
4474
- const desc = getDescriptor(latest(target), key);
4475
- if (desc === null || desc === undefined ? undefined : desc.set) {
4476
- desc.set.call(target.proxy, value);
4477
- return true;
4478
- }
4479
- const current = peek(latest(target), key);
4480
- const currentProxyDraft = getProxyDraft(current);
4481
- if (currentProxyDraft && isEqual(currentProxyDraft.original, value)) {
4482
- target.copy[key] = value;
4483
- target.assignedMap = (_a = target.assignedMap) !== null && _a !== undefined ? _a : new Map;
4484
- target.assignedMap.set(key, false);
4485
- return true;
4486
- }
4487
- if (isEqual(value, current) && (value !== undefined || has(target.original, key)))
4488
- return true;
4489
- ensureShallowCopy(target);
4490
- markChanged(target);
4491
- if (has(target.original, key) && isEqual(value, target.original[key])) {
4492
- target.assignedMap.delete(key);
4493
- } else {
4494
- target.assignedMap.set(key, true);
4495
- }
4496
- target.copy[key] = value;
4497
- markFinalization(target, key, value, generatePatches);
4498
- return true;
4499
- },
4500
- has(target, key) {
4501
- return key in latest(target);
4502
- },
4503
- ownKeys(target) {
4504
- return Reflect.ownKeys(latest(target));
4505
- },
4506
- getOwnPropertyDescriptor(target, key) {
4507
- const source = latest(target);
4508
- const descriptor = Reflect.getOwnPropertyDescriptor(source, key);
4509
- if (!descriptor)
4510
- return descriptor;
4511
- return {
4512
- writable: true,
4513
- configurable: target.type !== 1 || key !== "length",
4514
- enumerable: descriptor.enumerable,
4515
- value: source[key]
4516
- };
4517
- },
4518
- getPrototypeOf(target) {
4519
- return Reflect.getPrototypeOf(target.original);
4520
- },
4521
- setPrototypeOf() {
4522
- throw new Error(`Cannot call 'setPrototypeOf()' on drafts`);
4523
- },
4524
- defineProperty() {
4525
- throw new Error(`Cannot call 'defineProperty()' on drafts`);
4526
- },
4527
- deleteProperty(target, key) {
4528
- var _a;
4529
- if (target.type === 1) {
4530
- return proxyHandler.set.call(this, target, key, undefined, target.proxy);
4531
- }
4532
- if (peek(target.original, key) !== undefined || key in target.original) {
4533
- ensureShallowCopy(target);
4534
- markChanged(target);
4535
- target.assignedMap.set(key, false);
4536
- } else {
4537
- target.assignedMap = (_a = target.assignedMap) !== null && _a !== undefined ? _a : new Map;
4538
- target.assignedMap.delete(key);
4539
- }
4540
- if (target.copy)
4541
- delete target.copy[key];
4542
- return true;
4543
- }
4544
- };
4545
- function createDraft(createDraftOptions) {
4546
- const { original, parentDraft, key, finalities, options } = createDraftOptions;
4547
- const type = getType(original);
4548
- const proxyDraft = {
4549
- type,
4550
- finalized: false,
4551
- parent: parentDraft,
4552
- original,
4553
- copy: null,
4554
- proxy: null,
4555
- finalities,
4556
- options,
4557
- setMap: type === 3 ? new Map(original.entries()) : undefined
4558
- };
4559
- if (key || "key" in createDraftOptions) {
4560
- proxyDraft.key = key;
4561
- }
4562
- const { proxy, revoke } = Proxy.revocable(type === 1 ? Object.assign([], proxyDraft) : proxyDraft, proxyHandler);
4563
- finalities.revoke.push(revoke);
4564
- draftsCache.add(proxy);
4565
- proxyDraft.proxy = proxy;
4566
- if (parentDraft) {
4567
- const target = parentDraft;
4568
- target.finalities.draft.push((patches, inversePatches) => {
4569
- var _a, _b;
4570
- const oldProxyDraft = getProxyDraft(proxy);
4571
- let copy = target.type === 3 ? target.setMap : target.copy;
4572
- const draft = get(copy, key);
4573
- const proxyDraft2 = getProxyDraft(draft);
4574
- if (proxyDraft2) {
4575
- let updatedValue = proxyDraft2.original;
4576
- if (proxyDraft2.operated) {
4577
- updatedValue = getValue(draft);
4578
- }
4579
- finalizeSetValue(proxyDraft2);
4580
- finalizePatches(proxyDraft2, generatePatches, patches, inversePatches);
4581
- if (target.options.enableAutoFreeze) {
4582
- target.options.updatedValues = (_a = target.options.updatedValues) !== null && _a !== undefined ? _a : new WeakMap;
4583
- target.options.updatedValues.set(updatedValue, proxyDraft2.original);
4584
- }
4585
- set(copy, key, updatedValue);
4586
- }
4587
- (_b = oldProxyDraft.callbacks) === null || _b === undefined || _b.forEach((callback) => {
4588
- callback(patches, inversePatches);
4589
- });
4590
- });
4591
- } else {
4592
- const target = getProxyDraft(proxy);
4593
- target.finalities.draft.push((patches, inversePatches) => {
4594
- finalizeSetValue(target);
4595
- finalizePatches(target, generatePatches, patches, inversePatches);
4596
- });
4597
- }
4598
- return proxy;
4599
- }
4600
- internal.createDraft = createDraft;
4601
- function finalizeDraft(result, returnedValue, patches, inversePatches, enableAutoFreeze) {
4602
- var _a;
4603
- const proxyDraft = getProxyDraft(result);
4604
- const original = (_a = proxyDraft === null || proxyDraft === undefined ? undefined : proxyDraft.original) !== null && _a !== undefined ? _a : result;
4605
- const hasReturnedValue = !!returnedValue.length;
4606
- if (proxyDraft === null || proxyDraft === undefined ? undefined : proxyDraft.operated) {
4607
- while (proxyDraft.finalities.draft.length > 0) {
4608
- const finalize = proxyDraft.finalities.draft.pop();
4609
- finalize(patches, inversePatches);
4610
- }
4611
- }
4612
- const state = hasReturnedValue ? returnedValue[0] : proxyDraft ? proxyDraft.operated ? proxyDraft.copy : proxyDraft.original : result;
4613
- if (proxyDraft)
4614
- revokeProxy(proxyDraft);
4615
- if (enableAutoFreeze) {
4616
- deepFreeze(state, state, proxyDraft === null || proxyDraft === undefined ? undefined : proxyDraft.options.updatedValues);
4617
- }
4618
- return [
4619
- state,
4620
- patches && hasReturnedValue ? [{ op: Operation.Replace, path: [], value: returnedValue[0] }] : patches,
4621
- inversePatches && hasReturnedValue ? [{ op: Operation.Replace, path: [], value: original }] : inversePatches
4622
- ];
4623
- }
4624
- function draftify(baseState, options) {
4625
- var _a;
4626
- const finalities = {
4627
- draft: [],
4628
- revoke: [],
4629
- handledSet: new WeakSet
4630
- };
4631
- let patches;
4632
- let inversePatches;
4633
- if (options.enablePatches) {
4634
- patches = [];
4635
- inversePatches = [];
4636
- }
4637
- const isMutable = ((_a = options.mark) === null || _a === undefined ? undefined : _a.call(options, baseState, dataTypes)) === dataTypes.mutable || !isDraftable(baseState, options);
4638
- const draft = isMutable ? baseState : createDraft({
4639
- original: baseState,
4640
- parentDraft: null,
4641
- finalities,
4642
- options
4643
- });
4644
- return [
4645
- draft,
4646
- (returnedValue = []) => {
4647
- const [finalizedState, finalizedPatches, finalizedInversePatches] = finalizeDraft(draft, returnedValue, patches, inversePatches, options.enableAutoFreeze);
4648
- return options.enablePatches ? [finalizedState, finalizedPatches, finalizedInversePatches] : finalizedState;
4649
- }
4650
- ];
4651
- }
4652
- function handleReturnValue(options) {
4653
- const { rootDraft, value, useRawReturn = false, isRoot = true } = options;
4654
- forEach(value, (key, item, source) => {
4655
- const proxyDraft = getProxyDraft(item);
4656
- if (proxyDraft && rootDraft && proxyDraft.finalities === rootDraft.finalities) {
4657
- options.isContainDraft = true;
4658
- const currentValue = proxyDraft.original;
4659
- if (source instanceof Set) {
4660
- const arr = Array.from(source);
4661
- source.clear();
4662
- arr.forEach((_item) => source.add(key === _item ? currentValue : _item));
4663
- } else {
4664
- set(source, key, currentValue);
4665
- }
4666
- } else if (typeof item === "object" && item !== null) {
4667
- options.value = item;
4668
- options.isRoot = false;
4669
- handleReturnValue(options);
4670
- }
4671
- });
4672
- if (isRoot) {
4673
- if (!options.isContainDraft)
4674
- console.warn(`The return value does not contain any draft, please use 'rawReturn()' to wrap the return value to improve performance.`);
4675
- if (useRawReturn) {
4676
- console.warn(`The return value contains drafts, please don't use 'rawReturn()' to wrap the return value.`);
4677
- }
4678
- }
4679
- }
4680
- function getCurrent(target) {
4681
- const proxyDraft = getProxyDraft(target);
4682
- if (!isDraftable(target, proxyDraft === null || proxyDraft === undefined ? undefined : proxyDraft.options))
4683
- return target;
4684
- const type = getType(target);
4685
- if (proxyDraft && !proxyDraft.operated)
4686
- return proxyDraft.original;
4687
- let currentValue;
4688
- function ensureShallowCopy2() {
4689
- currentValue = type === 2 ? new Map(target) : type === 3 ? Array.from(proxyDraft.setMap.values()) : shallowCopy(target, proxyDraft === null || proxyDraft === undefined ? undefined : proxyDraft.options);
4690
- }
4691
- if (proxyDraft) {
4692
- proxyDraft.finalized = true;
4693
- try {
4694
- ensureShallowCopy2();
4695
- } finally {
4696
- proxyDraft.finalized = false;
4697
- }
4698
- } else {
4699
- currentValue = target;
4700
- }
4701
- forEach(currentValue, (key, value) => {
4702
- if (proxyDraft && isEqual(get(proxyDraft.original, key), value))
4703
- return;
4704
- const newValue = getCurrent(value);
4705
- if (newValue !== value) {
4706
- if (currentValue === target)
4707
- ensureShallowCopy2();
4708
- set(currentValue, key, newValue);
4709
- }
4710
- });
4711
- return type === 3 ? new Set(currentValue) : currentValue;
4712
- }
4713
- function current(target) {
4714
- if (!isDraft(target)) {
4715
- throw new Error(`current() is only used for Draft, parameter: ${target}`);
4716
- }
4717
- return getCurrent(target);
4718
- }
4719
- var makeCreator = (arg) => {
4720
- if (arg !== undefined && Object.prototype.toString.call(arg) !== "[object Object]") {
4721
- throw new Error(`Invalid options: ${String(arg)}, 'options' should be an object.`);
4722
- }
4723
- return function create(arg0, arg1, arg2) {
4724
- var _a, _b, _c;
4725
- if (typeof arg0 === "function" && typeof arg1 !== "function") {
4726
- return function(base2, ...args) {
4727
- return create(base2, (draft2) => arg0.call(this, draft2, ...args), arg1);
4728
- };
4729
- }
4730
- const base = arg0;
4731
- const mutate = arg1;
4732
- let options = arg2;
4733
- if (typeof arg1 !== "function") {
4734
- options = arg1;
4735
- }
4736
- if (options !== undefined && Object.prototype.toString.call(options) !== "[object Object]") {
4737
- throw new Error(`Invalid options: ${options}, 'options' should be an object.`);
4738
- }
4739
- options = Object.assign(Object.assign({}, arg), options);
4740
- const state = isDraft(base) ? current(base) : base;
4741
- const mark = Array.isArray(options.mark) ? (value, types) => {
4742
- for (const mark2 of options.mark) {
4743
- if (typeof mark2 !== "function") {
4744
- throw new Error(`Invalid mark: ${mark2}, 'mark' should be a function.`);
4745
- }
4746
- const result2 = mark2(value, types);
4747
- if (result2) {
4748
- return result2;
4749
- }
4750
- }
4751
- return;
4752
- } : options.mark;
4753
- const enablePatches = (_a = options.enablePatches) !== null && _a !== undefined ? _a : false;
4754
- const strict = (_b = options.strict) !== null && _b !== undefined ? _b : false;
4755
- const enableAutoFreeze = (_c = options.enableAutoFreeze) !== null && _c !== undefined ? _c : false;
4756
- const _options = {
4757
- enableAutoFreeze,
4758
- mark,
4759
- strict,
4760
- enablePatches
4761
- };
4762
- if (!isDraftable(state, _options) && typeof state === "object" && state !== null) {
4763
- throw new Error(`Invalid base state: create() only supports plain objects, arrays, Set, Map or using mark() to mark the state as immutable.`);
4764
- }
4765
- const [draft, finalize] = draftify(state, _options);
4766
- if (typeof arg1 !== "function") {
4767
- if (!isDraftable(state, _options)) {
4768
- throw new Error(`Invalid base state: create() only supports plain objects, arrays, Set, Map or using mark() to mark the state as immutable.`);
4769
- }
4770
- return [draft, finalize];
4771
- }
4772
- let result;
4773
- try {
4774
- result = mutate(draft);
4775
- } catch (error) {
4776
- revokeProxy(getProxyDraft(draft));
4777
- throw error;
4778
- }
4779
- const returnValue = (value) => {
4780
- const proxyDraft = getProxyDraft(draft);
4781
- if (!isDraft(value)) {
4782
- if (value !== undefined && !isEqual(value, draft) && (proxyDraft === null || proxyDraft === undefined ? undefined : proxyDraft.operated)) {
4783
- throw new Error(`Either the value is returned as a new non-draft value, or only the draft is modified without returning any value.`);
4784
- }
4785
- const rawReturnValue = value === null || value === undefined ? undefined : value[RAW_RETURN_SYMBOL];
4786
- if (rawReturnValue) {
4787
- const _value = rawReturnValue[0];
4788
- if (_options.strict && typeof value === "object" && value !== null) {
4789
- handleReturnValue({
4790
- rootDraft: proxyDraft,
4791
- value,
4792
- useRawReturn: true
4793
- });
4794
- }
4795
- return finalize([_value]);
4796
- }
4797
- if (value !== undefined) {
4798
- if (typeof value === "object" && value !== null) {
4799
- handleReturnValue({ rootDraft: proxyDraft, value });
4800
- }
4801
- return finalize([value]);
4802
- }
4803
- }
4804
- if (value === draft || value === undefined) {
4805
- return finalize([]);
4806
- }
4807
- const returnedProxyDraft = getProxyDraft(value);
4808
- if (_options === returnedProxyDraft.options) {
4809
- if (returnedProxyDraft.operated) {
4810
- throw new Error(`Cannot return a modified child draft.`);
4811
- }
4812
- return finalize([current(value)]);
4813
- }
4814
- return finalize([value]);
4815
- };
4816
- if (result instanceof Promise) {
4817
- return result.then(returnValue, (error) => {
4818
- revokeProxy(getProxyDraft(draft));
4819
- throw error;
4820
- });
4821
- }
4822
- return returnValue(result);
4823
- };
4824
- };
4825
- var create = makeCreator();
4826
- function apply(state, patches, applyOptions) {
4827
- let i;
4828
- for (i = patches.length - 1;i >= 0; i -= 1) {
4829
- const { value, op, path } = patches[i];
4830
- if (!path.length && op === Operation.Replace || path === "" && op === Operation.Add) {
4831
- state = value;
4832
- break;
4833
- }
4834
- }
4835
- if (i > -1) {
4836
- patches = patches.slice(i + 1);
4837
- }
4838
- const mutate = (draft) => {
4839
- patches.forEach((patch) => {
4840
- const { path: _path, op } = patch;
4841
- const path = unescapePath(_path);
4842
- let base = draft;
4843
- for (let index = 0;index < path.length - 1; index += 1) {
4844
- const parentType = getType(base);
4845
- let key2 = path[index];
4846
- if (typeof key2 !== "string" && typeof key2 !== "number") {
4847
- key2 = String(key2);
4848
- }
4849
- if ((parentType === 0 || parentType === 1) && (key2 === "__proto__" || key2 === "constructor") || typeof base === "function" && key2 === "prototype") {
4850
- throw new Error(`Patching reserved attributes like __proto__ and constructor is not allowed.`);
4851
- }
4852
- base = get(getType(base) === 3 ? Array.from(base) : base, key2);
4853
- if (typeof base !== "object") {
4854
- throw new Error(`Cannot apply patch at '${path.join("/")}'.`);
4855
- }
4856
- }
4857
- const type = getType(base);
4858
- const value = deepClone(patch.value);
4859
- const key = path[path.length - 1];
4860
- switch (op) {
4861
- case Operation.Replace:
4862
- switch (type) {
4863
- case 2:
4864
- return base.set(key, value);
4865
- case 3:
4866
- throw new Error(`Cannot apply replace patch to set.`);
4867
- default:
4868
- return base[key] = value;
4869
- }
4870
- case Operation.Add:
4871
- switch (type) {
4872
- case 1:
4873
- return key === "-" ? base.push(value) : base.splice(key, 0, value);
4874
- case 2:
4875
- return base.set(key, value);
4876
- case 3:
4877
- return base.add(value);
4878
- default:
4879
- return base[key] = value;
4880
- }
4881
- case Operation.Remove:
4882
- switch (type) {
4883
- case 1:
4884
- return base.splice(key, 1);
4885
- case 2:
4886
- return base.delete(key);
4887
- case 3:
4888
- return base.delete(patch.value);
4889
- default:
4890
- return delete base[key];
4891
- }
4892
- default:
4893
- throw new Error(`Unsupported patch operation: ${op}.`);
4894
- }
4895
- });
4896
- };
4897
- if (isDraft(state)) {
4898
- if (applyOptions !== undefined) {
4899
- throw new Error(`Cannot apply patches with options to a draft.`);
4900
- }
4901
- mutate(state);
4902
- return state;
4903
- }
4904
- return create(state, mutate, Object.assign(Object.assign({}, applyOptions), { enablePatches: false }));
4905
- }
4906
- var constructorString = Object.prototype.constructor.toString();
4907
-
4908
- // ../core/dist/index.js
4909
- class ArcContextElement {
4910
- $event;
4911
- name;
4912
- queryBuilder;
4913
- commandContext;
4914
- commandClient;
4915
- observer;
4916
- }
4917
-
4918
- class ArcContextElementWithStore extends ArcContextElement {
4919
- }
4920
-
4921
- class ArcOptional {
4922
- parent;
4923
- constructor(parent) {
4924
- this.parent = parent;
4925
- }
4926
- parse(value) {
4927
- if (!value)
4928
- return null;
4929
- return this.parent.parse(value);
4930
- }
4931
- serialize(value) {
4932
- if (value)
4933
- return this.parent.serialize(value);
4934
- return null;
4935
- }
4936
- deserialize(value) {
4937
- if (!value)
4938
- return null;
4939
- return this.parent.deserialize(value);
4940
- }
4941
- validate(value) {
4942
- if (!value)
4943
- return false;
4944
- return this.parent.validate(value);
4945
- }
4946
- toJsonSchema() {
4947
- const parentSchema = this.parent.toJsonSchema?.() ?? {};
4948
- return {
4949
- anyOf: [parentSchema, { type: "null" }]
4950
- };
4951
- }
4952
- }
4953
-
4954
- class ArcBranded {
4955
- parent;
4956
- brand;
4957
- constructor(parent, brand) {
4958
- this.parent = parent;
4959
- this.brand = brand;
4960
- }
4961
- serialize(value) {
4962
- return this.parent.serialize(value);
4963
- }
4964
- deserialize(value) {
4965
- return this.parent.deserialize(value);
4966
- }
4967
- parse(value) {
4968
- return this.parent.parse(value);
4969
- }
4970
- optional() {
4971
- return new ArcOptional(this);
4972
- }
4973
- validate(value) {
4974
- return this.parent.validate(value);
4975
- }
4976
- toJsonSchema() {
4977
- return this.parent.toJsonSchema?.() ?? {};
4978
- }
4979
- }
4980
-
4981
- class ArcDefault {
4982
- parent;
4983
- defaultValueOrCallback;
4984
- constructor(parent, defaultValueOrCallback) {
4985
- this.parent = parent;
4986
- this.defaultValueOrCallback = defaultValueOrCallback;
4987
- }
4988
- validate(value) {
4989
- throw new Error("Method not implemented.");
4990
- }
4991
- parse(value) {
4992
- if (value)
4993
- return this.parent.parse(value);
4994
- if (typeof this.defaultValueOrCallback === "function") {
4995
- return this.defaultValueOrCallback();
4996
- } else
4997
- return this.defaultValueOrCallback;
4998
- }
4999
- serialize(value) {
5000
- return this.parent.serialize(value);
5001
- }
5002
- deserialize(value) {
5003
- if (value)
5004
- return this.parent.deserialize(value);
5005
- if (typeof this.defaultValueOrCallback === "function") {
5006
- return this.defaultValueOrCallback();
5007
- } else
5008
- return this.defaultValueOrCallback;
5009
- }
5010
- toJsonSchema() {
5011
- const schema = this.parent.toJsonSchema?.() ?? {};
5012
- const defaultValue = typeof this.defaultValueOrCallback === "function" ? this.defaultValueOrCallback() : this.defaultValueOrCallback;
5013
- return {
5014
- ...schema,
5015
- default: defaultValue
5016
- };
5017
- }
5018
- }
5019
-
5020
- class ArcAbstract {
5021
- validations;
5022
- _description;
5023
- constructor(validations = []) {
5024
- this.validations = validations;
5025
- }
5026
- description(description) {
5027
- const clone = this.clone();
5028
- clone._description = description;
5029
- return clone;
5030
- }
5031
- default(defaultValueOrCallback) {
5032
- return new ArcDefault(this, defaultValueOrCallback);
5033
- }
5034
- optional() {
5035
- return new ArcOptional(this);
5036
- }
5037
- branded(name) {
5038
- return new ArcBranded(this, name);
5039
- }
5040
- clone() {
5041
- const Constructor = this.constructor;
5042
- const newInstance = Object.assign(new Constructor, this);
5043
- newInstance._description = this._description;
5044
- return newInstance;
5045
- }
5046
- validate(value) {
5047
- const errors = this.validations.reduce((acc, { name, validator }) => {
5048
- try {
5049
- acc[name] = validator(value);
5050
- } catch (error) {
5051
- acc[name] = error;
5052
- }
5053
- return acc;
5054
- }, {});
5055
- if (Object.values(errors).some((result) => !!result)) {
5056
- return errors;
5057
- }
5058
- return false;
5059
- }
5060
- pipeValidation(name, validator) {
5061
- const newInstance = this.clone();
5062
- newInstance.validations = [...this.validations, { name, validator }];
5063
- return newInstance;
5064
- }
5065
- toJsonSchema() {
5066
- const schema = {};
5067
- if (this._description) {
5068
- schema.description = this._description;
5069
- }
5070
- return schema;
5071
- }
5072
- getValidations() {
5073
- return this.validations;
5074
- }
5075
- }
5076
-
5077
- class ArcPrimitive extends ArcAbstract {
5078
- serialize(value) {
5079
- return value;
5080
- }
5081
- parse(value) {
5082
- return value;
5083
- }
5084
- deserialize(value) {
5085
- return value;
5086
- }
5087
- }
5088
- function primitiveTypeComparatorStrategyFactory(type) {
5089
- return (value) => typeof value === type;
5090
- }
5091
- function typeValidatorBuilder(typeName, comparatorStrategy) {
5092
- const comparator = comparatorStrategy || primitiveTypeComparatorStrategyFactory(typeName);
5093
- return {
5094
- name: "type",
5095
- validator: (value) => {
5096
- const valueType = typeof value;
5097
- if (!comparator(value))
5098
- return { current: valueType, expected: typeName };
5099
- return false;
5100
- }
5101
- };
5102
- }
5103
- var stringValidator = typeValidatorBuilder("string");
5104
-
5105
- class ArcString extends ArcPrimitive {
5106
- constructor() {
5107
- super([stringValidator]);
5108
- }
5109
- minLength(min) {
5110
- return this.validation("minLength", (value) => {
5111
- if (value.length < min)
5112
- return {
5113
- currentLength: value.length,
5114
- minLength: min
5115
- };
5116
- });
5117
- }
5118
- maxLength(max) {
5119
- return this.validation("maxLength", (value) => {
5120
- if (value.length > max)
5121
- return {
5122
- currentLength: value.length,
5123
- maxLength: max
5124
- };
5125
- });
5126
- }
5127
- length(number) {
5128
- return this.validation("length", (value) => {
5129
- if (value.length !== number) {
5130
- return {
5131
- currentLength: value.length,
5132
- length: number
5133
- };
5134
- }
5135
- });
5136
- }
5137
- includes(str) {
5138
- return this.validation("includes", (value) => {
5139
- if (!value.includes(str)) {
5140
- return {
5141
- currentValue: value,
5142
- includes: str
5143
- };
5144
- }
5145
- });
5146
- }
5147
- startsWith(str) {
5148
- return this.validation("startsWith", (value) => {
5149
- if (!value.startsWith(str)) {
5150
- return {
5151
- currentValue: value,
5152
- startsWith: str
5153
- };
5154
- }
5155
- });
5156
- }
5157
- endsWith(str) {
5158
- return this.validation("endsWith", (value) => {
5159
- if (!value.endsWith(str)) {
5160
- return {
5161
- currentValue: value,
5162
- endsWith: str
5163
- };
5164
- }
5165
- });
5166
- }
5167
- regex(regex) {
5168
- return this.validation("regex", (value) => {
5169
- if (!regex.test(value)) {
5170
- return {
5171
- currentValue: value,
5172
- regex
5173
- };
5174
- }
5175
- });
5176
- }
5177
- email() {
5178
- const regex = /^(?:(?:[a-zA-Z0-9!#$%&'*+/=?^_`{|}~.-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~.-]+)*)|(?:"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f])*"))@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$|(?:\[(?:\d{1,3}\.){3}\d{1,3}\])$/;
5179
- return this.validation("email", (value) => {
5180
- if (!regex.test(value)) {
5181
- return {
5182
- currentEmail: value
5183
- };
5184
- }
5185
- });
5186
- }
5187
- toJsonSchema() {
5188
- const schema = { type: "string" };
5189
- if (this._description) {
5190
- schema.description = this._description;
5191
- }
5192
- return schema;
5193
- }
5194
- url() {
5195
- const regex = /^(https?):\/\/(?![-0-9])(?!www\.[0-9])(?:[a-zA-Z0-9-]+(?::[a-zA-Z0-9-]+)?@)?(?:localhost|\b(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b|[a-zA-Z0-9-]+\.)?[a-zA-Z0-9-]+\.(?:[a-zA-Z]{2,}|[a-zA-Z]{2}\.[a-zA-Z]{2})(?::\d{1,5})?(?!\/\/)(?:\/[a-zA-Z0-9-._~:?#\[\]@!$&'()*+,;=]*)*(?!\/{2})(?:;[a-zA-Z0-9-._~:?#\[\]@!$&'()*+,;=]*)*(\?(?!=)[a-zA-Z0-9&=;]*)?(\#[a-zA-Z0-9-]*)?$|^(https?):\/\/(localhost|\b(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b)(?::\d{1,5})?(?!\/\/)(?:\/[a-zA-Z0-9-._~:?#\[\]@!$&'()*+,;=]*)*(?!\/{2})(?:;[a-zA-Z0-9-._~:?#\[\]@!$&'()*+,;=]*)*(\?(?!=)[a-zA-Z0-9&=;]*)?(\#[a-zA-Z0-9-]*)?$/;
5196
- return this.validation("url", (value) => {
5197
- if (!regex.test(value)) {
5198
- return {
5199
- currentUrl: value
5200
- };
5201
- }
5202
- });
5203
- }
5204
- ip() {
5205
- const IPv4regex = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
5206
- const IPv6regex = /^(?:([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|:(:[0-9a-fA-F]{1,4}){1,7}|([0-9a-fA-F]{1,4}:){1,6}:([0-9a-fA-F]{1,4}:){1,6}[0-9a-fA-F]{1,4})$/;
5207
- return this.validation("ip", (value) => {
5208
- if (!(IPv4regex.test(value) || IPv6regex.test(value))) {
5209
- return {
5210
- currentIP: value
5211
- };
5212
- }
5213
- });
5214
- }
5215
- validation(name, validator) {
5216
- const instance = this.pipeValidation(name, validator);
5217
- return instance;
5218
- }
5219
- }
5220
- function string() {
5221
- return new ArcString;
5222
- }
5223
-
5224
- class ArcCustomId extends ArcBranded {
5225
- createFn;
5226
- constructor(name, createFn) {
5227
- super(string(), name);
5228
- this.createFn = createFn;
5229
- }
5230
- get(...args) {
5231
- return this.createFn(...args);
5232
- }
5233
- }
5234
-
5235
- class ArcId extends ArcBranded {
5236
- generateFn;
5237
- constructor(name, generateFn) {
5238
- super(string(), name);
5239
- this.generateFn = generateFn;
5240
- }
5241
- generate() {
5242
- if (this.generateFn) {
5243
- return this.generateFn();
5244
- }
5245
- var timestamp = (new Date().getTime() / 1000 | 0).toString(16);
5246
- return timestamp + "xxxxxxxxxxxxxxxx".replace(/[x]/g, function() {
5247
- return (Math.random() * 16 | 0).toString(16);
5248
- }).toLowerCase();
5249
- }
5250
- }
5251
- function id(name, generateFn) {
5252
- return new ArcId(name, generateFn);
5253
- }
5254
- var objectValidator = typeValidatorBuilder("object");
5255
-
5256
- class ArcObject extends ArcAbstract {
5257
- rawShape;
5258
- constructor(rawShape) {
5259
- super([
5260
- objectValidator,
5261
- {
5262
- name: "schema",
5263
- validator: (value) => {
5264
- const errors = Object.entries(this.rawShape).reduce((acc, [key, element]) => {
5265
- if (!element.validate) {
5266
- return acc;
5267
- }
5268
- acc[key] = element.validate(value[key]);
5269
- return acc;
5270
- }, {});
5271
- if (Object.values(errors).some((result) => !!result)) {
5272
- return errors;
5273
- }
5274
- return false;
5275
- }
5276
- }
5277
- ]);
5278
- this.rawShape = rawShape;
5279
- }
5280
- parse(value) {
5281
- return Object.entries(this.rawShape).reduce((acc, [key, element]) => {
5282
- acc[key] = element.parse(value[key]);
5283
- return acc;
5284
- }, {});
5285
- }
5286
- serialize(value) {
5287
- return Object.entries(value).reduce((acc, [key, value2]) => {
5288
- if (!this.rawShape[key]) {
5289
- acc[key] = value2;
5290
- } else {
5291
- acc[key] = this.rawShape[key].serialize(value2);
5292
- }
5293
- return acc;
5294
- }, {});
5295
- }
5296
- deserialize(value) {
5297
- return Object.fromEntries(Object.entries(this.rawShape).map(([key, element]) => [
5298
- key,
5299
- element.deserialize(value[key])
5300
- ]));
5301
- }
5302
- deserializePath(path, value) {
5303
- if (path.length === 0) {
5304
- return this.deserialize(value);
5305
- }
5306
- const [key, ...restPath] = path;
5307
- const element = this.rawShape[key];
5308
- if (!element) {
5309
- console.warn(`No element found for key: ${key}`);
5310
- return value;
5311
- }
5312
- if (element instanceof ArcObject || element instanceof ArcArray) {
5313
- return element.deserializePath(restPath, value);
5314
- }
5315
- return element.deserialize(value);
5316
- }
5317
- parsePartial(value) {
5318
- return Object.entries(value).reduce((acc, [key, value2]) => {
5319
- acc[key] = this.rawShape[key].parse(value2);
5320
- return acc;
5321
- }, {});
5322
- }
5323
- deserializePartial(value) {
5324
- return Object.entries(value).reduce((acc, [key, value2]) => {
5325
- acc[key] = this.rawShape[key].deserialize(value2);
5326
- return acc;
5327
- }, {});
5328
- }
5329
- serializePartial(value) {
5330
- return Object.entries(value).reduce((acc, [key, value2]) => {
5331
- if (!this.rawShape[key]) {
5332
- console.warn(`No element found for key: ${key}`);
5333
- return acc;
5334
- }
5335
- acc[key] = this.rawShape[key].serialize(value2);
5336
- return acc;
5337
- }, {});
5338
- }
5339
- validatePartial(value) {
5340
- const errors = Object.entries(value).reduce((acc, [key, val]) => {
5341
- if (!this.rawShape[key]) {
5342
- return acc;
5343
- }
5344
- const result = this.rawShape[key].validate(val);
5345
- if (result) {
5346
- acc[key] = result;
5347
- }
5348
- return acc;
5349
- }, {});
5350
- if (Object.keys(errors).length > 0) {
5351
- return { schema: errors };
5352
- }
5353
- return false;
5354
- }
5355
- pick(...keys) {
5356
- return new ArcObject(Object.fromEntries(keys.map((key) => [key, this.rawShape[key]])));
5357
- }
5358
- omit(...keys) {
5359
- return new ArcObject(Object.fromEntries(Object.entries(this.rawShape).filter(([key]) => !keys.includes(key))));
5360
- }
5361
- entries() {
5362
- return Object.entries(this.rawShape);
5363
- }
5364
- toJsonSchema() {
5365
- const properties = {};
5366
- const required = [];
5367
- for (const [key, element] of Object.entries(this.rawShape)) {
5368
- properties[key] = element.toJsonSchema?.() ?? {};
5369
- if (!(element instanceof ArcOptional)) {
5370
- required.push(key);
5371
- }
5372
- }
5373
- const schema = {
5374
- type: "object",
5375
- properties
5376
- };
5377
- if (required.length)
5378
- schema.required = required;
5379
- if (this._description) {
5380
- schema.description = this._description;
5381
- }
5382
- return schema;
5383
- }
5384
- }
5385
- var arrayValidator = typeValidatorBuilder("array", Array.isArray);
5386
-
5387
- class ArcArray extends ArcAbstract {
5388
- parent;
5389
- constructor(parent) {
5390
- super([
5391
- arrayValidator,
5392
- {
5393
- name: "schema",
5394
- validator: (values) => {
5395
- const errors = values.reduce((acc, value, index) => {
5396
- const error = parent.validate(value);
5397
- if (error)
5398
- acc[index] = error;
5399
- return acc;
5400
- }, {});
5401
- if (Object.values(errors).some((result) => !!result)) {
5402
- return errors;
5403
- }
5404
- return false;
5405
- }
5406
- }
5407
- ]);
5408
- this.parent = parent;
5409
- }
5410
- minLength(min) {
5411
- return this.validation("minLength", (value) => {
5412
- if (value.length < min)
5413
- return {
5414
- currentLength: value.length,
5415
- minLength: min
5416
- };
5417
- });
5418
- }
5419
- maxLength(max) {
5420
- return this.validation("maxLength", (value) => {
5421
- if (value.length > max)
5422
- return {
5423
- currentLength: value.length,
5424
- maxLength: max
5425
- };
5426
- });
5427
- }
5428
- length(number) {
5429
- return this.validation("length", (value) => {
5430
- if (value.length !== number) {
5431
- return {
5432
- currentLength: value.length,
5433
- length: number
5434
- };
5435
- }
5436
- });
5437
- }
5438
- nonEmpty() {
5439
- return this.validation("nonEmpty", (value) => {
5440
- if (value.length === 0)
5441
- return { msg: "array is empty" };
5442
- });
5443
- }
5444
- parse(value) {
5445
- return value.map((v) => this.parent.parse(v));
5446
- }
5447
- serialize(value) {
5448
- return value.map((v) => this.parent.serialize(v));
5449
- }
5450
- deserialize(value) {
5451
- if (!Array.isArray(value))
5452
- return [];
5453
- return value.map((v) => this.parent.deserialize(v));
5454
- }
5455
- deserializePath(path, value) {
5456
- if (path.length === 0) {
5457
- return this.deserialize(value);
5458
- }
5459
- if (this.parent instanceof ArcObject || this.parent instanceof ArcArray) {
5460
- return this.parent.deserializePath(path, value);
5461
- }
5462
- return this.parent.deserialize(value);
5463
- }
5464
- validation(name, validator) {
5465
- const instance = this.pipeValidation(name, validator);
5466
- return instance;
5467
- }
5468
- toJsonSchema() {
5469
- const schema = {
5470
- type: "array",
5471
- items: this.parent.toJsonSchema?.() ?? {}
5472
- };
5473
- if (this._description) {
5474
- schema.description = this._description;
5475
- }
5476
- return schema;
5477
- }
5478
- }
5479
- class ArcBoolean extends ArcPrimitive {
5480
- hasToBeTrue() {
5481
- return this.validation("hasToBeTrue", (value) => {
5482
- if (!value)
5483
- return {
5484
- current: value
5485
- };
5486
- });
5487
- }
5488
- validation(name, validator) {
5489
- const instance = this.pipeValidation(name, validator);
5490
- return instance;
5491
- }
5492
- toJsonSchema() {
5493
- const schema = { type: "boolean" };
5494
- if (this._description) {
5495
- schema.description = this._description;
5496
- }
5497
- return schema;
5498
- }
5499
- }
5500
- var dateValidator = typeValidatorBuilder("Date", (value) => value instanceof Date);
5501
-
5502
- class ArcDate extends ArcAbstract {
5503
- constructor() {
5504
- super([dateValidator]);
5505
- }
5506
- parse(value) {
5507
- return new Date(value);
5508
- }
5509
- serialize(value) {
5510
- if (value instanceof Date) {
5511
- return value.getTime();
5512
- }
5513
- return value;
5514
- }
5515
- deserialize(value) {
5516
- return new Date(value);
5517
- }
5518
- after(after) {
5519
- return this.validation("after", (value) => {
5520
- if (value <= after)
5521
- return { current: value, after };
5522
- });
5523
- }
5524
- before(before) {
5525
- return this.validation("before", (value) => {
5526
- if (value >= before)
5527
- return { current: value, before };
5528
- });
5529
- }
5530
- validation(name, validator) {
5531
- const instance = this.pipeValidation(name, validator);
5532
- return instance;
5533
- }
5534
- toJsonSchema() {
5535
- const schema = {
5536
- type: "string",
5537
- format: "date-time"
5538
- };
5539
- if (this._description) {
5540
- schema.description = this._description;
5541
- }
5542
- return schema;
5543
- }
5544
- }
5545
- var numberValidator = typeValidatorBuilder("number");
5546
-
5547
- class ArcNumber extends ArcPrimitive {
5548
- constructor() {
5549
- super([numberValidator]);
5550
- }
5551
- min(min) {
5552
- return this.validation("min", (value) => {
5553
- if (value < min)
5554
- return { current: value, min };
5555
- });
5556
- }
5557
- max(max) {
5558
- return this.validation("max", (value) => {
5559
- if (value > max)
5560
- return { current: value, max };
5561
- });
5562
- }
5563
- validation(name, validator) {
5564
- const instance = this.pipeValidation(name, validator);
5565
- return instance;
5566
- }
5567
- toJsonSchema() {
5568
- const schema = { type: "number" };
5569
- if (this._description) {
5570
- schema.description = this._description;
5571
- }
5572
- return schema;
5573
- }
5574
- }
5575
- function getSQLiteType(element2) {
5576
- if (element2 instanceof ArcDate) {
5577
- return "TEXT";
5578
- }
5579
- if (element2 instanceof ArcArray || element2 instanceof ArcObject) {
5580
- return "TEXT";
5581
- }
5582
- if (element2 instanceof ArcBoolean) {
5583
- return "INTEGER";
5584
- }
5585
- if (element2 instanceof ArcNumber) {
5586
- return "NUMBER";
5587
- }
5588
- return "TEXT";
5589
- }
5590
- function arcObjectToStoreSchema(tableName, schema) {
5591
- const columns = schema.entries().map(([name, element2]) => ({
5592
- name,
5593
- type: getSQLiteType(element2),
5594
- isOptional: element2 instanceof ArcOptional
5595
- }));
5596
- columns.unshift({
5597
- name: "_id",
5598
- type: "TEXT",
5599
- isOptional: false
5600
- }, {
5601
- name: "deleted",
5602
- type: "INTEGER",
5603
- isOptional: false,
5604
- default: 0
5605
- }, {
5606
- name: "lastUpdate",
5607
- type: "TEXT",
5608
- isOptional: false
5609
- });
5610
- return {
5611
- tables: [
5612
- {
5613
- name: tableName,
5614
- columns,
5615
- primaryKey: "_id"
5616
- }
5617
- ]
5618
- };
5619
- }
5620
-
5621
- class ArcQuery {
5622
- lastResult;
5623
- listeners = new Set;
5624
- subscribe(listener) {
5625
- this.listeners.add(listener);
5626
- }
5627
- unsubscribe(listener) {
5628
- this.listeners.delete(listener);
5629
- }
5630
- nextResult(result) {
5631
- this.lastResult = result;
5632
- this.listeners.forEach((listener) => listener(result));
5633
- }
5634
- }
5635
-
5636
- class ArcSerializableQuery extends ArcQuery {
5637
- params;
5638
- static key;
5639
- constructor(params) {
5640
- super();
5641
- this.params = params;
5642
- }
5643
- serialize() {
5644
- return {
5645
- key: this.constructor.key,
5646
- params: this.params
5647
- };
5648
- }
5649
- }
5650
-
5651
- class ArcCollectionQuery extends ArcSerializableQuery {
5652
- collection;
5653
- bindedChangeHandler = this.changeHandler.bind(this);
5654
- store;
5655
- constructor(collection, params) {
5656
- super(params);
5657
- this.collection = collection;
5658
- }
5659
- async run(dataStorage) {
5660
- const store = dataStorage.getStore(this.collection.name);
5661
- this.store = store;
5662
- const result = await this.fetch(store);
5663
- this.lastResult = result;
5664
- return result;
5665
- }
5666
- changeHandler(changes) {
5667
- let resultChanged = false;
5668
- for (const change of changes) {
5669
- const response = this.onChange(change);
5670
- if (response !== false) {
5671
- this.lastResult = response;
5672
- resultChanged = true;
5673
- }
5674
- }
5675
- if (resultChanged)
5676
- this.nextResult(this.lastResult);
5677
- }
5678
- }
5679
-
5680
- class QueryCollectionResult {
5681
- result;
5682
- constructor(result) {
5683
- this.result = result;
5684
- }
5685
- get(id3) {
5686
- return id3 ? this.result.find((r) => r._id === id3) : undefined;
5687
- }
5688
- map(callbackfn) {
5689
- return this.result.map(callbackfn);
5690
- }
5691
- toArray() {
5692
- return this.result;
5693
- }
5694
- }
5695
-
5696
- class ArcFindQuery extends ArcCollectionQuery {
5697
- params;
5698
- constructor(collection, params) {
5699
- super(collection, params);
5700
- this.params = params;
5701
- }
5702
- async fetch(store) {
5703
- const results = await store.find(this.params, this.bindedChangeHandler);
5704
- return this.createResult(results);
5705
- }
5706
- checkItem(item) {
5707
- if (!this.params.where)
5708
- return true;
5709
- return Object.entries(this.params.where).every(([key, condition]) => {
5710
- const value = item[key];
5711
- if (typeof condition !== "object" || condition === null) {
5712
- return value === condition;
5713
- }
5714
- return Object.entries(condition).every(([operator, operatorValue]) => {
5715
- switch (operator) {
5716
- case "$eq":
5717
- return value === operatorValue;
5718
- case "$ne":
5719
- return value !== operatorValue;
5720
- case "$gt":
5721
- return typeof value === "number" && typeof operatorValue === "number" && value > operatorValue;
5722
- case "$gte":
5723
- return typeof value === "number" && typeof operatorValue === "number" && value >= operatorValue;
5724
- case "$lt":
5725
- return typeof value === "number" && typeof operatorValue === "number" && value < operatorValue;
5726
- case "$lte":
5727
- return typeof value === "number" && typeof operatorValue === "number" && value <= operatorValue;
5728
- case "$in":
5729
- return Array.isArray(operatorValue) && operatorValue.includes(value);
5730
- case "$nin":
5731
- return Array.isArray(operatorValue) && !operatorValue.includes(value);
5732
- case "$exists":
5733
- return typeof operatorValue === "boolean" ? operatorValue ? value !== undefined : value === undefined : true;
5734
- default:
5735
- return true;
5736
- }
5737
- });
5738
- });
5739
- }
5740
- onChange(change) {
5741
- const lastResult = this.lastResult;
5742
- const lastResultAsArray = lastResult || [];
5743
- const index = lastResultAsArray.findIndex((e) => e._id === (change.type === "delete" ? change.id : change.id));
5744
- const isInLastResult = index !== -1;
5745
- const shouldBeInTheResult = change.type !== "delete" && this.checkItem(change.item);
5746
- if (isInLastResult && shouldBeInTheResult)
5747
- return this.createResult(lastResultAsArray.toSpliced(index, 1, change.item));
5748
- else if (isInLastResult && (change.type === "delete" || !shouldBeInTheResult))
5749
- return this.createResult(lastResultAsArray.toSpliced(index, 1));
5750
- else if (!isInLastResult && shouldBeInTheResult)
5751
- return this.createResult(lastResultAsArray.concat(change.item));
5752
- return false;
5753
- }
5754
- createResult(result) {
5755
- return new QueryCollectionResult(result);
5756
- }
5757
- }
5758
-
5759
- class ArcFindQueryBuilder {
5760
- collection;
5761
- queryContext;
5762
- options;
5763
- constructor(collection, queryContext, options) {
5764
- this.collection = collection;
5765
- this.queryContext = queryContext;
5766
- this.options = options;
5767
- }
5768
- toQuery() {
5769
- return this.queryContext.cacheQuery(ArcFindQuery, [
5770
- this.collection,
5771
- this.options
5772
- ]);
5773
- }
5774
- run() {
5775
- return this.queryContext.runQuery(this.toQuery());
5776
- }
5777
- }
5778
-
5779
- class ArcCollection extends ArcContextElementWithStore {
5780
- name;
5781
- id;
5782
- schema;
5783
- options;
5784
- _restrictions;
5785
- constructor(name, id3, schema, options) {
5786
- super();
5787
- this.name = name;
5788
- this.id = id3;
5789
- this.schema = schema;
5790
- this.options = options;
5791
- }
5792
- storeSchema() {
5793
- return arcObjectToStoreSchema(this.name, this.schema);
5794
- }
5795
- restrictions(authContext) {
5796
- if (this._restrictions) {
5797
- return this._restrictions(authContext);
5798
- }
5799
- return {
5800
- read: false,
5801
- write: false,
5802
- modify: false,
5803
- delete: false
5804
- };
5805
- }
5806
- auth(restrictionsFn) {
5807
- const collection = new ArcCollection(this.name, this.id, this.schema, this.options);
5808
- collection._restrictions = restrictionsFn;
5809
- return collection;
5810
- }
5811
- serialize(data) {
5812
- return {
5813
- _id: this.id.serialize(data._id),
5814
- ...this.schema.serialize(data)
5815
- };
5816
- }
5817
- deserialize(data) {
5818
- return {
5819
- _id: this.id.deserialize(data._id),
5820
- ...this.schema.deserialize(data)
5821
- };
5822
- }
5823
- queryBuilder = (context) => {
5824
- return {
5825
- find: (options) => new ArcFindQueryBuilder(this, context, options || {})
5826
- };
5827
- };
5828
- commandContext = (dataStorage, publishEvent) => {
5829
- const store = dataStorage.getStore(this.name);
5830
- return {
5831
- add: async (data) => {
5832
- if (this.id instanceof ArcCustomId)
5833
- throw new Error("Collection with custom id not support 'add' method");
5834
- const id3 = this.id.generate();
5835
- const parsed = this.schema.parse(data);
5836
- const body = {
5837
- _id: id3,
5838
- lastUpdate: new Date().toISOString(),
5839
- ...parsed
5840
- };
5841
- await store.set(body);
5842
- await publishEvent({
5843
- type: "set",
5844
- to: body
5845
- });
5846
- return { id: id3 };
5847
- },
5848
- remove: async (id3) => {
5849
- await store.remove(id3);
5850
- return { success: true };
5851
- },
5852
- set: async (id3, data) => {
5853
- const parsed = this.schema.parse(data);
5854
- const body = {
5855
- _id: id3,
5856
- ...parsed
5857
- };
5858
- await store.set(body);
5859
- await publishEvent({
5860
- type: "set",
5861
- to: body
5862
- });
5863
- return { success: true };
5864
- },
5865
- find: async (options) => {
5866
- return store.find(options);
5867
- },
5868
- findOne: async (where) => {
5869
- const result = await store.find({
5870
- where,
5871
- limit: 1
5872
- });
5873
- return result[0];
5874
- },
5875
- modify: async (id3, data) => {
5876
- const deserialized = this.schema.serializePartial(data);
5877
- const { from, to } = await store.modify(id3, deserialized);
5878
- await publishEvent({
5879
- type: "modify",
5880
- changes: deserialized,
5881
- from,
5882
- to
5883
- });
5884
- },
5885
- edit: async (id3, editCallback) => {
5886
- const { from, to } = await store.mutate(id3, editCallback);
5887
- await publishEvent({
5888
- type: "mutate",
5889
- from,
5890
- to
5891
- });
5892
- }
5893
- };
5894
- };
5895
- }
5896
- var eventValidator = typeValidatorBuilder("object");
5897
- var eventId = id("event");
5898
- class QueryBuilderContext {
5899
- queryCache;
5900
- dataStorage;
5901
- usedQueries = new Set;
5902
- constructor(queryCache, dataStorage) {
5903
- this.queryCache = queryCache;
5904
- this.dataStorage = dataStorage;
5905
- }
5906
- cacheQuery(QueryConstructor, args) {
5907
- return new QueryConstructor(...args);
5908
- }
5909
- runQuery(query) {
5910
- this.usedQueries.add(query);
5911
- return query.run(this.dataStorage);
5912
- }
5913
- getUsedQueries() {
5914
- const queries = Array.from(this.usedQueries);
5915
- this.usedQueries.clear();
5916
- return queries;
5917
- }
5918
- }
5919
- function murmurHash(key, seed = 0) {
5920
- var remainder, bytes, h1, h1b, c1, c1b, c2, c2b, k1, i;
5921
- remainder = key.length & 3;
5922
- bytes = key.length - remainder;
5923
- h1 = seed;
5924
- c1 = 3432918353;
5925
- c2 = 461845907;
5926
- i = 0;
5927
- while (i < bytes) {
5928
- k1 = key.charCodeAt(i) & 255 | (key.charCodeAt(++i) & 255) << 8 | (key.charCodeAt(++i) & 255) << 16 | (key.charCodeAt(++i) & 255) << 24;
5929
- ++i;
5930
- k1 = (k1 & 65535) * c1 + (((k1 >>> 16) * c1 & 65535) << 16) & 4294967295;
5931
- k1 = k1 << 15 | k1 >>> 17;
5932
- k1 = (k1 & 65535) * c2 + (((k1 >>> 16) * c2 & 65535) << 16) & 4294967295;
5933
- h1 ^= k1;
5934
- h1 = h1 << 13 | h1 >>> 19;
5935
- h1b = (h1 & 65535) * 5 + (((h1 >>> 16) * 5 & 65535) << 16) & 4294967295;
5936
- h1 = (h1b & 65535) + 27492 + (((h1b >>> 16) + 58964 & 65535) << 16);
5937
- }
5938
- k1 = 0;
5939
- switch (remainder) {
5940
- case 3:
5941
- k1 ^= (key.charCodeAt(i + 2) & 255) << 16;
5942
- case 2:
5943
- k1 ^= (key.charCodeAt(i + 1) & 255) << 8;
5944
- case 1:
5945
- k1 ^= key.charCodeAt(i) & 255;
5946
- k1 = (k1 & 65535) * c1 + (((k1 >>> 16) * c1 & 65535) << 16) & 4294967295;
5947
- k1 = k1 << 15 | k1 >>> 17;
5948
- k1 = (k1 & 65535) * c2 + (((k1 >>> 16) * c2 & 65535) << 16) & 4294967295;
5949
- h1 ^= k1;
5950
- }
5951
- h1 ^= key.length;
5952
- h1 ^= h1 >>> 16;
5953
- h1 = (h1 & 65535) * 2246822507 + (((h1 >>> 16) * 2246822507 & 65535) << 16) & 4294967295;
5954
- h1 ^= h1 >>> 13;
5955
- h1 = (h1 & 65535) * 3266489909 + (((h1 >>> 16) * 3266489909 & 65535) << 16) & 4294967295;
5956
- h1 ^= h1 >>> 16;
5957
- return h1 >>> 0;
5958
- }
5959
-
5960
- class QueryCache {
5961
- cache = new Map;
5962
- getIndexHash(value) {
5963
- if (typeof value === "number" || typeof value === "string" || typeof value === "function" || value === null || value === undefined) {
5964
- return value;
5965
- }
5966
- return murmurHash(value);
5967
- }
5968
- set(index, query) {
5969
- let current2 = this.cache;
5970
- for (let i = 0;i < index.length - 1; i++) {
5971
- const hashedIndex = this.getIndexHash(index[i]);
5972
- if (!current2.has(hashedIndex)) {
5973
- current2.set(hashedIndex, new Map);
5974
- }
5975
- current2 = current2.get(hashedIndex);
5976
- }
5977
- const lastHashedIndex = this.getIndexHash(index[index.length - 1]);
5978
- current2.set(lastHashedIndex, query);
5979
- }
5980
- get(index) {
5981
- let current2 = this.cache;
5982
- for (let i = 0;i < index.length - 1; i++) {
5983
- const hashedIndex = this.getIndexHash(index[i]);
5984
- if (!current2.has(hashedIndex)) {
5985
- return;
5986
- }
5987
- current2 = current2.get(hashedIndex);
5988
- }
5989
- const lastHashedIndex = this.getIndexHash(index[index.length - 1]);
5990
- return current2.get(lastHashedIndex);
5991
- }
5992
- debug() {
5993
- return this.cache;
5994
- }
5995
- }
5996
-
5997
- class ReactiveQuery extends ArcQuery {
5998
- queryContext;
5999
- queryBuilder;
6000
- fn;
6001
- queries = [];
6002
- constructor(queryContext, queryBuilder, fn) {
6003
- super();
6004
- this.queryContext = queryContext;
6005
- this.queryBuilder = queryBuilder;
6006
- this.fn = fn;
6007
- }
6008
- run() {
6009
- const promise = new Promise(async (resolve) => {
6010
- const value = await this.runQuery();
6011
- resolve(value);
6012
- });
6013
- return promise;
6014
- }
6015
- onChangeHandler = this.onChange.bind(this);
6016
- async onChange() {
6017
- const value = await this.runQuery();
6018
- await this.nextResult(value);
6019
- }
6020
- async runQuery() {
6021
- const value = await this.fn(this.queryBuilder);
6022
- const queries = this.queryContext.getUsedQueries();
6023
- this.queries.forEach((query) => {
6024
- if (!queries.includes(query)) {
6025
- query.unsubscribe(this.onChangeHandler);
6026
- }
6027
- });
6028
- queries.forEach((query) => {
6029
- if (!this.queries.includes(query)) {
6030
- query.subscribe(this.onChangeHandler);
6031
- }
6032
- });
6033
- this.queries = queries;
6034
- return value;
6035
- }
6036
- }
6037
- class DataStorage {
6038
- async commitChanges(changes) {
6039
- await Promise.all(changes.map(({ store, changes: changes2 }) => this.getStore(store).applyChanges(changes2)));
6040
- }
6041
- }
6042
- function deepMerge(target, source) {
6043
- const output = { ...target };
6044
- for (const key in source) {
6045
- if (source[key] === undefined) {
6046
- output[key] = undefined;
6047
- continue;
6048
- }
6049
- if (isObject(source[key]) && isObject(target[key])) {
6050
- output[key] = deepMerge(target[key], source[key]);
6051
- } else {
6052
- output[key] = source[key];
6053
- }
6054
- }
6055
- return output;
6056
- }
6057
- function isObject(item) {
6058
- return item && typeof item === "object" && !Array.isArray(item);
6059
- }
6060
-
6061
- class StoreState {
6062
- storeName;
6063
- dataStorage;
6064
- deserialize;
6065
- listeners = new Map;
6066
- constructor(storeName, dataStorage, deserialize) {
6067
- this.storeName = storeName;
6068
- this.dataStorage = dataStorage;
6069
- this.deserialize = deserialize;
6070
- }
6071
- fork() {
6072
- return new ForkedStoreState(this.storeName, this.dataStorage, this);
6073
- }
6074
- async set(item) {
6075
- const change = {
6076
- type: "set",
6077
- data: item
6078
- };
6079
- await this.applyChanges([change]);
6080
- }
6081
- async remove(id3) {
6082
- const change = {
6083
- type: "delete",
6084
- id: id3
6085
- };
6086
- await this.applyChanges([change]);
6087
- }
6088
- async modify(id3, data) {
6089
- const change = {
6090
- type: "modify",
6091
- id: id3,
6092
- data
6093
- };
6094
- const { from, to } = await this.applyChange(change);
6095
- return { from, to };
6096
- }
6097
- async mutate(id3, editCallback) {
6098
- const result = await this.find({ where: { _id: id3 } });
6099
- const object3 = result[0];
6100
- const [draft, finalize] = create(object3 || {}, { enablePatches: true });
6101
- await editCallback(draft);
6102
- const [_, patches] = finalize();
6103
- const change = {
6104
- type: "mutate",
6105
- id: id3,
6106
- patches
6107
- };
6108
- const { from, to } = await this.applyChange(change);
6109
- return { from, to };
6110
- }
6111
- applySerializedChanges(changes) {
6112
- return Promise.all(changes.map((change) => this.applyChange(change)));
6113
- }
6114
- unsubscribe(listener) {
6115
- this.listeners.delete(listener);
6116
- }
6117
- notifyListeners(events) {
6118
- for (const listener of this.listeners.values()) {
6119
- listener.callback(events);
6120
- }
6121
- }
6122
- }
6123
-
6124
- class ForkedStoreState extends StoreState {
6125
- master;
6126
- changedItems = new Map;
6127
- changes = [];
6128
- constructor(storeName, dataStorage, master) {
6129
- super(storeName, dataStorage, master.deserialize);
6130
- this.master = master;
6131
- }
6132
- async applyChangeAndReturnEvent(change) {
6133
- this.changes.push(change);
6134
- if (change.type === "set") {
6135
- const item = this.deserialize ? this.deserialize(change.data) : change.data;
6136
- this.changedItems.set(change.data._id, item);
6137
- return {
6138
- from: null,
6139
- to: item,
6140
- event: {
6141
- type: "set",
6142
- item: change.data,
6143
- id: change.data._id
6144
- }
6145
- };
6146
- }
6147
- if (change.type === "delete") {
6148
- const from = await this.find({ where: { _id: change.id } }).then((results) => results[0] || null);
6149
- this.changedItems.set(change.id, null);
6150
- return {
6151
- from,
6152
- to: null,
6153
- event: {
6154
- type: "delete",
6155
- item: null,
6156
- id: change.id
6157
- }
6158
- };
6159
- }
6160
- if (change.type === "modify") {
6161
- const existing = await this.find({
6162
- where: { _id: change.id }
6163
- }).then((results) => results[0]);
6164
- const updated = existing ? deepMerge(existing, change.data) : { _id: change.id, ...change.data };
6165
- const item = this.deserialize ? this.deserialize(updated) : updated;
6166
- this.changedItems.set(change.id, item);
6167
- return {
6168
- from: existing || null,
6169
- to: item,
6170
- event: {
6171
- type: "set",
6172
- item,
6173
- id: change.id
6174
- }
6175
- };
6176
- }
6177
- if (change.type === "mutate") {
6178
- const existing = await this.find({
6179
- where: { _id: change.id }
6180
- }).then((results) => results[0]);
6181
- const updated = apply(existing || {}, change.patches);
6182
- const item = this.deserialize ? this.deserialize(updated) : updated;
6183
- this.changedItems.set(change.id, item);
6184
- return {
6185
- from: existing || null,
6186
- to: item,
6187
- event: {
6188
- type: "set",
6189
- item,
6190
- id: change.id
6191
- }
6192
- };
6193
- }
6194
- throw new Error("Unknown change type");
6195
- }
6196
- async applyChange(change) {
6197
- const { event: event3, from, to } = await this.applyChangeAndReturnEvent(change);
6198
- this.notifyListeners([event3]);
6199
- return { from, to };
6200
- }
6201
- async applyChanges(changes) {
6202
- const events = [];
6203
- for (const change of changes) {
6204
- const { event: event3 } = await this.applyChangeAndReturnEvent(change);
6205
- if (event3)
6206
- events.push(event3);
6207
- }
6208
- if (events.length > 0) {
6209
- this.notifyListeners(events);
6210
- }
6211
- }
6212
- async find(options, listener) {
6213
- if (listener) {
6214
- this.listeners.set(listener, { callback: listener });
6215
- }
6216
- const parentResults = await this.master.find(options);
6217
- const results = new Map;
6218
- parentResults.forEach((item) => results.set(item._id, item));
6219
- for (const [id3, changedItem] of this.changedItems) {
6220
- if (changedItem === null) {
6221
- results.delete(id3);
6222
- continue;
6223
- }
6224
- const matches = !options.where || Object.entries(options.where).every(([key, value]) => changedItem[key] === value);
6225
- if (matches) {
6226
- results.set(id3, changedItem);
6227
- } else {
6228
- results.delete(id3);
6229
- }
6230
- }
6231
- return Array.from(results.values());
6232
- }
6233
- }
6234
-
6235
- class ForkedDataStorage extends DataStorage {
6236
- master;
6237
- stores = new Map;
6238
- constructor(master) {
6239
- super();
6240
- this.master = master;
6241
- }
6242
- getReadTransaction() {
6243
- return this.master.getReadTransaction();
6244
- }
6245
- getReadWriteTransaction() {
6246
- return this.master.getReadWriteTransaction();
6247
- }
6248
- getStore(storeName) {
6249
- if (this.stores.has(storeName))
6250
- return this.stores.get(storeName);
6251
- const masterStorage = this.master.getStore(storeName);
6252
- const storage = new ForkedStoreState(storeName, this, masterStorage);
6253
- this.stores.set(storeName, storage);
6254
- return storage;
6255
- }
6256
- fork() {
6257
- return new ForkedDataStorage(this);
6258
- }
6259
- async merge() {
6260
- const changes = Array.from(this.stores.values()).filter((store) => store.changes.length > 0).map((store) => ({
6261
- store: store.storeName,
6262
- changes: store.changes
6263
- }));
6264
- await this.master.commitChanges(changes);
6265
- }
6266
- }
6267
-
6268
- class MasterStoreState extends StoreState {
6269
- constructor(storeName, dataStorage, deserialize) {
6270
- super(storeName, dataStorage, deserialize);
6271
- }
6272
- async applyChangeAndReturnEvent(transaction, change) {
6273
- if (change.type === "set") {
6274
- await transaction.set(this.storeName, change.data);
6275
- const item = this.deserialize ? this.deserialize(change.data) : change.data;
6276
- return {
6277
- from: null,
6278
- to: item,
6279
- event: {
6280
- type: "set",
6281
- item: change.data,
6282
- id: change.data._id
6283
- }
6284
- };
6285
- }
6286
- if (change.type === "delete") {
6287
- await transaction.remove(this.storeName, change.id);
6288
- return {
6289
- from: null,
6290
- to: null,
6291
- event: {
6292
- type: "delete",
6293
- item: null,
6294
- id: change.id
6295
- }
6296
- };
6297
- }
6298
- if (change.type === "modify") {
6299
- const existing = await transaction.find(this.storeName, { where: { _id: change.id } }).then((results) => results[0]);
6300
- const updated = existing ? deepMerge(existing, change.data) : { _id: change.id, ...change.data };
6301
- await transaction.set(this.storeName, updated);
6302
- const item = this.deserialize ? this.deserialize(updated) : updated;
6303
- return {
6304
- from: null,
6305
- to: item,
6306
- event: {
6307
- type: "set",
6308
- item,
6309
- id: change.id
6310
- }
6311
- };
6312
- }
6313
- if (change.type === "mutate") {
6314
- const existing = await transaction.find(this.storeName, { where: { _id: change.id } }).then((results) => results[0]);
6315
- const updated = apply(existing || {}, change.patches);
6316
- await transaction.set(this.storeName, updated);
6317
- const item = this.deserialize ? this.deserialize(updated) : updated;
6318
- return {
6319
- from: null,
6320
- to: item,
6321
- event: {
6322
- type: "set",
6323
- item,
6324
- id: change.id
6325
- }
6326
- };
6327
- }
6328
- throw new Error("Unknown change type");
6329
- }
6330
- async applyChange(change) {
6331
- const transaction = await this.dataStorage.getReadWriteTransaction();
6332
- const { event: event3, from, to } = await this.applyChangeAndReturnEvent(transaction, change);
6333
- await transaction.commit();
6334
- this.notifyListeners([event3]);
6335
- return { from, to };
6336
- }
6337
- async applyChanges(changes) {
6338
- const transaction = await this.dataStorage.getReadWriteTransaction();
6339
- const events = [];
6340
- for (const change of changes) {
6341
- const { event: event3 } = await this.applyChangeAndReturnEvent(transaction, change);
6342
- if (event3)
6343
- events.push(event3);
6344
- }
6345
- await transaction.commit();
6346
- if (events.length > 0) {
6347
- this.notifyListeners(events);
6348
- }
6349
- }
6350
- async find(options, listener) {
6351
- if (listener) {
6352
- this.listeners.set(listener, { callback: listener });
6353
- }
6354
- const transaction = await this.dataStorage.getReadTransaction();
6355
- const results = await transaction.find(this.storeName, options);
6356
- return results.map((item) => this.deserialize ? this.deserialize(item) : item);
6357
- }
6358
- }
6359
-
6360
- class MasterDataStorage extends DataStorage {
6361
- dbAdapter;
6362
- arcContext;
6363
- stores = new Map;
6364
- rtcAdapter;
6365
- constructor(dbAdapter, rtcAdapterFactory, arcContext) {
6366
- super();
6367
- this.dbAdapter = dbAdapter;
6368
- this.arcContext = arcContext;
6369
- this.rtcAdapter = rtcAdapterFactory(this);
6370
- }
6371
- async getReadTransaction() {
6372
- return (await this.dbAdapter).readTransaction();
6373
- }
6374
- async getReadWriteTransaction() {
6375
- return (await this.dbAdapter).readWriteTransaction();
6376
- }
6377
- getStore(storeName) {
6378
- if (!this.stores.has(storeName)) {
6379
- this.stores.set(storeName, new MasterStoreState(storeName, this));
6380
- }
6381
- return this.stores.get(storeName);
6382
- }
6383
- async applyChanges(changes) {
6384
- return Promise.all(changes.map(({ store, changes: changes2 }) => this.getStore(store).applyChanges(changes2)));
6385
- }
6386
- applySerializedChanges(changes) {
6387
- return Promise.all(changes.map(({ store, changes: changes2 }) => this.getStore(store).applySerializedChanges(changes2)));
6388
- }
6389
- async commitChanges(changes) {
6390
- await Promise.all([
6391
- this.applyChanges(changes),
6392
- this.rtcAdapter.commitChanges(changes)
6393
- ]);
6394
- }
6395
- fork() {
6396
- return new ForkedDataStorage(this);
6397
- }
6398
- async sync(progressCallback) {
6399
- await this.rtcAdapter.sync(progressCallback);
6400
- }
6401
- }
6402
-
6403
- class SQLiteReadTransaction {
6404
- db;
6405
- tables;
6406
- constructor(db, tables) {
6407
- this.db = db;
6408
- this.tables = tables;
6409
- }
6410
- deserializeValue(value, column) {
6411
- if (value === null || value === undefined)
6412
- return null;
6413
- switch (column.type.toLowerCase()) {
6414
- case "json":
6415
- case "text": {
6416
- try {
6417
- const parsed = JSON.parse(value);
6418
- if (typeof parsed === "object" || Array.isArray(parsed)) {
6419
- return parsed;
6420
- }
6421
- return value;
6422
- } catch {
6423
- return value;
6424
- }
6425
- }
6426
- case "datetime":
6427
- case "timestamp":
6428
- return new Date(value);
6429
- default:
6430
- return value;
6431
- }
6432
- }
6433
- deserializeRow(row, table) {
6434
- const result = {};
6435
- for (const column of table.columns) {
6436
- const value = row[column.name];
6437
- result[column.name] = this.deserializeValue(value, column);
6438
- }
6439
- return result;
6440
- }
6441
- getId(store, id3) {
6442
- return id3;
6443
- }
6444
- buildWhereClause(where) {
6445
- if (!where) {
6446
- return { sql: "deleted != 1", params: [] };
6447
- }
6448
- const conditions = ["deleted != 1"];
6449
- const params = [];
6450
- Object.entries(where).forEach(([key, value]) => {
6451
- if (typeof value === "object" && value !== null) {
6452
- Object.entries(value).forEach(([operator, operand]) => {
6453
- switch (operator) {
6454
- case "$eq":
6455
- case "$ne":
6456
- case "$gt":
6457
- case "$gte":
6458
- case "$lt":
6459
- case "$lte":
6460
- conditions.push(`${key} ${this.getOperatorSymbol(operator)} ?`);
6461
- params.push(operand);
6462
- break;
6463
- case "$in":
6464
- case "$nin":
6465
- if (Array.isArray(operand)) {
6466
- conditions.push(`${key} ${operator === "$in" ? "IN" : "NOT IN"} (${operand.map(() => "?").join(", ")})`);
6467
- params.push(...operand);
6468
- }
6469
- break;
6470
- case "$exists":
6471
- if (typeof operand === "boolean") {
6472
- conditions.push(operand ? `${key} IS NOT NULL` : `${key} IS NULL`);
6473
- }
6474
- break;
6475
- }
6476
- });
6477
- } else {
6478
- conditions.push(`${key} = ?`);
6479
- params.push(value);
6480
- }
6481
- });
6482
- return {
6483
- sql: conditions.join(" AND "),
6484
- params
6485
- };
6486
- }
6487
- getOperatorSymbol(operator) {
6488
- const operators = {
6489
- $eq: "=",
6490
- $ne: "!=",
6491
- $gt: ">",
6492
- $gte: ">=",
6493
- $lt: "<",
6494
- $lte: "<="
6495
- };
6496
- return operators[operator] || "=";
6497
- }
6498
- buildOrderByClause(orderBy) {
6499
- if (!orderBy)
6500
- return "";
6501
- const orderClauses = Object.entries(orderBy).map(([key, direction]) => `${key} ${direction.toUpperCase()}`).join(", ");
6502
- return orderClauses ? `ORDER BY ${orderClauses}` : "";
6503
- }
6504
- async find(store, options) {
6505
- const { where, limit, offset, orderBy } = options || {};
6506
- const whereClause = this.buildWhereClause(where);
6507
- const orderByClause = this.buildOrderByClause(orderBy);
6508
- const table = this.tables.get(store);
6509
- if (!table) {
6510
- throw new Error(`Store ${store} not found`);
6511
- }
6512
- const query2 = `
6513
- SELECT *
6514
- FROM ${store}
6515
- WHERE ${whereClause.sql}
6516
- ${orderByClause}
6517
- ${limit ? `LIMIT ${limit}` : ""}
6518
- ${offset ? `OFFSET ${offset}` : ""}
6519
- `;
6520
- const rows = await this.db.exec(query2, whereClause.params);
6521
- return rows.map((row) => this.deserializeRow(row, table));
6522
- }
6523
- }
6524
-
6525
- class SQLiteReadWriteTransaction extends SQLiteReadTransaction {
6526
- async remove(store, id3) {
6527
- const table = this.tables.get(store);
6528
- if (!table) {
6529
- throw new Error(`Store ${store} not found`);
6530
- }
6531
- const query2 = `UPDATE ${store} SET deleted = 1, lastUpdate = ? WHERE ${table.primaryKey} = ?`;
6532
- await this.db.exec(query2, [new Date().toISOString(), id3]);
6533
- }
6534
- async set(store, item) {
6535
- const table = this.tables.get(store);
6536
- if (!table) {
6537
- throw new Error(`Store ${store} not found`);
6538
- }
6539
- const now = new Date().toISOString();
6540
- const columnNames = table.columns.map((col) => col.name);
6541
- const values = table.columns.map((column) => {
6542
- let value = item[column.name];
6543
- if (value === undefined && column.default !== undefined) {
6544
- value = column.default;
6545
- }
6546
- return this.serializeValue(value, column);
6547
- });
6548
- const placeholders = columnNames.map(() => "?").join(", ");
6549
- const sql = `
6550
- INSERT OR REPLACE INTO ${table.name}
6551
- (${columnNames.map((c) => `"${c}"`).join(", ")})
6552
- VALUES (${placeholders})
6553
- `;
6554
- await this.db.exec(sql, values);
6555
- }
6556
- async commit() {
6557
- return Promise.resolve();
6558
- }
6559
- serializeValue(value, column) {
6560
- if (value === null || value === undefined)
6561
- return null;
6562
- switch (column.type.toLowerCase()) {
6563
- case "json":
6564
- return JSON.stringify(value);
6565
- default:
6566
- if (value instanceof Date) {
6567
- return value.toISOString();
6568
- }
6569
- if (Array.isArray(value) || typeof value === "object") {
6570
- return JSON.stringify(value);
6571
- }
6572
- return value;
6573
- }
6574
- }
6575
- }
6576
-
6577
- class SQLiteAdapter {
6578
- db;
6579
- context;
6580
- tables = new Map;
6581
- constructor(db, context3) {
6582
- this.db = db;
6583
- this.context = context3;
6584
- this.context.elements.forEach((element3) => {
6585
- if ("storeSchema" in element3 && typeof element3.storeSchema === "function") {
6586
- element3.storeSchema().tables.forEach((table) => {
6587
- this.tables.set(table.name, table);
6588
- });
6589
- }
6590
- });
6591
- }
6592
- async initialize() {
6593
- const stores = new Set;
6594
- for (const element3 of this.context.elements) {
6595
- if ("storeSchema" in element3 && typeof element3.storeSchema === "function") {
6596
- const schema = element3.storeSchema();
6597
- stores.add(schema);
6598
- }
6599
- }
6600
- for (const schema of stores) {
6601
- for (const table of schema.tables) {
6602
- await this.createTableIfNotExists(table);
6603
- }
6604
- }
6605
- }
6606
- async createTableIfNotExists(table) {
6607
- const columns = table.columns.map((column) => {
6608
- const constraints = [];
6609
- if (!column.isOptional) {
6610
- constraints.push("NOT NULL");
6611
- }
6612
- if (column.default !== undefined) {
6613
- constraints.push(`DEFAULT ${JSON.stringify(column.default)}`);
6614
- }
6615
- if (column.name === table.primaryKey) {
6616
- constraints.push("PRIMARY KEY");
6617
- }
6618
- return `"${column.name}" ${column.type} ${constraints.join(" ")}`.trim();
6619
- });
6620
- const createTableSQL = `
6621
- CREATE TABLE IF NOT EXISTS ${table.name} (
6622
- ${columns.join(`,
6623
- `)}
6624
- )
6625
- `;
6626
- await this.db.exec(createTableSQL);
6627
- }
6628
- readWriteTransaction(stores) {
6629
- return new SQLiteReadWriteTransaction(this.db, this.tables);
6630
- }
6631
- readTransaction(stores) {
6632
- return new SQLiteReadTransaction(this.db, this.tables);
6633
- }
6634
- }
6635
- var createSQLiteAdapterFactory = (db) => {
6636
- return async (context3) => {
6637
- const adapter = new SQLiteAdapter(db, context3);
6638
- await adapter.initialize();
6639
- return adapter;
6640
- };
6641
- };
6642
- class EventPublisher {
6643
- context;
6644
- dataStorage;
6645
- authContext;
6646
- asyncEvents = [];
6647
- constructor(context3, dataStorage, authContext) {
6648
- this.context = context3;
6649
- this.dataStorage = dataStorage;
6650
- this.authContext = authContext;
6651
- }
6652
- async publishEvent(event3, commandDataStorage) {
6653
- const recursivePublishEvent = async (childEvent) => {
6654
- await this.publishEvent(childEvent, commandDataStorage);
6655
- };
6656
- const syncListeners = this.context.getSyncListeners(event3.type, this.authContext);
6657
- for (const listener3 of syncListeners) {
6658
- try {
6659
- await listener3(event3, commandDataStorage, recursivePublishEvent);
6660
- } catch (error) {
6661
- console.error("Sync listener failed:", error);
6662
- throw error;
6663
- }
6664
- }
6665
- const asyncListeners = this.context.getAsyncListeners(event3.type, this.authContext);
6666
- if (asyncListeners.length > 0) {
6667
- this.asyncEvents.push({
6668
- event: event3,
6669
- listeners: asyncListeners,
6670
- authContext: this.authContext
6671
- });
6672
- }
6673
- }
6674
- async runAsyncListeners() {
6675
- const allAsyncTasks = this.asyncEvents.flatMap(({ event: event3, listeners, authContext }) => listeners.map(async (listener3) => {
6676
- const listenerFork = this.dataStorage.fork();
6677
- const asyncPublishEvent = async (childEvent) => {
6678
- const childPublisher = new EventPublisher(this.context, listenerFork, authContext);
6679
- await childPublisher.publishEvent(childEvent, listenerFork);
6680
- await childPublisher.runAsyncListeners();
6681
- };
6682
- try {
6683
- await listener3(event3, listenerFork, asyncPublishEvent);
6684
- await listenerFork.merge();
6685
- } catch (error) {
6686
- console.error("Async listener failed:", error);
6687
- }
6688
- }));
6689
- await Promise.all(allAsyncTasks);
6690
- this.asyncEvents = [];
6691
- }
6692
- }
6693
-
6694
- class ModelBase {
6695
- token = null;
6696
- setAuthToken(token) {
6697
- this.token = token;
6698
- }
6699
- }
6700
-
6701
- class Model extends ModelBase {
6702
- context;
6703
- dataStorage;
6704
- catchErrorCallback;
6705
- queryCache = new QueryCache;
6706
- constructor(context3, dataStorage, catchErrorCallback) {
6707
- super();
6708
- this.context = context3;
6709
- this.dataStorage = dataStorage;
6710
- this.catchErrorCallback = catchErrorCallback;
6711
- }
6712
- async query(queryBuilderFn, authContext) {
6713
- const queryContext = new QueryBuilderContext(this.queryCache, this.dataStorage);
6714
- const queryBuilder = this.context.queryBuilder(queryContext, authContext);
6715
- const query2 = queryBuilderFn(queryBuilder).toQuery(queryContext);
6716
- return query2.run(this.dataStorage);
6717
- }
6718
- subscribe(queryBuilderFn, callback, authContext) {
6719
- const queryContext = new QueryBuilderContext(this.queryCache, this.dataStorage);
6720
- const queryBuilder = this.context.queryBuilder(queryContext, authContext);
6721
- const query2 = queryBuilderFn(queryBuilder).toQuery(queryContext);
6722
- query2.subscribe(callback);
6723
- const runPromise = query2.run(this.dataStorage);
6724
- runPromise.then((result) => {
6725
- callback(result);
6726
- });
6727
- return {
6728
- unsubscribe: () => {
6729
- query2.unsubscribe(callback);
6730
- },
6731
- result: runPromise
6732
- };
6733
- }
6734
- commands(authContext) {
6735
- return new Proxy({}, {
6736
- get: (_, name) => {
6737
- const element3 = this.context.elements.find((element4) => element4.name === name);
6738
- if (!element3) {
6739
- throw new Error(`Element "${String(name)}" not found`);
6740
- }
6741
- if (!element3.commandClient) {
6742
- throw new Error(`Element "${String(name)}" does not have a command client`);
6743
- }
6744
- return async (arg) => {
6745
- const forkedDataStorage = this.dataStorage.fork();
6746
- const eventPublisher = new EventPublisher(this.context, this.dataStorage, authContext);
6747
- const publishEvent = async (event3) => {
6748
- await eventPublisher.publishEvent(event3, forkedDataStorage);
6749
- };
6750
- const commandContext = this.context.commandContext(forkedDataStorage, publishEvent, authContext);
6751
- try {
6752
- const result = await element3.commandClient(commandContext, authContext)(arg);
6753
- await forkedDataStorage.merge();
6754
- eventPublisher.runAsyncListeners();
6755
- return result;
6756
- } catch (error) {
6757
- this.catchErrorCallback(error);
6758
- return error;
6759
- }
6760
- };
6761
- }
6762
- });
6763
- }
6764
- routes(authContext) {
6765
- return new Proxy({}, {
6766
- get: (_, name) => {
6767
- const element3 = this.context.elements.find((element4) => element4.name === name);
6768
- if (!element3) {
6769
- throw new Error(`Route element "${String(name)}" not found`);
6770
- }
6771
- if (typeof element3.getHandler !== "function") {
6772
- throw new Error(`Element "${String(name)}" does not have route handlers`);
6773
- }
6774
- return async (method, req, routeParams, url) => {
6775
- const handler = element3.getHandler(method);
6776
- if (!handler) {
6777
- throw new Error(`Method ${method} not allowed for route ${String(name)}`);
6778
- }
6779
- const forkedDataStorage = this.dataStorage.fork();
6780
- const eventPublisher = new EventPublisher(this.context, this.dataStorage, authContext);
6781
- const publishEvent = async (event3) => {
6782
- await eventPublisher.publishEvent(event3, forkedDataStorage);
6783
- };
6784
- const commandContext = this.context.commandContext(forkedDataStorage, publishEvent, authContext);
6785
- try {
6786
- const result = await handler(commandContext, req, routeParams, url);
6787
- await forkedDataStorage.merge();
6788
- eventPublisher.runAsyncListeners();
6789
- return result;
6790
- } catch (error) {
6791
- this.catchErrorCallback(error);
6792
- throw error;
6793
- }
6794
- };
6795
- }
6796
- });
6797
- }
6798
- get $debug() {
6799
- return {};
6800
- }
6801
- }
6802
- class ArcViewQuery extends ArcSerializableQuery {
6803
- view;
6804
- bindedChangeHandler = this.changeHandler.bind(this);
6805
- store;
6806
- constructor(view, params) {
6807
- super(params);
6808
- this.view = view;
6809
- }
6810
- async run(dataStorage) {
6811
- const store = dataStorage.getStore(this.view.name);
6812
- this.store = store;
6813
- const result = await this.fetch(store);
6814
- this.lastResult = result;
6815
- return result;
6816
- }
6817
- changeHandler(changes) {
6818
- let resultChanged = false;
6819
- for (const change of changes) {
6820
- const response = this.onChange(change);
6821
- if (response !== false) {
6822
- this.lastResult = response;
6823
- resultChanged = true;
6824
- }
6825
- }
6826
- if (resultChanged)
6827
- this.nextResult(this.lastResult);
6828
- }
6829
- }
3644
+ // host.ts
3645
+ import {
3646
+ MasterDataStorage,
3647
+ Model,
3648
+ QueryBuilderContext,
3649
+ QueryCache
3650
+ } from "@arcote.tech/arc";
6830
3651
 
6831
3652
  // auth/jwt.ts
6832
3653
  var import_jsonwebtoken = __toESM(require_jsonwebtoken(), 1);
@@ -6898,35 +3719,35 @@ class RTCHost {
6898
3719
  }
6899
3720
  setNestedProperty(obj, path, value) {
6900
3721
  const keys = path.split(/[\[\]]+/).filter((key) => key !== "");
6901
- let current2 = obj;
3722
+ let current = obj;
6902
3723
  for (let i = 0;i < keys.length - 1; i++) {
6903
3724
  const key = keys[i];
6904
3725
  const nextKey = keys[i + 1];
6905
3726
  if (!isNaN(Number(nextKey))) {
6906
- if (!current2[key]) {
6907
- current2[key] = [];
3727
+ if (!current[key]) {
3728
+ current[key] = [];
6908
3729
  }
6909
- if (!current2[key][Number(nextKey)]) {
6910
- current2[key][Number(nextKey)] = {};
3730
+ if (!current[key][Number(nextKey)]) {
3731
+ current[key][Number(nextKey)] = {};
6911
3732
  }
6912
- current2 = current2[key][Number(nextKey)];
3733
+ current = current[key][Number(nextKey)];
6913
3734
  i++;
6914
3735
  } else {
6915
- if (!current2[key]) {
6916
- current2[key] = {};
3736
+ if (!current[key]) {
3737
+ current[key] = {};
6917
3738
  }
6918
- current2 = current2[key];
3739
+ current = current[key];
6919
3740
  }
6920
3741
  }
6921
3742
  const finalKey = keys[keys.length - 1];
6922
3743
  if (!isNaN(Number(finalKey))) {
6923
3744
  const parentKey = keys[keys.length - 2];
6924
- if (!current2[parentKey]) {
6925
- current2[parentKey] = [];
3745
+ if (!current[parentKey]) {
3746
+ current[parentKey] = [];
6926
3747
  }
6927
- current2[parentKey][Number(finalKey)] = value;
3748
+ current[parentKey][Number(finalKey)] = value;
6928
3749
  } else {
6929
- current2[finalKey] = value;
3750
+ current[finalKey] = value;
6930
3751
  }
6931
3752
  }
6932
3753
  async handleCommand(req) {
@@ -7130,7 +3951,6 @@ class RTCHost {
7130
3951
  }
7131
3952
  } : {};
7132
3953
  const syncResults = [];
7133
- for (const collection of this.context.elements.filter((element) => element instanceof ArcCollection).concat([{ name: "state" }])) {}
7134
3954
  return new Response(JSON.stringify({
7135
3955
  results: syncResults,
7136
3956
  syncDate: syncDate.toISOString()
@@ -7163,6 +3983,9 @@ var rtcHostFactory = (context, dbAdapter) => () => {
7163
3983
  };
7164
3984
 
7165
3985
  // sqliteAdapter.ts
3986
+ import {
3987
+ createSQLiteAdapterFactory
3988
+ } from "@arcote.tech/arc";
7166
3989
  import { Database } from "bun:sqlite";
7167
3990
 
7168
3991
  class BunSQLiteDatabase {
@@ -7191,11 +4014,57 @@ var sqliteAdapterFactory = (dbName) => {
7191
4014
  };
7192
4015
  };
7193
4016
 
4017
+ // postgresAdapter.ts
4018
+ import {
4019
+ createPostgreSQLAdapterFactory
4020
+ } from "@arcote.tech/arc";
4021
+ var {SQL } = globalThis.Bun;
4022
+
4023
+ class BunPostgreSQLDatabase {
4024
+ connectionString;
4025
+ sql;
4026
+ constructor(connectionString) {
4027
+ this.connectionString = connectionString;
4028
+ this.sql = new SQL(this.connectionString);
4029
+ }
4030
+ async exec(query, params) {
4031
+ try {
4032
+ const result = await this.sql.unsafe(query, params);
4033
+ return result;
4034
+ } catch (error) {
4035
+ console.error("PostgreSQL error:", error, query, params);
4036
+ throw error;
4037
+ }
4038
+ }
4039
+ async execBatch(queries) {
4040
+ try {
4041
+ return await this.sql.transaction(async (tx) => {
4042
+ for (const query of queries) {
4043
+ await tx.unsafe(query.sql, query.params);
4044
+ }
4045
+ });
4046
+ } catch (error) {
4047
+ console.error("PostgreSQL batch transaction error:", error);
4048
+ throw error;
4049
+ }
4050
+ }
4051
+ }
4052
+ var postgreSQLAdapterFactory = (connectionString) => {
4053
+ return async (context) => {
4054
+ const pgDb = new BunPostgreSQLDatabase(connectionString);
4055
+ return createPostgreSQLAdapterFactory(pgDb)(context);
4056
+ };
4057
+ };
4058
+
7194
4059
  // index.ts
7195
4060
  function hostLiveModel(context, options) {
7196
4061
  const dbAdapterFactory = sqliteAdapterFactory(options.db);
7197
4062
  rtcHostFactory(context, dbAdapterFactory(context))();
7198
4063
  }
7199
4064
  export {
4065
+ postgreSQLAdapterFactory,
7200
4066
  hostLiveModel
7201
4067
  };
4068
+
4069
+ //# debugId=3170B378AC8CEA7664756E2164756E21
4070
+ //# sourceMappingURL=index.js.map