@arcote.tech/arc-host 0.3.1 → 0.3.2

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
@@ -3855,7 +3855,17 @@ class ContextHandler {
3855
3855
  throw new Error(`Command '${commandName}' not found`);
3856
3856
  }
3857
3857
  this.authAdapter.setToken(rawToken);
3858
- return await command(params);
3858
+ try {
3859
+ return await command(params);
3860
+ } catch (error) {
3861
+ console.error(`[ARC] Command '${commandName}' failed:`);
3862
+ console.error(`[ARC] Params:`, JSON.stringify(params, null, 2));
3863
+ console.error(`[ARC] Error:`, error);
3864
+ if (error instanceof Error) {
3865
+ console.error(`[ARC] Stack:`, error.stack);
3866
+ }
3867
+ throw error;
3868
+ }
3859
3869
  }
3860
3870
  async persistEvents(events, clientId, token) {
3861
3871
  const persistedEvents = [];
@@ -4114,7 +4124,7 @@ class ArcHost {
4114
4124
  return self.handleHttpCommand(req, url, corsHeaders, token);
4115
4125
  }
4116
4126
  if (url.pathname.startsWith("/query/") && req.method === "POST") {
4117
- return self.handleHttpQuery(req, url, tokenPayload, corsHeaders);
4127
+ return self.handleHttpQuery(req, url, tokenPayload, corsHeaders, token);
4118
4128
  }
4119
4129
  if (url.pathname.startsWith("/stream/") && req.method === "GET") {
4120
4130
  return self.handleHttpStream(req, url, tokenPayload, corsHeaders, token);
@@ -4122,6 +4132,9 @@ class ArcHost {
4122
4132
  if (url.pathname === "/sync/events" && req.method === "POST") {
4123
4133
  return self.handleHttpEventSync(req, tokenPayload, corsHeaders);
4124
4134
  }
4135
+ if (url.pathname.startsWith("/route/")) {
4136
+ return self.handleHttpRoute(req, url, tokenPayload, corsHeaders, token);
4137
+ }
4125
4138
  return new Response("Not Found", { status: 404, headers: corsHeaders });
4126
4139
  },
4127
4140
  websocket: {
@@ -4166,13 +4179,17 @@ class ArcHost {
4166
4179
  headers: { ...corsHeaders, "Content-Type": "application/json" }
4167
4180
  });
4168
4181
  } catch (error) {
4182
+ console.error(`[ARC HTTP] Command '${commandName}' error:`, error);
4183
+ if (error instanceof Error && error.stack) {
4184
+ console.error(`[ARC HTTP] Stack trace:`, error.stack);
4185
+ }
4169
4186
  return new Response(JSON.stringify({ error: error.message }), {
4170
4187
  status: 500,
4171
4188
  headers: { ...corsHeaders, "Content-Type": "application/json" }
4172
4189
  });
4173
4190
  }
4174
4191
  }
4175
- async handleHttpQuery(req, url, token, corsHeaders) {
4192
+ async handleHttpQuery(req, url, _token, corsHeaders, rawToken) {
4176
4193
  const viewName = url.pathname.split("/query/")[1];
4177
4194
  if (!viewName) {
4178
4195
  return new Response("Invalid query path", {
@@ -4182,9 +4199,18 @@ class ArcHost {
4182
4199
  }
4183
4200
  try {
4184
4201
  const params = await req.json();
4185
- const dataStorage = this.contextHandler.getDataStorage();
4186
- const tx = await dataStorage.getReadTransaction();
4187
- const result = await tx.find(viewName, params);
4202
+ const viewElement = this.contextHandler.getModel().context.get(viewName);
4203
+ if (!viewElement || !viewElement.queryContext) {
4204
+ return new Response(JSON.stringify({ error: "View not found" }), {
4205
+ status: 404,
4206
+ headers: { ...corsHeaders, "Content-Type": "application/json" }
4207
+ });
4208
+ }
4209
+ this.contextHandler.setAuthToken(rawToken);
4210
+ const model = this.contextHandler.getModel();
4211
+ const adapters = model.getAdapters();
4212
+ const queryCtx = viewElement.queryContext(adapters);
4213
+ const result = await queryCtx.find(params);
4188
4214
  return new Response(JSON.stringify(result), {
4189
4215
  headers: { ...corsHeaders, "Content-Type": "application/json" }
4190
4216
  });
@@ -4305,3755 +4331,102 @@ class ArcHost {
4305
4331
  });
4306
4332
  }
4307
4333
  }
4308
- stop() {
4309
- for (const conn of this.streamConnections.values()) {
4310
- conn.unsubscribe();
4311
- }
4312
- this.streamConnections.clear();
4313
- this.server?.stop();
4314
- }
4315
- }
4316
- // ../adapters/db/sqlite/dist/index.js
4317
- import { Database } from "bun:sqlite";
4318
- var Operation = {
4319
- Remove: "remove",
4320
- Replace: "replace",
4321
- Add: "add"
4322
- };
4323
- var PROXY_DRAFT = Symbol.for("__MUTATIVE_PROXY_DRAFT__");
4324
- var RAW_RETURN_SYMBOL = Symbol("__MUTATIVE_RAW_RETURN_SYMBOL__");
4325
- var iteratorSymbol = Symbol.iterator;
4326
- var dataTypes = {
4327
- mutable: "mutable",
4328
- immutable: "immutable"
4329
- };
4330
- var internal = {};
4331
- function has(target, key) {
4332
- return target instanceof Map ? target.has(key) : Object.prototype.hasOwnProperty.call(target, key);
4333
- }
4334
- function getDescriptor(target, key) {
4335
- if (key in target) {
4336
- let prototype = Reflect.getPrototypeOf(target);
4337
- while (prototype) {
4338
- const descriptor = Reflect.getOwnPropertyDescriptor(prototype, key);
4339
- if (descriptor)
4340
- return descriptor;
4341
- prototype = Reflect.getPrototypeOf(prototype);
4342
- }
4343
- }
4344
- return;
4345
- }
4346
- function isBaseSetInstance(obj) {
4347
- return Object.getPrototypeOf(obj) === Set.prototype;
4348
- }
4349
- function isBaseMapInstance(obj) {
4350
- return Object.getPrototypeOf(obj) === Map.prototype;
4351
- }
4352
- function latest(proxyDraft) {
4353
- var _a;
4354
- return (_a = proxyDraft.copy) !== null && _a !== undefined ? _a : proxyDraft.original;
4355
- }
4356
- function isDraft(target) {
4357
- return !!getProxyDraft(target);
4358
- }
4359
- function getProxyDraft(value) {
4360
- if (typeof value !== "object")
4361
- return null;
4362
- return value === null || value === undefined ? undefined : value[PROXY_DRAFT];
4363
- }
4364
- function getValue(value) {
4365
- var _a;
4366
- const proxyDraft = getProxyDraft(value);
4367
- return proxyDraft ? (_a = proxyDraft.copy) !== null && _a !== undefined ? _a : proxyDraft.original : value;
4368
- }
4369
- function isDraftable(value, options) {
4370
- if (!value || typeof value !== "object")
4371
- return false;
4372
- let markResult;
4373
- 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");
4374
- }
4375
- function getPath(target, path = []) {
4376
- if (Object.hasOwnProperty.call(target, "key")) {
4377
- const parentCopy = target.parent.copy;
4378
- const proxyDraft = getProxyDraft(get(parentCopy, target.key));
4379
- if (proxyDraft !== null && (proxyDraft === null || proxyDraft === undefined ? undefined : proxyDraft.original) !== target.original) {
4380
- return null;
4381
- }
4382
- const isSet = target.parent.type === 3;
4383
- const key = isSet ? Array.from(target.parent.setMap.keys()).indexOf(target.key) : target.key;
4384
- if (!(isSet && parentCopy.size > key || has(parentCopy, key)))
4385
- return null;
4386
- path.push(key);
4387
- }
4388
- if (target.parent) {
4389
- return getPath(target.parent, path);
4390
- }
4391
- path.reverse();
4392
- try {
4393
- resolvePath(target.copy, path);
4394
- } catch (e) {
4395
- return null;
4396
- }
4397
- return path;
4398
- }
4399
- function getType(target) {
4400
- if (Array.isArray(target))
4401
- return 1;
4402
- if (target instanceof Map)
4403
- return 2;
4404
- if (target instanceof Set)
4405
- return 3;
4406
- return 0;
4407
- }
4408
- function get(target, key) {
4409
- return getType(target) === 2 ? target.get(key) : target[key];
4410
- }
4411
- function set(target, key, value) {
4412
- const type = getType(target);
4413
- if (type === 2) {
4414
- target.set(key, value);
4415
- } else {
4416
- target[key] = value;
4417
- }
4418
- }
4419
- function peek(target, key) {
4420
- const state = getProxyDraft(target);
4421
- const source = state ? latest(state) : target;
4422
- return source[key];
4423
- }
4424
- function isEqual(x, y) {
4425
- if (x === y) {
4426
- return x !== 0 || 1 / x === 1 / y;
4427
- } else {
4428
- return x !== x && y !== y;
4429
- }
4430
- }
4431
- function revokeProxy(proxyDraft) {
4432
- if (!proxyDraft)
4433
- return;
4434
- while (proxyDraft.finalities.revoke.length > 0) {
4435
- const revoke = proxyDraft.finalities.revoke.pop();
4436
- revoke();
4437
- }
4438
- }
4439
- function escapePath(path, pathAsArray) {
4440
- return pathAsArray ? path : [""].concat(path).map((_item) => {
4441
- const item = `${_item}`;
4442
- if (item.indexOf("/") === -1 && item.indexOf("~") === -1)
4443
- return item;
4444
- return item.replace(/~/g, "~0").replace(/\//g, "~1");
4445
- }).join("/");
4446
- }
4447
- function unescapePath(path) {
4448
- if (Array.isArray(path))
4449
- return path;
4450
- return path.split("/").map((_item) => _item.replace(/~1/g, "/").replace(/~0/g, "~")).slice(1);
4451
- }
4452
- function resolvePath(base, path) {
4453
- for (let index = 0;index < path.length - 1; index += 1) {
4454
- const key = path[index];
4455
- base = get(getType(base) === 3 ? Array.from(base) : base, key);
4456
- if (typeof base !== "object") {
4457
- throw new Error(`Cannot resolve patch at '${path.join("/")}'.`);
4458
- }
4459
- }
4460
- return base;
4461
- }
4462
- function strictCopy(target) {
4463
- const copy = Object.create(Object.getPrototypeOf(target));
4464
- Reflect.ownKeys(target).forEach((key) => {
4465
- let desc = Reflect.getOwnPropertyDescriptor(target, key);
4466
- if (desc.enumerable && desc.configurable && desc.writable) {
4467
- copy[key] = target[key];
4468
- return;
4469
- }
4470
- if (!desc.writable) {
4471
- desc.writable = true;
4472
- desc.configurable = true;
4473
- }
4474
- if (desc.get || desc.set)
4475
- desc = {
4476
- configurable: true,
4477
- writable: true,
4478
- enumerable: desc.enumerable,
4479
- value: target[key]
4480
- };
4481
- Reflect.defineProperty(copy, key, desc);
4482
- });
4483
- return copy;
4484
- }
4485
- var propIsEnum = Object.prototype.propertyIsEnumerable;
4486
- function shallowCopy(original, options) {
4487
- let markResult;
4488
- if (Array.isArray(original)) {
4489
- return Array.prototype.concat.call(original);
4490
- } else if (original instanceof Set) {
4491
- if (!isBaseSetInstance(original)) {
4492
- const SubClass = Object.getPrototypeOf(original).constructor;
4493
- return new SubClass(original.values());
4494
- }
4495
- return Set.prototype.difference ? Set.prototype.difference.call(original, new Set) : new Set(original.values());
4496
- } else if (original instanceof Map) {
4497
- if (!isBaseMapInstance(original)) {
4498
- const SubClass = Object.getPrototypeOf(original).constructor;
4499
- return new SubClass(original);
4500
- }
4501
- return new Map(original);
4502
- } else if ((options === null || options === undefined ? undefined : options.mark) && (markResult = options.mark(original, dataTypes), markResult !== undefined) && markResult !== dataTypes.mutable) {
4503
- if (markResult === dataTypes.immutable) {
4504
- return strictCopy(original);
4505
- } else if (typeof markResult === "function") {
4506
- if (options.enablePatches || options.enableAutoFreeze) {
4507
- throw new Error(`You can't use mark and patches or auto freeze together.`);
4508
- }
4509
- return markResult();
4510
- }
4511
- throw new Error(`Unsupported mark result: ${markResult}`);
4512
- } else if (typeof original === "object" && Object.getPrototypeOf(original) === Object.prototype) {
4513
- const copy = {};
4514
- Object.keys(original).forEach((key) => {
4515
- copy[key] = original[key];
4516
- });
4517
- Object.getOwnPropertySymbols(original).forEach((key) => {
4518
- if (propIsEnum.call(original, key)) {
4519
- copy[key] = original[key];
4520
- }
4521
- });
4522
- return copy;
4523
- } else {
4524
- throw new Error(`Please check mark() to ensure that it is a stable marker draftable function.`);
4525
- }
4526
- }
4527
- function ensureShallowCopy(target) {
4528
- if (target.copy)
4529
- return;
4530
- target.copy = shallowCopy(target.original, target.options);
4531
- }
4532
- function deepClone(target) {
4533
- if (!isDraftable(target))
4534
- return getValue(target);
4535
- if (Array.isArray(target))
4536
- return target.map(deepClone);
4537
- if (target instanceof Map) {
4538
- const iterable = Array.from(target.entries()).map(([k, v]) => [
4539
- k,
4540
- deepClone(v)
4541
- ]);
4542
- if (!isBaseMapInstance(target)) {
4543
- const SubClass = Object.getPrototypeOf(target).constructor;
4544
- return new SubClass(iterable);
4545
- }
4546
- return new Map(iterable);
4547
- }
4548
- if (target instanceof Set) {
4549
- const iterable = Array.from(target).map(deepClone);
4550
- if (!isBaseSetInstance(target)) {
4551
- const SubClass = Object.getPrototypeOf(target).constructor;
4552
- return new SubClass(iterable);
4553
- }
4554
- return new Set(iterable);
4555
- }
4556
- const copy = Object.create(Object.getPrototypeOf(target));
4557
- for (const key in target)
4558
- copy[key] = deepClone(target[key]);
4559
- return copy;
4560
- }
4561
- function cloneIfNeeded(target) {
4562
- return isDraft(target) ? deepClone(target) : target;
4563
- }
4564
- function markChanged(proxyDraft) {
4565
- var _a;
4566
- proxyDraft.assignedMap = (_a = proxyDraft.assignedMap) !== null && _a !== undefined ? _a : new Map;
4567
- if (!proxyDraft.operated) {
4568
- proxyDraft.operated = true;
4569
- if (proxyDraft.parent) {
4570
- markChanged(proxyDraft.parent);
4571
- }
4572
- }
4573
- }
4574
- function throwFrozenError() {
4575
- throw new Error("Cannot modify frozen object");
4576
- }
4577
- function deepFreeze(target, subKey, updatedValues, stack, keys) {
4578
- {
4579
- updatedValues = updatedValues !== null && updatedValues !== undefined ? updatedValues : new WeakMap;
4580
- stack = stack !== null && stack !== undefined ? stack : [];
4581
- keys = keys !== null && keys !== undefined ? keys : [];
4582
- const value = updatedValues.has(target) ? updatedValues.get(target) : target;
4583
- if (stack.length > 0) {
4584
- const index = stack.indexOf(value);
4585
- if (value && typeof value === "object" && index !== -1) {
4586
- if (stack[0] === value) {
4587
- throw new Error(`Forbids circular reference`);
4588
- }
4589
- throw new Error(`Forbids circular reference: ~/${keys.slice(0, index).map((key, index2) => {
4590
- if (typeof key === "symbol")
4591
- return `[${key.toString()}]`;
4592
- const parent = stack[index2];
4593
- if (typeof key === "object" && (parent instanceof Map || parent instanceof Set))
4594
- return Array.from(parent.keys()).indexOf(key);
4595
- return key;
4596
- }).join("/")}`);
4597
- }
4598
- stack.push(value);
4599
- keys.push(subKey);
4600
- } else {
4601
- stack.push(value);
4602
- }
4603
- }
4604
- if (Object.isFrozen(target) || isDraft(target)) {
4605
- {
4606
- stack.pop();
4607
- keys.pop();
4608
- }
4609
- return;
4610
- }
4611
- const type = getType(target);
4612
- switch (type) {
4613
- case 2:
4614
- for (const [key, value] of target) {
4615
- deepFreeze(key, key, updatedValues, stack, keys);
4616
- deepFreeze(value, key, updatedValues, stack, keys);
4617
- }
4618
- target.set = target.clear = target.delete = throwFrozenError;
4619
- break;
4620
- case 3:
4621
- for (const value of target) {
4622
- deepFreeze(value, value, updatedValues, stack, keys);
4623
- }
4624
- target.add = target.clear = target.delete = throwFrozenError;
4625
- break;
4626
- case 1:
4627
- Object.freeze(target);
4628
- let index = 0;
4629
- for (const value of target) {
4630
- deepFreeze(value, index, updatedValues, stack, keys);
4631
- index += 1;
4632
- }
4633
- break;
4634
- default:
4635
- Object.freeze(target);
4636
- Object.keys(target).forEach((name) => {
4637
- const value = target[name];
4638
- deepFreeze(value, name, updatedValues, stack, keys);
4639
- });
4640
- }
4641
- {
4642
- stack.pop();
4643
- keys.pop();
4644
- }
4645
- }
4646
- function forEach(target, iter) {
4647
- const type = getType(target);
4648
- if (type === 0) {
4649
- Reflect.ownKeys(target).forEach((key) => {
4650
- iter(key, target[key], target);
4651
- });
4652
- } else if (type === 1) {
4653
- let index = 0;
4654
- for (const entry of target) {
4655
- iter(index, entry, target);
4656
- index += 1;
4657
- }
4658
- } else {
4659
- target.forEach((entry, index) => iter(index, entry, target));
4660
- }
4661
- }
4662
- function handleValue(target, handledSet, options) {
4663
- if (isDraft(target) || !isDraftable(target, options) || handledSet.has(target) || Object.isFrozen(target))
4664
- return;
4665
- const isSet = target instanceof Set;
4666
- const setMap = isSet ? new Map : undefined;
4667
- handledSet.add(target);
4668
- forEach(target, (key, value) => {
4669
- var _a;
4670
- if (isDraft(value)) {
4671
- const proxyDraft = getProxyDraft(value);
4672
- ensureShallowCopy(proxyDraft);
4673
- const updatedValue = ((_a = proxyDraft.assignedMap) === null || _a === undefined ? undefined : _a.size) || proxyDraft.operated ? proxyDraft.copy : proxyDraft.original;
4674
- set(isSet ? setMap : target, key, updatedValue);
4675
- } else {
4676
- handleValue(value, handledSet, options);
4677
- }
4678
- });
4679
- if (setMap) {
4680
- const set2 = target;
4681
- const values = Array.from(set2);
4682
- set2.clear();
4683
- values.forEach((value) => {
4684
- set2.add(setMap.has(value) ? setMap.get(value) : value);
4685
- });
4686
- }
4687
- }
4688
- function finalizeAssigned(proxyDraft, key) {
4689
- const copy = proxyDraft.type === 3 ? proxyDraft.setMap : proxyDraft.copy;
4690
- if (proxyDraft.finalities.revoke.length > 1 && proxyDraft.assignedMap.get(key) && copy) {
4691
- handleValue(get(copy, key), proxyDraft.finalities.handledSet, proxyDraft.options);
4692
- }
4693
- }
4694
- function finalizeSetValue(target) {
4695
- if (target.type === 3 && target.copy) {
4696
- target.copy.clear();
4697
- target.setMap.forEach((value) => {
4698
- target.copy.add(getValue(value));
4699
- });
4700
- }
4701
- }
4702
- function finalizePatches(target, generatePatches, patches, inversePatches) {
4703
- const shouldFinalize = target.operated && target.assignedMap && target.assignedMap.size > 0 && !target.finalized;
4704
- if (shouldFinalize) {
4705
- if (patches && inversePatches) {
4706
- const basePath = getPath(target);
4707
- if (basePath) {
4708
- generatePatches(target, basePath, patches, inversePatches);
4709
- }
4710
- }
4711
- target.finalized = true;
4712
- }
4713
- }
4714
- function markFinalization(target, key, value, generatePatches) {
4715
- const proxyDraft = getProxyDraft(value);
4716
- if (proxyDraft) {
4717
- if (!proxyDraft.callbacks) {
4718
- proxyDraft.callbacks = [];
4719
- }
4720
- proxyDraft.callbacks.push((patches, inversePatches) => {
4721
- var _a;
4722
- const copy = target.type === 3 ? target.setMap : target.copy;
4723
- if (isEqual(get(copy, key), value)) {
4724
- let updatedValue = proxyDraft.original;
4725
- if (proxyDraft.copy) {
4726
- updatedValue = proxyDraft.copy;
4727
- }
4728
- finalizeSetValue(target);
4729
- finalizePatches(target, generatePatches, patches, inversePatches);
4730
- if (target.options.enableAutoFreeze) {
4731
- target.options.updatedValues = (_a = target.options.updatedValues) !== null && _a !== undefined ? _a : new WeakMap;
4732
- target.options.updatedValues.set(updatedValue, proxyDraft.original);
4334
+ async handleHttpRoute(req, url, tokenPayload, corsHeaders, rawToken) {
4335
+ const method = req.method;
4336
+ const context = this.contextHandler.getModel().context;
4337
+ let matchedRoute = null;
4338
+ let routeParams = {};
4339
+ for (const element of context.elements) {
4340
+ if (element && typeof element.matchesPath === "function") {
4341
+ const route = element;
4342
+ const match = route.matchesPath(url.pathname);
4343
+ if (match.matches) {
4344
+ matchedRoute = route;
4345
+ routeParams = match.params;
4346
+ break;
4733
4347
  }
4734
- set(copy, key, updatedValue);
4735
- }
4736
- });
4737
- if (target.options.enableAutoFreeze) {
4738
- if (proxyDraft.finalities !== target.finalities) {
4739
- target.options.enableAutoFreeze = false;
4740
- }
4741
- }
4742
- }
4743
- if (isDraftable(value, target.options)) {
4744
- target.finalities.draft.push(() => {
4745
- const copy = target.type === 3 ? target.setMap : target.copy;
4746
- if (isEqual(get(copy, key), value)) {
4747
- finalizeAssigned(target, key);
4748
- }
4749
- });
4750
- }
4751
- }
4752
- function generateArrayPatches(proxyState, basePath, patches, inversePatches, pathAsArray) {
4753
- let { original, assignedMap, options } = proxyState;
4754
- let copy = proxyState.copy;
4755
- if (copy.length < original.length) {
4756
- [original, copy] = [copy, original];
4757
- [patches, inversePatches] = [inversePatches, patches];
4758
- }
4759
- for (let index = 0;index < original.length; index += 1) {
4760
- if (assignedMap.get(index.toString()) && copy[index] !== original[index]) {
4761
- const _path = basePath.concat([index]);
4762
- const path = escapePath(_path, pathAsArray);
4763
- patches.push({
4764
- op: Operation.Replace,
4765
- path,
4766
- value: cloneIfNeeded(copy[index])
4767
- });
4768
- inversePatches.push({
4769
- op: Operation.Replace,
4770
- path,
4771
- value: cloneIfNeeded(original[index])
4772
- });
4773
- }
4774
- }
4775
- for (let index = original.length;index < copy.length; index += 1) {
4776
- const _path = basePath.concat([index]);
4777
- const path = escapePath(_path, pathAsArray);
4778
- patches.push({
4779
- op: Operation.Add,
4780
- path,
4781
- value: cloneIfNeeded(copy[index])
4782
- });
4783
- }
4784
- if (original.length < copy.length) {
4785
- const { arrayLengthAssignment = true } = options.enablePatches;
4786
- if (arrayLengthAssignment) {
4787
- const _path = basePath.concat(["length"]);
4788
- const path = escapePath(_path, pathAsArray);
4789
- inversePatches.push({
4790
- op: Operation.Replace,
4791
- path,
4792
- value: original.length
4793
- });
4794
- } else {
4795
- for (let index = copy.length;original.length < index; index -= 1) {
4796
- const _path = basePath.concat([index - 1]);
4797
- const path = escapePath(_path, pathAsArray);
4798
- inversePatches.push({
4799
- op: Operation.Remove,
4800
- path
4801
- });
4802
4348
  }
4803
4349
  }
4804
- }
4805
- }
4806
- function generatePatchesFromAssigned({ original, copy, assignedMap }, basePath, patches, inversePatches, pathAsArray) {
4807
- assignedMap.forEach((assignedValue, key) => {
4808
- const originalValue = get(original, key);
4809
- const value = cloneIfNeeded(get(copy, key));
4810
- const op = !assignedValue ? Operation.Remove : has(original, key) ? Operation.Replace : Operation.Add;
4811
- if (isEqual(originalValue, value) && op === Operation.Replace)
4812
- return;
4813
- const _path = basePath.concat(key);
4814
- const path = escapePath(_path, pathAsArray);
4815
- patches.push(op === Operation.Remove ? { op, path } : { op, path, value });
4816
- inversePatches.push(op === Operation.Add ? { op: Operation.Remove, path } : op === Operation.Remove ? { op: Operation.Add, path, value: originalValue } : { op: Operation.Replace, path, value: originalValue });
4817
- });
4818
- }
4819
- function generateSetPatches({ original, copy }, basePath, patches, inversePatches, pathAsArray) {
4820
- let index = 0;
4821
- original.forEach((value) => {
4822
- if (!copy.has(value)) {
4823
- const _path = basePath.concat([index]);
4824
- const path = escapePath(_path, pathAsArray);
4825
- patches.push({
4826
- op: Operation.Remove,
4827
- path,
4828
- value
4829
- });
4830
- inversePatches.unshift({
4831
- op: Operation.Add,
4832
- path,
4833
- value
4350
+ if (!matchedRoute) {
4351
+ return new Response(JSON.stringify({ error: "Route not found" }), {
4352
+ status: 404,
4353
+ headers: { ...corsHeaders, "Content-Type": "application/json" }
4834
4354
  });
4835
4355
  }
4836
- index += 1;
4837
- });
4838
- index = 0;
4839
- copy.forEach((value) => {
4840
- if (!original.has(value)) {
4841
- const _path = basePath.concat([index]);
4842
- const path = escapePath(_path, pathAsArray);
4843
- patches.push({
4844
- op: Operation.Add,
4845
- path,
4846
- value
4847
- });
4848
- inversePatches.unshift({
4849
- op: Operation.Remove,
4850
- path,
4851
- value
4356
+ const handler = matchedRoute.getHandler(method);
4357
+ if (!handler) {
4358
+ return new Response(JSON.stringify({ error: `Method ${method} not allowed` }), {
4359
+ status: 405,
4360
+ headers: { ...corsHeaders, "Content-Type": "application/json" }
4852
4361
  });
4853
4362
  }
4854
- index += 1;
4855
- });
4856
- }
4857
- function generatePatches(proxyState, basePath, patches, inversePatches) {
4858
- const { pathAsArray = true } = proxyState.options.enablePatches;
4859
- switch (proxyState.type) {
4860
- case 0:
4861
- case 2:
4862
- return generatePatchesFromAssigned(proxyState, basePath, patches, inversePatches, pathAsArray);
4863
- case 1:
4864
- return generateArrayPatches(proxyState, basePath, patches, inversePatches, pathAsArray);
4865
- case 3:
4866
- return generateSetPatches(proxyState, basePath, patches, inversePatches, pathAsArray);
4867
- }
4868
- }
4869
- var readable = false;
4870
- var checkReadable = (value, options, ignoreCheckDraftable = false) => {
4871
- if (typeof value === "object" && value !== null && (!isDraftable(value, options) || ignoreCheckDraftable) && !readable) {
4872
- throw new Error(`Strict mode: Mutable data cannot be accessed directly, please use 'unsafe(callback)' wrap.`);
4873
- }
4874
- };
4875
- var mapHandler = {
4876
- get size() {
4877
- const current = latest(getProxyDraft(this));
4878
- return current.size;
4879
- },
4880
- has(key) {
4881
- return latest(getProxyDraft(this)).has(key);
4882
- },
4883
- set(key, value) {
4884
- const target = getProxyDraft(this);
4885
- const source = latest(target);
4886
- if (!source.has(key) || !isEqual(source.get(key), value)) {
4887
- ensureShallowCopy(target);
4888
- markChanged(target);
4889
- target.assignedMap.set(key, true);
4890
- target.copy.set(key, value);
4891
- markFinalization(target, key, value, generatePatches);
4892
- }
4893
- return this;
4894
- },
4895
- delete(key) {
4896
- if (!this.has(key)) {
4897
- return false;
4898
- }
4899
- const target = getProxyDraft(this);
4900
- ensureShallowCopy(target);
4901
- markChanged(target);
4902
- if (target.original.has(key)) {
4903
- target.assignedMap.set(key, false);
4904
- } else {
4905
- target.assignedMap.delete(key);
4906
- }
4907
- target.copy.delete(key);
4908
- return true;
4909
- },
4910
- clear() {
4911
- const target = getProxyDraft(this);
4912
- if (!this.size)
4913
- return;
4914
- ensureShallowCopy(target);
4915
- markChanged(target);
4916
- target.assignedMap = new Map;
4917
- for (const [key] of target.original) {
4918
- target.assignedMap.set(key, false);
4919
- }
4920
- target.copy.clear();
4921
- },
4922
- forEach(callback, thisArg) {
4923
- const target = getProxyDraft(this);
4924
- latest(target).forEach((_value, _key) => {
4925
- callback.call(thisArg, this.get(_key), _key, this);
4926
- });
4927
- },
4928
- get(key) {
4929
- var _a, _b;
4930
- const target = getProxyDraft(this);
4931
- const value = latest(target).get(key);
4932
- const mutable = ((_b = (_a = target.options).mark) === null || _b === undefined ? undefined : _b.call(_a, value, dataTypes)) === dataTypes.mutable;
4933
- if (target.options.strict) {
4934
- checkReadable(value, target.options, mutable);
4935
- }
4936
- if (mutable) {
4937
- return value;
4938
- }
4939
- if (target.finalized || !isDraftable(value, target.options)) {
4940
- return value;
4941
- }
4942
- if (value !== target.original.get(key)) {
4943
- return value;
4944
- }
4945
- const draft = internal.createDraft({
4946
- original: value,
4947
- parentDraft: target,
4948
- key,
4949
- finalities: target.finalities,
4950
- options: target.options
4951
- });
4952
- ensureShallowCopy(target);
4953
- target.copy.set(key, draft);
4954
- return draft;
4955
- },
4956
- keys() {
4957
- return latest(getProxyDraft(this)).keys();
4958
- },
4959
- values() {
4960
- const iterator = this.keys();
4961
- return {
4962
- [iteratorSymbol]: () => this.values(),
4963
- next: () => {
4964
- const result = iterator.next();
4965
- if (result.done)
4966
- return result;
4967
- const value = this.get(result.value);
4968
- return {
4969
- done: false,
4970
- value
4971
- };
4972
- }
4973
- };
4974
- },
4975
- entries() {
4976
- const iterator = this.keys();
4977
- return {
4978
- [iteratorSymbol]: () => this.entries(),
4979
- next: () => {
4980
- const result = iterator.next();
4981
- if (result.done)
4982
- return result;
4983
- const value = this.get(result.value);
4984
- return {
4985
- done: false,
4986
- value: [result.value, value]
4987
- };
4363
+ if (!matchedRoute.isPublic && matchedRoute.hasProtections) {
4364
+ if (!tokenPayload) {
4365
+ return new Response(JSON.stringify({ error: "Unauthorized" }), {
4366
+ status: 401,
4367
+ headers: { ...corsHeaders, "Content-Type": "application/json" }
4368
+ });
4988
4369
  }
4989
- };
4990
- },
4991
- [iteratorSymbol]() {
4992
- return this.entries();
4993
- }
4994
- };
4995
- var mapHandlerKeys = Reflect.ownKeys(mapHandler);
4996
- var getNextIterator = (target, iterator, { isValuesIterator }) => () => {
4997
- var _a, _b;
4998
- const result = iterator.next();
4999
- if (result.done)
5000
- return result;
5001
- const key = result.value;
5002
- let value = target.setMap.get(key);
5003
- const currentDraft = getProxyDraft(value);
5004
- const mutable = ((_b = (_a = target.options).mark) === null || _b === undefined ? undefined : _b.call(_a, value, dataTypes)) === dataTypes.mutable;
5005
- if (target.options.strict) {
5006
- checkReadable(key, target.options, mutable);
5007
- }
5008
- if (!mutable && !currentDraft && isDraftable(key, target.options) && !target.finalized && target.original.has(key)) {
5009
- const proxy = internal.createDraft({
5010
- original: key,
5011
- parentDraft: target,
5012
- key,
5013
- finalities: target.finalities,
5014
- options: target.options
5015
- });
5016
- target.setMap.set(key, proxy);
5017
- value = proxy;
5018
- } else if (currentDraft) {
5019
- value = currentDraft.proxy;
5020
- }
5021
- return {
5022
- done: false,
5023
- value: isValuesIterator ? value : [value, value]
5024
- };
5025
- };
5026
- var setHandler = {
5027
- get size() {
5028
- const target = getProxyDraft(this);
5029
- return target.setMap.size;
5030
- },
5031
- has(value) {
5032
- const target = getProxyDraft(this);
5033
- if (target.setMap.has(value))
5034
- return true;
5035
- ensureShallowCopy(target);
5036
- const valueProxyDraft = getProxyDraft(value);
5037
- if (valueProxyDraft && target.setMap.has(valueProxyDraft.original))
5038
- return true;
5039
- return false;
5040
- },
5041
- add(value) {
5042
- const target = getProxyDraft(this);
5043
- if (!this.has(value)) {
5044
- ensureShallowCopy(target);
5045
- markChanged(target);
5046
- target.assignedMap.set(value, true);
5047
- target.setMap.set(value, value);
5048
- markFinalization(target, value, value, generatePatches);
5049
- }
5050
- return this;
5051
- },
5052
- delete(value) {
5053
- if (!this.has(value)) {
5054
- return false;
5055
- }
5056
- const target = getProxyDraft(this);
5057
- ensureShallowCopy(target);
5058
- markChanged(target);
5059
- const valueProxyDraft = getProxyDraft(value);
5060
- if (valueProxyDraft && target.setMap.has(valueProxyDraft.original)) {
5061
- target.assignedMap.set(valueProxyDraft.original, false);
5062
- return target.setMap.delete(valueProxyDraft.original);
5063
- }
5064
- if (!valueProxyDraft && target.setMap.has(value)) {
5065
- target.assignedMap.set(value, false);
5066
- } else {
5067
- target.assignedMap.delete(value);
5068
- }
5069
- return target.setMap.delete(value);
5070
- },
5071
- clear() {
5072
- if (!this.size)
5073
- return;
5074
- const target = getProxyDraft(this);
5075
- ensureShallowCopy(target);
5076
- markChanged(target);
5077
- for (const value of target.original) {
5078
- target.assignedMap.set(value, false);
5079
- }
5080
- target.setMap.clear();
5081
- },
5082
- values() {
5083
- const target = getProxyDraft(this);
5084
- ensureShallowCopy(target);
5085
- const iterator = target.setMap.keys();
5086
- return {
5087
- [Symbol.iterator]: () => this.values(),
5088
- next: getNextIterator(target, iterator, { isValuesIterator: true })
5089
- };
5090
- },
5091
- entries() {
5092
- const target = getProxyDraft(this);
5093
- ensureShallowCopy(target);
5094
- const iterator = target.setMap.keys();
5095
- return {
5096
- [Symbol.iterator]: () => this.entries(),
5097
- next: getNextIterator(target, iterator, {
5098
- isValuesIterator: false
5099
- })
5100
- };
5101
- },
5102
- keys() {
5103
- return this.values();
5104
- },
5105
- [iteratorSymbol]() {
5106
- return this.values();
5107
- },
5108
- forEach(callback, thisArg) {
5109
- const iterator = this.values();
5110
- let result = iterator.next();
5111
- while (!result.done) {
5112
- callback.call(thisArg, result.value, result.value, this);
5113
- result = iterator.next();
5114
- }
5115
- }
5116
- };
5117
- if (Set.prototype.difference) {
5118
- Object.assign(setHandler, {
5119
- intersection(other) {
5120
- return Set.prototype.intersection.call(new Set(this.values()), other);
5121
- },
5122
- union(other) {
5123
- return Set.prototype.union.call(new Set(this.values()), other);
5124
- },
5125
- difference(other) {
5126
- return Set.prototype.difference.call(new Set(this.values()), other);
5127
- },
5128
- symmetricDifference(other) {
5129
- return Set.prototype.symmetricDifference.call(new Set(this.values()), other);
5130
- },
5131
- isSubsetOf(other) {
5132
- return Set.prototype.isSubsetOf.call(new Set(this.values()), other);
5133
- },
5134
- isSupersetOf(other) {
5135
- return Set.prototype.isSupersetOf.call(new Set(this.values()), other);
5136
- },
5137
- isDisjointFrom(other) {
5138
- return Set.prototype.isDisjointFrom.call(new Set(this.values()), other);
5139
- }
5140
- });
5141
- }
5142
- var setHandlerKeys = Reflect.ownKeys(setHandler);
5143
- var proxyHandler = {
5144
- get(target, key, receiver) {
5145
- var _a, _b;
5146
- const copy = (_a = target.copy) === null || _a === undefined ? undefined : _a[key];
5147
- if (copy && target.finalities.draftsCache.has(copy)) {
5148
- return copy;
5149
- }
5150
- if (key === PROXY_DRAFT)
5151
- return target;
5152
- let markResult;
5153
- if (target.options.mark) {
5154
- const value2 = key === "size" && (target.original instanceof Map || target.original instanceof Set) ? Reflect.get(target.original, key) : Reflect.get(target.original, key, receiver);
5155
- markResult = target.options.mark(value2, dataTypes);
5156
- if (markResult === dataTypes.mutable) {
5157
- if (target.options.strict) {
5158
- checkReadable(value2, target.options, true);
4370
+ this.contextHandler.setAuthToken(rawToken);
4371
+ let isAuthorized = false;
4372
+ for (const protection of matchedRoute.protections) {
4373
+ if (protection.token.name === tokenPayload.tokenType) {
4374
+ const mockTokenInstance = {
4375
+ params: tokenPayload.params,
4376
+ getTokenDefinition: () => protection.token
4377
+ };
4378
+ const allowed = await protection.check(mockTokenInstance);
4379
+ if (allowed) {
4380
+ isAuthorized = true;
4381
+ break;
4382
+ }
5159
4383
  }
5160
- return value2;
5161
4384
  }
5162
- }
5163
- const source = latest(target);
5164
- if (source instanceof Map && mapHandlerKeys.includes(key)) {
5165
- if (key === "size") {
5166
- return Object.getOwnPropertyDescriptor(mapHandler, "size").get.call(target.proxy);
4385
+ if (!isAuthorized) {
4386
+ return new Response(JSON.stringify({ error: "Forbidden" }), {
4387
+ status: 403,
4388
+ headers: { ...corsHeaders, "Content-Type": "application/json" }
4389
+ });
5167
4390
  }
5168
- const handle = mapHandler[key];
5169
- return handle.bind(target.proxy);
5170
- }
5171
- if (source instanceof Set && setHandlerKeys.includes(key)) {
5172
- if (key === "size") {
5173
- return Object.getOwnPropertyDescriptor(setHandler, "size").get.call(target.proxy);
4391
+ } else if (!matchedRoute.isPublic && !matchedRoute.hasProtections) {
4392
+ if (!tokenPayload) {
4393
+ return new Response(JSON.stringify({ error: "Unauthorized" }), {
4394
+ status: 401,
4395
+ headers: { ...corsHeaders, "Content-Type": "application/json" }
4396
+ });
5174
4397
  }
5175
- const handle = setHandler[key];
5176
- return handle.bind(target.proxy);
5177
- }
5178
- if (!has(source, key)) {
5179
- const desc = getDescriptor(source, key);
5180
- return desc ? `value` in desc ? desc.value : (_b = desc.get) === null || _b === undefined ? undefined : _b.call(target.proxy) : undefined;
5181
- }
5182
- const value = source[key];
5183
- if (target.options.strict) {
5184
- checkReadable(value, target.options);
5185
4398
  }
5186
- if (target.finalized || !isDraftable(value, target.options)) {
5187
- return value;
5188
- }
5189
- if (value === peek(target.original, key)) {
5190
- ensureShallowCopy(target);
5191
- target.copy[key] = createDraft({
5192
- original: target.original[key],
5193
- parentDraft: target,
5194
- key: target.type === 1 ? Number(key) : key,
5195
- finalities: target.finalities,
5196
- options: target.options
4399
+ this.contextHandler.setAuthToken(rawToken);
4400
+ const model = this.contextHandler.getModel();
4401
+ const adapters = model.getAdapters();
4402
+ const authParams = tokenPayload ? { params: tokenPayload.params, tokenName: tokenPayload.tokenType } : undefined;
4403
+ const routeContext = matchedRoute.buildContext(adapters, authParams);
4404
+ try {
4405
+ const response = await handler(routeContext, req, routeParams, url);
4406
+ const newHeaders = new Headers(response.headers);
4407
+ for (const [key, value] of Object.entries(corsHeaders)) {
4408
+ newHeaders.set(key, value);
4409
+ }
4410
+ return new Response(response.body, {
4411
+ status: response.status,
4412
+ statusText: response.statusText,
4413
+ headers: newHeaders
5197
4414
  });
5198
- if (typeof markResult === "function") {
5199
- const subProxyDraft = getProxyDraft(target.copy[key]);
5200
- ensureShallowCopy(subProxyDraft);
5201
- markChanged(subProxyDraft);
5202
- return subProxyDraft.copy;
5203
- }
5204
- return target.copy[key];
5205
- }
5206
- if (isDraft(value)) {
5207
- target.finalities.draftsCache.add(value);
5208
- }
5209
- return value;
5210
- },
5211
- set(target, key, value) {
5212
- var _a;
5213
- if (target.type === 3 || target.type === 2) {
5214
- throw new Error(`Map/Set draft does not support any property assignment.`);
5215
- }
5216
- let _key;
5217
- if (target.type === 1 && key !== "length" && !(Number.isInteger(_key = Number(key)) && _key >= 0 && (key === 0 || _key === 0 || String(_key) === String(key)))) {
5218
- throw new Error(`Only supports setting array indices and the 'length' property.`);
5219
- }
5220
- const desc = getDescriptor(latest(target), key);
5221
- if (desc === null || desc === undefined ? undefined : desc.set) {
5222
- desc.set.call(target.proxy, value);
5223
- return true;
5224
- }
5225
- const current = peek(latest(target), key);
5226
- const currentProxyDraft = getProxyDraft(current);
5227
- if (currentProxyDraft && isEqual(currentProxyDraft.original, value)) {
5228
- target.copy[key] = value;
5229
- target.assignedMap = (_a = target.assignedMap) !== null && _a !== undefined ? _a : new Map;
5230
- target.assignedMap.set(key, false);
5231
- return true;
5232
- }
5233
- if (isEqual(value, current) && (value !== undefined || has(target.original, key)))
5234
- return true;
5235
- ensureShallowCopy(target);
5236
- markChanged(target);
5237
- if (has(target.original, key) && isEqual(value, target.original[key])) {
5238
- target.assignedMap.delete(key);
5239
- } else {
5240
- target.assignedMap.set(key, true);
5241
- }
5242
- target.copy[key] = value;
5243
- markFinalization(target, key, value, generatePatches);
5244
- return true;
5245
- },
5246
- has(target, key) {
5247
- return key in latest(target);
5248
- },
5249
- ownKeys(target) {
5250
- return Reflect.ownKeys(latest(target));
5251
- },
5252
- getOwnPropertyDescriptor(target, key) {
5253
- const source = latest(target);
5254
- const descriptor = Reflect.getOwnPropertyDescriptor(source, key);
5255
- if (!descriptor)
5256
- return descriptor;
5257
- return {
5258
- writable: true,
5259
- configurable: target.type !== 1 || key !== "length",
5260
- enumerable: descriptor.enumerable,
5261
- value: source[key]
5262
- };
5263
- },
5264
- getPrototypeOf(target) {
5265
- return Reflect.getPrototypeOf(target.original);
5266
- },
5267
- setPrototypeOf() {
5268
- throw new Error(`Cannot call 'setPrototypeOf()' on drafts`);
5269
- },
5270
- defineProperty() {
5271
- throw new Error(`Cannot call 'defineProperty()' on drafts`);
5272
- },
5273
- deleteProperty(target, key) {
5274
- var _a;
5275
- if (target.type === 1) {
5276
- return proxyHandler.set.call(this, target, key, undefined, target.proxy);
5277
- }
5278
- if (peek(target.original, key) !== undefined || key in target.original) {
5279
- ensureShallowCopy(target);
5280
- markChanged(target);
5281
- target.assignedMap.set(key, false);
5282
- } else {
5283
- target.assignedMap = (_a = target.assignedMap) !== null && _a !== undefined ? _a : new Map;
5284
- target.assignedMap.delete(key);
5285
- }
5286
- if (target.copy)
5287
- delete target.copy[key];
5288
- return true;
5289
- }
5290
- };
5291
- function createDraft(createDraftOptions) {
5292
- const { original, parentDraft, key, finalities, options } = createDraftOptions;
5293
- const type = getType(original);
5294
- const proxyDraft = {
5295
- type,
5296
- finalized: false,
5297
- parent: parentDraft,
5298
- original,
5299
- copy: null,
5300
- proxy: null,
5301
- finalities,
5302
- options,
5303
- setMap: type === 3 ? new Map(original.entries()) : undefined
5304
- };
5305
- if (key || "key" in createDraftOptions) {
5306
- proxyDraft.key = key;
5307
- }
5308
- const { proxy, revoke } = Proxy.revocable(type === 1 ? Object.assign([], proxyDraft) : proxyDraft, proxyHandler);
5309
- finalities.revoke.push(revoke);
5310
- proxyDraft.proxy = proxy;
5311
- if (parentDraft) {
5312
- const target = parentDraft;
5313
- target.finalities.draft.push((patches, inversePatches) => {
5314
- var _a, _b;
5315
- const oldProxyDraft = getProxyDraft(proxy);
5316
- let copy = target.type === 3 ? target.setMap : target.copy;
5317
- const draft = get(copy, key);
5318
- const proxyDraft2 = getProxyDraft(draft);
5319
- if (proxyDraft2) {
5320
- let updatedValue = proxyDraft2.original;
5321
- if (proxyDraft2.operated) {
5322
- updatedValue = getValue(draft);
5323
- }
5324
- finalizeSetValue(proxyDraft2);
5325
- finalizePatches(proxyDraft2, generatePatches, patches, inversePatches);
5326
- if (target.options.enableAutoFreeze) {
5327
- target.options.updatedValues = (_a = target.options.updatedValues) !== null && _a !== undefined ? _a : new WeakMap;
5328
- target.options.updatedValues.set(updatedValue, proxyDraft2.original);
5329
- }
5330
- set(copy, key, updatedValue);
5331
- }
5332
- (_b = oldProxyDraft.callbacks) === null || _b === undefined || _b.forEach((callback) => {
5333
- callback(patches, inversePatches);
4415
+ } catch (error) {
4416
+ return new Response(JSON.stringify({ error: error.message }), {
4417
+ status: 500,
4418
+ headers: { ...corsHeaders, "Content-Type": "application/json" }
5334
4419
  });
5335
- });
5336
- } else {
5337
- const target = getProxyDraft(proxy);
5338
- target.finalities.draft.push((patches, inversePatches) => {
5339
- finalizeSetValue(target);
5340
- finalizePatches(target, generatePatches, patches, inversePatches);
5341
- });
5342
- }
5343
- return proxy;
5344
- }
5345
- internal.createDraft = createDraft;
5346
- function finalizeDraft(result, returnedValue, patches, inversePatches, enableAutoFreeze) {
5347
- var _a;
5348
- const proxyDraft = getProxyDraft(result);
5349
- const original = (_a = proxyDraft === null || proxyDraft === undefined ? undefined : proxyDraft.original) !== null && _a !== undefined ? _a : result;
5350
- const hasReturnedValue = !!returnedValue.length;
5351
- if (proxyDraft === null || proxyDraft === undefined ? undefined : proxyDraft.operated) {
5352
- while (proxyDraft.finalities.draft.length > 0) {
5353
- const finalize = proxyDraft.finalities.draft.pop();
5354
- finalize(patches, inversePatches);
5355
- }
5356
- }
5357
- const state = hasReturnedValue ? returnedValue[0] : proxyDraft ? proxyDraft.operated ? proxyDraft.copy : proxyDraft.original : result;
5358
- if (proxyDraft)
5359
- revokeProxy(proxyDraft);
5360
- if (enableAutoFreeze) {
5361
- deepFreeze(state, state, proxyDraft === null || proxyDraft === undefined ? undefined : proxyDraft.options.updatedValues);
5362
- }
5363
- return [
5364
- state,
5365
- patches && hasReturnedValue ? [{ op: Operation.Replace, path: [], value: returnedValue[0] }] : patches,
5366
- inversePatches && hasReturnedValue ? [{ op: Operation.Replace, path: [], value: original }] : inversePatches
5367
- ];
5368
- }
5369
- function draftify(baseState, options) {
5370
- var _a;
5371
- const finalities = {
5372
- draft: [],
5373
- revoke: [],
5374
- handledSet: new WeakSet,
5375
- draftsCache: new WeakSet
5376
- };
5377
- let patches;
5378
- let inversePatches;
5379
- if (options.enablePatches) {
5380
- patches = [];
5381
- inversePatches = [];
5382
- }
5383
- const isMutable = ((_a = options.mark) === null || _a === undefined ? undefined : _a.call(options, baseState, dataTypes)) === dataTypes.mutable || !isDraftable(baseState, options);
5384
- const draft = isMutable ? baseState : createDraft({
5385
- original: baseState,
5386
- parentDraft: null,
5387
- finalities,
5388
- options
5389
- });
5390
- return [
5391
- draft,
5392
- (returnedValue = []) => {
5393
- const [finalizedState, finalizedPatches, finalizedInversePatches] = finalizeDraft(draft, returnedValue, patches, inversePatches, options.enableAutoFreeze);
5394
- return options.enablePatches ? [finalizedState, finalizedPatches, finalizedInversePatches] : finalizedState;
5395
- }
5396
- ];
5397
- }
5398
- function handleReturnValue(options) {
5399
- const { rootDraft, value, useRawReturn = false, isRoot = true } = options;
5400
- forEach(value, (key, item, source) => {
5401
- const proxyDraft = getProxyDraft(item);
5402
- if (proxyDraft && rootDraft && proxyDraft.finalities === rootDraft.finalities) {
5403
- options.isContainDraft = true;
5404
- const currentValue = proxyDraft.original;
5405
- if (source instanceof Set) {
5406
- const arr = Array.from(source);
5407
- source.clear();
5408
- arr.forEach((_item) => source.add(key === _item ? currentValue : _item));
5409
- } else {
5410
- set(source, key, currentValue);
5411
- }
5412
- } else if (typeof item === "object" && item !== null) {
5413
- options.value = item;
5414
- options.isRoot = false;
5415
- handleReturnValue(options);
5416
4420
  }
5417
- });
5418
- if (isRoot) {
5419
- if (!options.isContainDraft)
5420
- console.warn(`The return value does not contain any draft, please use 'rawReturn()' to wrap the return value to improve performance.`);
5421
- if (useRawReturn) {
5422
- console.warn(`The return value contains drafts, please don't use 'rawReturn()' to wrap the return value.`);
5423
- }
5424
- }
5425
- }
5426
- function getCurrent(target) {
5427
- var _a;
5428
- const proxyDraft = getProxyDraft(target);
5429
- if (!isDraftable(target, proxyDraft === null || proxyDraft === undefined ? undefined : proxyDraft.options))
5430
- return target;
5431
- const type = getType(target);
5432
- if (proxyDraft && !proxyDraft.operated)
5433
- return proxyDraft.original;
5434
- let currentValue;
5435
- function ensureShallowCopy2() {
5436
- currentValue = type === 2 ? !isBaseMapInstance(target) ? new (Object.getPrototypeOf(target)).constructor(target) : new Map(target) : type === 3 ? Array.from(proxyDraft.setMap.values()) : shallowCopy(target, proxyDraft === null || proxyDraft === undefined ? undefined : proxyDraft.options);
5437
- }
5438
- if (proxyDraft) {
5439
- proxyDraft.finalized = true;
5440
- try {
5441
- ensureShallowCopy2();
5442
- } finally {
5443
- proxyDraft.finalized = false;
5444
- }
5445
- } else {
5446
- currentValue = target;
5447
4421
  }
5448
- forEach(currentValue, (key, value) => {
5449
- if (proxyDraft && isEqual(get(proxyDraft.original, key), value))
5450
- return;
5451
- const newValue = getCurrent(value);
5452
- if (newValue !== value) {
5453
- if (currentValue === target)
5454
- ensureShallowCopy2();
5455
- set(currentValue, key, newValue);
4422
+ stop() {
4423
+ for (const conn of this.streamConnections.values()) {
4424
+ conn.unsubscribe();
5456
4425
  }
5457
- });
5458
- if (type === 3) {
5459
- const value = (_a = proxyDraft === null || proxyDraft === undefined ? undefined : proxyDraft.original) !== null && _a !== undefined ? _a : currentValue;
5460
- return !isBaseSetInstance(value) ? new (Object.getPrototypeOf(value)).constructor(currentValue) : new Set(currentValue);
5461
- }
5462
- return currentValue;
5463
- }
5464
- function current(target) {
5465
- if (!isDraft(target)) {
5466
- throw new Error(`current() is only used for Draft, parameter: ${target}`);
4426
+ this.streamConnections.clear();
4427
+ this.server?.stop();
5467
4428
  }
5468
- return getCurrent(target);
5469
4429
  }
5470
- var makeCreator = (arg) => {
5471
- if (arg !== undefined && Object.prototype.toString.call(arg) !== "[object Object]") {
5472
- throw new Error(`Invalid options: ${String(arg)}, 'options' should be an object.`);
5473
- }
5474
- return function create(arg0, arg1, arg2) {
5475
- var _a, _b, _c;
5476
- if (typeof arg0 === "function" && typeof arg1 !== "function") {
5477
- return function(base2, ...args) {
5478
- return create(base2, (draft2) => arg0.call(this, draft2, ...args), arg1);
5479
- };
5480
- }
5481
- const base = arg0;
5482
- const mutate = arg1;
5483
- let options = arg2;
5484
- if (typeof arg1 !== "function") {
5485
- options = arg1;
5486
- }
5487
- if (options !== undefined && Object.prototype.toString.call(options) !== "[object Object]") {
5488
- throw new Error(`Invalid options: ${options}, 'options' should be an object.`);
5489
- }
5490
- options = Object.assign(Object.assign({}, arg), options);
5491
- const state = isDraft(base) ? current(base) : base;
5492
- const mark = Array.isArray(options.mark) ? (value, types) => {
5493
- for (const mark2 of options.mark) {
5494
- if (typeof mark2 !== "function") {
5495
- throw new Error(`Invalid mark: ${mark2}, 'mark' should be a function.`);
5496
- }
5497
- const result2 = mark2(value, types);
5498
- if (result2) {
5499
- return result2;
5500
- }
5501
- }
5502
- return;
5503
- } : options.mark;
5504
- const enablePatches = (_a = options.enablePatches) !== null && _a !== undefined ? _a : false;
5505
- const strict = (_b = options.strict) !== null && _b !== undefined ? _b : false;
5506
- const enableAutoFreeze = (_c = options.enableAutoFreeze) !== null && _c !== undefined ? _c : false;
5507
- const _options = {
5508
- enableAutoFreeze,
5509
- mark,
5510
- strict,
5511
- enablePatches
5512
- };
5513
- if (!isDraftable(state, _options) && typeof state === "object" && state !== null) {
5514
- throw new Error(`Invalid base state: create() only supports plain objects, arrays, Set, Map or using mark() to mark the state as immutable.`);
5515
- }
5516
- const [draft, finalize] = draftify(state, _options);
5517
- if (typeof arg1 !== "function") {
5518
- if (!isDraftable(state, _options)) {
5519
- throw new Error(`Invalid base state: create() only supports plain objects, arrays, Set, Map or using mark() to mark the state as immutable.`);
5520
- }
5521
- return [draft, finalize];
5522
- }
5523
- let result;
5524
- try {
5525
- result = mutate(draft);
5526
- } catch (error) {
5527
- revokeProxy(getProxyDraft(draft));
5528
- throw error;
5529
- }
5530
- const returnValue = (value) => {
5531
- const proxyDraft = getProxyDraft(draft);
5532
- if (!isDraft(value)) {
5533
- if (value !== undefined && !isEqual(value, draft) && (proxyDraft === null || proxyDraft === undefined ? undefined : proxyDraft.operated)) {
5534
- throw new Error(`Either the value is returned as a new non-draft value, or only the draft is modified without returning any value.`);
5535
- }
5536
- const rawReturnValue = value === null || value === undefined ? undefined : value[RAW_RETURN_SYMBOL];
5537
- if (rawReturnValue) {
5538
- const _value = rawReturnValue[0];
5539
- if (_options.strict && typeof value === "object" && value !== null) {
5540
- handleReturnValue({
5541
- rootDraft: proxyDraft,
5542
- value,
5543
- useRawReturn: true
5544
- });
5545
- }
5546
- return finalize([_value]);
5547
- }
5548
- if (value !== undefined) {
5549
- if (typeof value === "object" && value !== null) {
5550
- handleReturnValue({ rootDraft: proxyDraft, value });
5551
- }
5552
- return finalize([value]);
5553
- }
5554
- }
5555
- if (value === draft || value === undefined) {
5556
- return finalize([]);
5557
- }
5558
- const returnedProxyDraft = getProxyDraft(value);
5559
- if (_options === returnedProxyDraft.options) {
5560
- if (returnedProxyDraft.operated) {
5561
- throw new Error(`Cannot return a modified child draft.`);
5562
- }
5563
- return finalize([current(value)]);
5564
- }
5565
- return finalize([value]);
5566
- };
5567
- if (result instanceof Promise) {
5568
- return result.then(returnValue, (error) => {
5569
- revokeProxy(getProxyDraft(draft));
5570
- throw error;
5571
- });
5572
- }
5573
- return returnValue(result);
5574
- };
5575
- };
5576
- var create = makeCreator();
5577
- function apply(state, patches, applyOptions) {
5578
- let i;
5579
- for (i = patches.length - 1;i >= 0; i -= 1) {
5580
- const { value, op, path } = patches[i];
5581
- if (!path.length && op === Operation.Replace || path === "" && op === Operation.Add) {
5582
- state = value;
5583
- break;
5584
- }
5585
- }
5586
- if (i > -1) {
5587
- patches = patches.slice(i + 1);
5588
- }
5589
- const mutate = (draft) => {
5590
- patches.forEach((patch) => {
5591
- const { path: _path, op } = patch;
5592
- const path = unescapePath(_path);
5593
- let base = draft;
5594
- for (let index = 0;index < path.length - 1; index += 1) {
5595
- const parentType = getType(base);
5596
- let key2 = path[index];
5597
- if (typeof key2 !== "string" && typeof key2 !== "number") {
5598
- key2 = String(key2);
5599
- }
5600
- if ((parentType === 0 || parentType === 1) && (key2 === "__proto__" || key2 === "constructor") || typeof base === "function" && key2 === "prototype") {
5601
- throw new Error(`Patching reserved attributes like __proto__ and constructor is not allowed.`);
5602
- }
5603
- base = get(parentType === 3 ? Array.from(base) : base, key2);
5604
- if (typeof base !== "object") {
5605
- throw new Error(`Cannot apply patch at '${path.join("/")}'.`);
5606
- }
5607
- }
5608
- const type = getType(base);
5609
- const value = deepClone(patch.value);
5610
- const key = path[path.length - 1];
5611
- switch (op) {
5612
- case Operation.Replace:
5613
- switch (type) {
5614
- case 2:
5615
- return base.set(key, value);
5616
- case 3:
5617
- throw new Error(`Cannot apply replace patch to set.`);
5618
- default:
5619
- return base[key] = value;
5620
- }
5621
- case Operation.Add:
5622
- switch (type) {
5623
- case 1:
5624
- return key === "-" ? base.push(value) : base.splice(key, 0, value);
5625
- case 2:
5626
- return base.set(key, value);
5627
- case 3:
5628
- return base.add(value);
5629
- default:
5630
- return base[key] = value;
5631
- }
5632
- case Operation.Remove:
5633
- switch (type) {
5634
- case 1:
5635
- return base.splice(key, 1);
5636
- case 2:
5637
- return base.delete(key);
5638
- case 3:
5639
- return base.delete(patch.value);
5640
- default:
5641
- return delete base[key];
5642
- }
5643
- default:
5644
- throw new Error(`Unsupported patch operation: ${op}.`);
5645
- }
5646
- });
5647
- };
5648
- if (applyOptions === null || applyOptions === undefined ? undefined : applyOptions.mutable) {
5649
- {
5650
- if (Object.keys(applyOptions).filter((key) => key !== "mutable").length) {
5651
- console.warn('The "mutable" option is not allowed to be used with other options.');
5652
- }
5653
- }
5654
- mutate(state);
5655
- return;
5656
- }
5657
- if (isDraft(state)) {
5658
- if (applyOptions !== undefined) {
5659
- throw new Error(`Cannot apply patches with options to a draft.`);
5660
- }
5661
- mutate(state);
5662
- return state;
5663
- }
5664
- return create(state, mutate, Object.assign(Object.assign({}, applyOptions), { enablePatches: false }));
5665
- }
5666
- var constructorString = Object.prototype.constructor.toString();
5667
-
5668
- class ArcContextElement {
5669
- name;
5670
- constructor(name) {
5671
- this.name = name;
5672
- }
5673
- }
5674
-
5675
- class ArcOptional {
5676
- parent;
5677
- constructor(parent) {
5678
- this.parent = parent;
5679
- }
5680
- parse(value) {
5681
- if (!value)
5682
- return null;
5683
- return this.parent.parse(value);
5684
- }
5685
- serialize(value) {
5686
- if (value)
5687
- return this.parent.serialize(value);
5688
- return null;
5689
- }
5690
- deserialize(value) {
5691
- if (!value)
5692
- return null;
5693
- return this.parent.deserialize(value);
5694
- }
5695
- validate(value) {
5696
- if (!value)
5697
- return false;
5698
- return this.parent.validate(value);
5699
- }
5700
- toJsonSchema() {
5701
- const parentSchema = this.parent.toJsonSchema?.() ?? {};
5702
- return {
5703
- anyOf: [parentSchema, { type: "null" }]
5704
- };
5705
- }
5706
- getColumnData() {
5707
- const parentColumnData = this.parent.getColumnData?.();
5708
- if (!parentColumnData) {
5709
- throw new Error(`Parent element does not implement getColumnData()`);
5710
- }
5711
- return {
5712
- ...parentColumnData,
5713
- storeData: {
5714
- ...parentColumnData.storeData,
5715
- isNullable: true
5716
- }
5717
- };
5718
- }
5719
- }
5720
-
5721
- class ArcBranded {
5722
- parent;
5723
- brand;
5724
- constructor(parent, brand) {
5725
- this.parent = parent;
5726
- this.brand = brand;
5727
- }
5728
- serialize(value) {
5729
- return this.parent.serialize(value);
5730
- }
5731
- deserialize(value) {
5732
- return this.parent.deserialize(value);
5733
- }
5734
- parse(value) {
5735
- return this.parent.parse(value);
5736
- }
5737
- optional() {
5738
- return new ArcOptional(this);
5739
- }
5740
- validate(value) {
5741
- return this.parent.validate(value);
5742
- }
5743
- toJsonSchema() {
5744
- return this.parent.toJsonSchema?.() ?? {};
5745
- }
5746
- getColumnData() {
5747
- const parentColumnData = this.parent.getColumnData?.();
5748
- if (!parentColumnData) {
5749
- throw new Error(`Parent element does not implement getColumnData()`);
5750
- }
5751
- return parentColumnData;
5752
- }
5753
- }
5754
-
5755
- class ArcDefault {
5756
- parent;
5757
- defaultValueOrCallback;
5758
- constructor(parent, defaultValueOrCallback) {
5759
- this.parent = parent;
5760
- this.defaultValueOrCallback = defaultValueOrCallback;
5761
- }
5762
- validate(value) {
5763
- throw new Error("Method not implemented.");
5764
- }
5765
- parse(value) {
5766
- if (value)
5767
- return this.parent.parse(value);
5768
- if (typeof this.defaultValueOrCallback === "function") {
5769
- return this.defaultValueOrCallback();
5770
- } else
5771
- return this.defaultValueOrCallback;
5772
- }
5773
- serialize(value) {
5774
- return this.parent.serialize(value);
5775
- }
5776
- deserialize(value) {
5777
- if (value)
5778
- return this.parent.deserialize(value);
5779
- if (typeof this.defaultValueOrCallback === "function") {
5780
- return this.defaultValueOrCallback();
5781
- } else
5782
- return this.defaultValueOrCallback;
5783
- }
5784
- toJsonSchema() {
5785
- const schema = this.parent.toJsonSchema?.() ?? {};
5786
- const defaultValue = typeof this.defaultValueOrCallback === "function" ? this.defaultValueOrCallback() : this.defaultValueOrCallback;
5787
- return {
5788
- ...schema,
5789
- default: defaultValue
5790
- };
5791
- }
5792
- getColumnData() {
5793
- const parentColumnData = this.parent.getColumnData?.();
5794
- if (!parentColumnData) {
5795
- throw new Error(`Parent element does not implement getColumnData()`);
5796
- }
5797
- const defaultValue = typeof this.defaultValueOrCallback === "function" ? this.defaultValueOrCallback() : this.defaultValueOrCallback;
5798
- return {
5799
- ...parentColumnData,
5800
- defaultValue
5801
- };
5802
- }
5803
- }
5804
-
5805
- class ArcAbstract {
5806
- validations;
5807
- _description;
5808
- _storeData;
5809
- constructor(validations = []) {
5810
- this.validations = validations;
5811
- }
5812
- description(description) {
5813
- const clone = this.clone();
5814
- clone._description = description;
5815
- return clone;
5816
- }
5817
- default(defaultValueOrCallback) {
5818
- return new ArcDefault(this, defaultValueOrCallback);
5819
- }
5820
- optional() {
5821
- return new ArcOptional(this);
5822
- }
5823
- branded(name) {
5824
- return new ArcBranded(this, name);
5825
- }
5826
- clone() {
5827
- const Constructor = this.constructor;
5828
- const newInstance = Object.assign(new Constructor, this);
5829
- newInstance._description = this._description;
5830
- newInstance._storeData = this._storeData ? { ...this._storeData } : undefined;
5831
- return newInstance;
5832
- }
5833
- validate(value) {
5834
- const errors = this.validations.reduce((acc, { name, validator }) => {
5835
- try {
5836
- acc[name] = validator(value);
5837
- } catch (error) {
5838
- acc[name] = error;
5839
- }
5840
- return acc;
5841
- }, {});
5842
- if (Object.values(errors).some((result) => !!result)) {
5843
- return errors;
5844
- }
5845
- return false;
5846
- }
5847
- pipeValidation(name, validator) {
5848
- const newInstance = this.clone();
5849
- newInstance.validations = [...this.validations, { name, validator }];
5850
- return newInstance;
5851
- }
5852
- toJsonSchema() {
5853
- const schema = {};
5854
- if (this._description) {
5855
- schema.description = this._description;
5856
- }
5857
- return schema;
5858
- }
5859
- getValidations() {
5860
- return this.validations;
5861
- }
5862
- primaryKey() {
5863
- const clone = this.clone();
5864
- clone._storeData = { ...clone._storeData, isPrimaryKey: true };
5865
- return clone;
5866
- }
5867
- autoIncrement() {
5868
- const clone = this.clone();
5869
- clone._storeData = { ...clone._storeData, isAutoIncrement: true };
5870
- return clone;
5871
- }
5872
- unique() {
5873
- const clone = this.clone();
5874
- clone._storeData = { ...clone._storeData, isUnique: true };
5875
- return clone;
5876
- }
5877
- index() {
5878
- const clone = this.clone();
5879
- clone._storeData = { ...clone._storeData, hasIndex: true };
5880
- return clone;
5881
- }
5882
- foreignKey(table, column, options) {
5883
- const clone = this.clone();
5884
- clone._storeData = {
5885
- ...clone._storeData,
5886
- foreignKey: { table, column, ...options }
5887
- };
5888
- return clone;
5889
- }
5890
- databaseType(overrides) {
5891
- const clone = this.clone();
5892
- clone._storeData = {
5893
- ...clone._storeData,
5894
- databaseType: { ...clone._storeData?.databaseType, ...overrides }
5895
- };
5896
- return clone;
5897
- }
5898
- columnOptions(options) {
5899
- const clone = this.clone();
5900
- clone._storeData = {
5901
- ...clone._storeData,
5902
- columnOptions: { ...clone._storeData?.columnOptions, ...options }
5903
- };
5904
- return clone;
5905
- }
5906
- getStoreData() {
5907
- return this._storeData;
5908
- }
5909
- }
5910
- function primitiveTypeComparatorStrategyFactory(type) {
5911
- return (value) => typeof value === type;
5912
- }
5913
- function typeValidatorBuilder(typeName, comparatorStrategy) {
5914
- const comparator = comparatorStrategy || primitiveTypeComparatorStrategyFactory(typeName);
5915
- return {
5916
- name: "type",
5917
- validator: (value) => {
5918
- const valueType = typeof value;
5919
- if (!comparator(value))
5920
- return { current: valueType, expected: typeName };
5921
- return false;
5922
- }
5923
- };
5924
- }
5925
- var arrayValidator = typeValidatorBuilder("array", Array.isArray);
5926
-
5927
- class ArcArray extends ArcAbstract {
5928
- parent;
5929
- constructor(parent) {
5930
- super([
5931
- arrayValidator,
5932
- {
5933
- name: "schema",
5934
- validator: (values) => {
5935
- const errors = values.reduce((acc, value, index) => {
5936
- const error = parent.validate(value);
5937
- if (error)
5938
- acc[index] = error;
5939
- return acc;
5940
- }, {});
5941
- if (Object.values(errors).some((result) => !!result)) {
5942
- return errors;
5943
- }
5944
- return false;
5945
- }
5946
- }
5947
- ]);
5948
- this.parent = parent;
5949
- }
5950
- minLength(min) {
5951
- return this.validation("minLength", (value) => {
5952
- if (value.length < min)
5953
- return {
5954
- currentLength: value.length,
5955
- minLength: min
5956
- };
5957
- });
5958
- }
5959
- maxLength(max) {
5960
- return this.validation("maxLength", (value) => {
5961
- if (value.length > max)
5962
- return {
5963
- currentLength: value.length,
5964
- maxLength: max
5965
- };
5966
- });
5967
- }
5968
- length(number) {
5969
- return this.validation("length", (value) => {
5970
- if (value.length !== number) {
5971
- return {
5972
- currentLength: value.length,
5973
- length: number
5974
- };
5975
- }
5976
- });
5977
- }
5978
- nonEmpty() {
5979
- return this.validation("nonEmpty", (value) => {
5980
- if (value.length === 0)
5981
- return { msg: "array is empty" };
5982
- });
5983
- }
5984
- parse(value) {
5985
- return value.map((v) => this.parent.parse(v));
5986
- }
5987
- serialize(value) {
5988
- return value.map((v) => this.parent.serialize(v));
5989
- }
5990
- deserialize(value) {
5991
- if (!Array.isArray(value))
5992
- return [];
5993
- return value.map((v) => this.parent.deserialize(v));
5994
- }
5995
- deserializePath(path, value) {
5996
- if (path.length === 0) {
5997
- return this.deserialize(value);
5998
- }
5999
- if (this.parent instanceof ArcObject || this.parent instanceof ArcArray) {
6000
- return this.parent.deserializePath(path, value);
6001
- }
6002
- return this.parent.deserialize(value);
6003
- }
6004
- validation(name, validator) {
6005
- const instance = this.pipeValidation(name, validator);
6006
- return instance;
6007
- }
6008
- toJsonSchema() {
6009
- const schema = {
6010
- type: "array",
6011
- items: this.parent.toJsonSchema?.() ?? {}
6012
- };
6013
- if (this._description) {
6014
- schema.description = this._description;
6015
- }
6016
- return schema;
6017
- }
6018
- getColumnData() {
6019
- const storeData = this.getStoreData();
6020
- return {
6021
- type: "array",
6022
- storeData: {
6023
- ...storeData,
6024
- isNullable: false
6025
- }
6026
- };
6027
- }
6028
- }
6029
- var objectValidator = typeValidatorBuilder("object");
6030
-
6031
- class ArcObject extends ArcAbstract {
6032
- rawShape;
6033
- constructor(rawShape) {
6034
- super([
6035
- objectValidator,
6036
- {
6037
- name: "schema",
6038
- validator: (value) => {
6039
- const errors = Object.entries(this.rawShape).reduce((acc, [key, element]) => {
6040
- if (!element.validate) {
6041
- return acc;
6042
- }
6043
- acc[key] = element.validate(value[key]);
6044
- return acc;
6045
- }, {});
6046
- if (Object.values(errors).some((result) => !!result)) {
6047
- return errors;
6048
- }
6049
- return false;
6050
- }
6051
- }
6052
- ]);
6053
- this.rawShape = rawShape;
6054
- }
6055
- parse(value) {
6056
- return Object.entries(this.rawShape).reduce((acc, [key, element]) => {
6057
- acc[key] = element.parse(value[key]);
6058
- return acc;
6059
- }, {});
6060
- }
6061
- serialize(value) {
6062
- return Object.entries(value).reduce((acc, [key, value2]) => {
6063
- if (!this.rawShape[key]) {
6064
- acc[key] = value2;
6065
- } else {
6066
- acc[key] = this.rawShape[key].serialize(value2);
6067
- }
6068
- return acc;
6069
- }, {});
6070
- }
6071
- deserialize(value) {
6072
- return Object.fromEntries(Object.entries(this.rawShape).map(([key, element]) => [
6073
- key,
6074
- element.deserialize(value[key])
6075
- ]));
6076
- }
6077
- deserializePath(path, value) {
6078
- if (path.length === 0) {
6079
- return this.deserialize(value);
6080
- }
6081
- const [key, ...restPath] = path;
6082
- const element = this.rawShape[key];
6083
- if (!element) {
6084
- console.warn(`No element found for key: ${key}`);
6085
- return value;
6086
- }
6087
- if (element instanceof ArcObject || element instanceof ArcArray) {
6088
- return element.deserializePath(restPath, value);
6089
- }
6090
- return element.deserialize(value);
6091
- }
6092
- parsePartial(value) {
6093
- return Object.entries(value).reduce((acc, [key, value2]) => {
6094
- acc[key] = this.rawShape[key].parse(value2);
6095
- return acc;
6096
- }, {});
6097
- }
6098
- deserializePartial(value) {
6099
- return Object.entries(value).reduce((acc, [key, value2]) => {
6100
- acc[key] = this.rawShape[key].deserialize(value2);
6101
- return acc;
6102
- }, {});
6103
- }
6104
- serializePartial(value) {
6105
- return Object.entries(value).reduce((acc, [key, value2]) => {
6106
- if (!this.rawShape[key]) {
6107
- console.warn(`No element found for key: ${key}`);
6108
- return acc;
6109
- }
6110
- acc[key] = this.rawShape[key].serialize(value2);
6111
- return acc;
6112
- }, {});
6113
- }
6114
- validatePartial(value) {
6115
- const errors = Object.entries(value).reduce((acc, [key, val]) => {
6116
- if (!this.rawShape[key]) {
6117
- return acc;
6118
- }
6119
- const result = this.rawShape[key].validate(val);
6120
- if (result) {
6121
- acc[key] = result;
6122
- }
6123
- return acc;
6124
- }, {});
6125
- if (Object.keys(errors).length > 0) {
6126
- return { schema: errors };
6127
- }
6128
- return false;
6129
- }
6130
- pick(...keys) {
6131
- return new ArcObject(Object.fromEntries(keys.map((key) => [key, this.rawShape[key]])));
6132
- }
6133
- omit(...keys) {
6134
- return new ArcObject(Object.fromEntries(Object.entries(this.rawShape).filter(([key]) => !keys.includes(key))));
6135
- }
6136
- entries() {
6137
- return Object.entries(this.rawShape);
6138
- }
6139
- keys() {
6140
- return Object.keys(this.rawShape);
6141
- }
6142
- toJsonSchema() {
6143
- const properties = {};
6144
- const required = [];
6145
- for (const [key, element] of Object.entries(this.rawShape)) {
6146
- if (element instanceof ArcOptional) {
6147
- properties[key] = element.parent.toJsonSchema?.() ?? {};
6148
- } else {
6149
- properties[key] = element.toJsonSchema?.() ?? {};
6150
- required.push(key);
6151
- }
6152
- }
6153
- const schema = {
6154
- type: "object",
6155
- properties
6156
- };
6157
- if (required.length)
6158
- schema.required = required;
6159
- if (this._description) {
6160
- schema.description = this._description;
6161
- }
6162
- return schema;
6163
- }
6164
- getColumnData() {
6165
- const storeData = this.getStoreData();
6166
- return {
6167
- type: "object",
6168
- storeData: {
6169
- ...storeData,
6170
- isNullable: false
6171
- }
6172
- };
6173
- }
6174
- merge(otherShape) {
6175
- const mergedShape = { ...this.rawShape, ...otherShape };
6176
- return new ArcObject(mergedShape);
6177
- }
6178
- partial() {
6179
- const partialShape = Object.fromEntries(Object.entries(this.rawShape).map(([key, element]) => [
6180
- key,
6181
- element instanceof ArcOptional ? element : new ArcOptional(element)
6182
- ]));
6183
- return new ArcObject(partialShape);
6184
- }
6185
- }
6186
-
6187
- class ArcPrimitive extends ArcAbstract {
6188
- serialize(value) {
6189
- return value;
6190
- }
6191
- parse(value) {
6192
- return value;
6193
- }
6194
- deserialize(value) {
6195
- return value;
6196
- }
6197
- }
6198
-
6199
- class ArcBoolean extends ArcPrimitive {
6200
- hasToBeTrue() {
6201
- return this.validation("hasToBeTrue", (value) => {
6202
- if (!value)
6203
- return {
6204
- current: value
6205
- };
6206
- });
6207
- }
6208
- validation(name, validator) {
6209
- const instance = this.pipeValidation(name, validator);
6210
- return instance;
6211
- }
6212
- toJsonSchema() {
6213
- const schema = { type: "boolean" };
6214
- if (this._description) {
6215
- schema.description = this._description;
6216
- }
6217
- return schema;
6218
- }
6219
- getColumnData() {
6220
- const storeData = this.getStoreData();
6221
- return {
6222
- type: "boolean",
6223
- storeData: {
6224
- ...storeData,
6225
- isNullable: false
6226
- }
6227
- };
6228
- }
6229
- }
6230
- var stringValidator = typeValidatorBuilder("string");
6231
-
6232
- class ArcString extends ArcPrimitive {
6233
- constructor() {
6234
- super([stringValidator]);
6235
- }
6236
- minLength(min) {
6237
- return this.validation("minLength", (value) => {
6238
- if (value.length < min)
6239
- return {
6240
- currentLength: value.length,
6241
- minLength: min
6242
- };
6243
- });
6244
- }
6245
- maxLength(max) {
6246
- return this.validation("maxLength", (value) => {
6247
- if (value.length > max)
6248
- return {
6249
- currentLength: value.length,
6250
- maxLength: max
6251
- };
6252
- });
6253
- }
6254
- length(number) {
6255
- return this.validation("length", (value) => {
6256
- if (value.length !== number) {
6257
- return {
6258
- currentLength: value.length,
6259
- length: number
6260
- };
6261
- }
6262
- });
6263
- }
6264
- includes(str) {
6265
- return this.validation("includes", (value) => {
6266
- if (!value.includes(str)) {
6267
- return {
6268
- currentValue: value,
6269
- includes: str
6270
- };
6271
- }
6272
- });
6273
- }
6274
- startsWith(str) {
6275
- return this.validation("startsWith", (value) => {
6276
- if (!value.startsWith(str)) {
6277
- return {
6278
- currentValue: value,
6279
- startsWith: str
6280
- };
6281
- }
6282
- });
6283
- }
6284
- endsWith(str) {
6285
- return this.validation("endsWith", (value) => {
6286
- if (!value.endsWith(str)) {
6287
- return {
6288
- currentValue: value,
6289
- endsWith: str
6290
- };
6291
- }
6292
- });
6293
- }
6294
- regex(regex) {
6295
- return this.validation("regex", (value) => {
6296
- if (!regex.test(value)) {
6297
- return {
6298
- currentValue: value,
6299
- regex
6300
- };
6301
- }
6302
- });
6303
- }
6304
- email() {
6305
- 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}\])$/;
6306
- return this.validation("email", (value) => {
6307
- if (!regex.test(value)) {
6308
- return {
6309
- currentEmail: value
6310
- };
6311
- }
6312
- });
6313
- }
6314
- toJsonSchema() {
6315
- const schema = { type: "string" };
6316
- if (this._description) {
6317
- schema.description = this._description;
6318
- }
6319
- return schema;
6320
- }
6321
- url() {
6322
- 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-]*)?$/;
6323
- return this.validation("url", (value) => {
6324
- if (!regex.test(value)) {
6325
- return {
6326
- currentUrl: value
6327
- };
6328
- }
6329
- });
6330
- }
6331
- ip() {
6332
- 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]?)$/;
6333
- 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})$/;
6334
- return this.validation("ip", (value) => {
6335
- if (!(IPv4regex.test(value) || IPv6regex.test(value))) {
6336
- return {
6337
- currentIP: value
6338
- };
6339
- }
6340
- });
6341
- }
6342
- validation(name, validator) {
6343
- const instance = this.pipeValidation(name, validator);
6344
- return instance;
6345
- }
6346
- getColumnData() {
6347
- const storeData = this.getStoreData();
6348
- const validationInfo = {};
6349
- for (const validation of this.validations) {
6350
- switch (validation.name) {
6351
- case "minLength":
6352
- break;
6353
- case "maxLength":
6354
- break;
6355
- case "regex":
6356
- break;
6357
- case "email":
6358
- validationInfo.pattern = "email";
6359
- break;
6360
- case "url":
6361
- validationInfo.pattern = "url";
6362
- break;
6363
- case "ip":
6364
- validationInfo.pattern = "ip";
6365
- break;
6366
- }
6367
- }
6368
- return {
6369
- type: "string",
6370
- storeData: {
6371
- ...storeData,
6372
- isNullable: false
6373
- },
6374
- validationInfo
6375
- };
6376
- }
6377
- }
6378
- function string() {
6379
- return new ArcString;
6380
- }
6381
-
6382
- class ArcId extends ArcBranded {
6383
- generateFn;
6384
- constructor(name, generateFn) {
6385
- super(string(), name);
6386
- this.generateFn = generateFn;
6387
- }
6388
- generate() {
6389
- if (this.generateFn) {
6390
- return this.generateFn();
6391
- }
6392
- var timestamp = (new Date().getTime() / 1000 | 0).toString(16);
6393
- return timestamp + "xxxxxxxxxxxxxxxx".replace(/[x]/g, function() {
6394
- return (Math.random() * 16 | 0).toString(16);
6395
- }).toLowerCase();
6396
- }
6397
- }
6398
- function id(name, generateFn) {
6399
- return new ArcId(name, generateFn);
6400
- }
6401
- var numberValidator = typeValidatorBuilder("number");
6402
-
6403
- class ArcNumber extends ArcPrimitive {
6404
- constructor() {
6405
- super([numberValidator]);
6406
- }
6407
- min(min) {
6408
- return this.validation("min", (value) => {
6409
- if (value < min)
6410
- return { current: value, min };
6411
- });
6412
- }
6413
- max(max) {
6414
- return this.validation("max", (value) => {
6415
- if (value > max)
6416
- return { current: value, max };
6417
- });
6418
- }
6419
- validation(name, validator) {
6420
- const instance = this.pipeValidation(name, validator);
6421
- return instance;
6422
- }
6423
- toJsonSchema() {
6424
- const schema = { type: "number" };
6425
- if (this._description) {
6426
- schema.description = this._description;
6427
- }
6428
- return schema;
6429
- }
6430
- getColumnData() {
6431
- const storeData = this.getStoreData();
6432
- const validationInfo = {};
6433
- for (const validation of this.validations) {
6434
- switch (validation.name) {
6435
- case "min":
6436
- break;
6437
- case "max":
6438
- break;
6439
- }
6440
- }
6441
- return {
6442
- type: "number",
6443
- storeData: {
6444
- ...storeData,
6445
- isNullable: false
6446
- },
6447
- validationInfo
6448
- };
6449
- }
6450
- }
6451
-
6452
- class ArcEvent extends ArcContextElement {
6453
- data;
6454
- eventId = id("event");
6455
- constructor(data) {
6456
- super(data.name);
6457
- this.data = data;
6458
- }
6459
- get payload() {
6460
- return this.data.payload;
6461
- }
6462
- description(description) {
6463
- return new ArcEvent({
6464
- ...this.data,
6465
- description
6466
- });
6467
- }
6468
- mutateContext(adapters) {
6469
- return {
6470
- emit: async (payload) => {
6471
- if (!adapters.eventPublisher) {
6472
- throw new Error(`Event "${this.data.name}" cannot be emitted: no eventPublisher adapter available`);
6473
- }
6474
- const event = {
6475
- type: this.data.name,
6476
- payload,
6477
- id: this.eventId.generate(),
6478
- createdAt: new Date
6479
- };
6480
- await adapters.eventPublisher.publish(event);
6481
- }
6482
- };
6483
- }
6484
- protectBy(token, protectionFn) {
6485
- const existingProtections = this.data.protections || [];
6486
- return new ArcEvent({
6487
- ...this.data,
6488
- protections: [...existingProtections, { token, protectionFn }]
6489
- });
6490
- }
6491
- get hasProtections() {
6492
- return (this.data.protections?.length ?? 0) > 0;
6493
- }
6494
- get protections() {
6495
- return this.data.protections || [];
6496
- }
6497
- getProtectionFor(tokenInstance) {
6498
- if (!this.data.protections) {
6499
- return null;
6500
- }
6501
- for (const protection of this.data.protections) {
6502
- if (tokenInstance.getTokenDefinition() === protection.token) {
6503
- return protection.protectionFn(tokenInstance.params);
6504
- }
6505
- }
6506
- return null;
6507
- }
6508
- tags(tagFields) {
6509
- return new ArcEvent({
6510
- ...this.data,
6511
- tagFields
6512
- });
6513
- }
6514
- get tagFields() {
6515
- return this.data.tagFields || [];
6516
- }
6517
- static _sharedSchema = null;
6518
- static sharedDatabaseStoreSchema() {
6519
- if (ArcEvent._sharedSchema) {
6520
- return ArcEvent._sharedSchema;
6521
- }
6522
- const eventsSchema = new ArcObject({
6523
- _id: new ArcString().primaryKey(),
6524
- type: new ArcString().index(),
6525
- payload: new ArcString,
6526
- createdAt: new ArcString().index()
6527
- });
6528
- const tagsSchema = new ArcObject({
6529
- _id: new ArcString().primaryKey(),
6530
- eventId: new ArcString().foreignKey("events", "_id", {
6531
- onDelete: "CASCADE"
6532
- }),
6533
- tagKey: new ArcString().index(),
6534
- tagValue: new ArcString().index()
6535
- });
6536
- const syncStatusSchema = new ArcObject({
6537
- _id: new ArcString().primaryKey(),
6538
- eventId: new ArcString().foreignKey("events", "_id", {
6539
- onDelete: "CASCADE"
6540
- }),
6541
- synced: new ArcBoolean().index(),
6542
- timestamp: new ArcNumber,
6543
- retryCount: new ArcNumber
6544
- });
6545
- ArcEvent._sharedSchema = {
6546
- tables: [
6547
- { name: "events", schema: eventsSchema },
6548
- { name: "event_tags", schema: tagsSchema },
6549
- { name: "event_sync_status", schema: syncStatusSchema }
6550
- ]
6551
- };
6552
- return ArcEvent._sharedSchema;
6553
- }
6554
- databaseStoreSchema() {
6555
- return ArcEvent.sharedDatabaseStoreSchema();
6556
- }
6557
- }
6558
-
6559
- class DataStorage {
6560
- async commitChanges(changes) {
6561
- await Promise.all(changes.map(({ store, changes: changes2 }) => this.getStore(store).applyChanges(changes2)));
6562
- }
6563
- }
6564
-
6565
- class StoreState {
6566
- storeName;
6567
- dataStorage;
6568
- deserialize;
6569
- listeners = new Map;
6570
- constructor(storeName, dataStorage, deserialize) {
6571
- this.storeName = storeName;
6572
- this.dataStorage = dataStorage;
6573
- this.deserialize = deserialize;
6574
- }
6575
- fork() {
6576
- return new ForkedStoreState(this.storeName, this.dataStorage, this);
6577
- }
6578
- async set(item) {
6579
- const change = {
6580
- type: "set",
6581
- data: item
6582
- };
6583
- await this.applyChanges([change]);
6584
- }
6585
- async remove(id2) {
6586
- const change = {
6587
- type: "delete",
6588
- id: id2
6589
- };
6590
- await this.applyChanges([change]);
6591
- }
6592
- async modify(id2, data) {
6593
- const change = {
6594
- type: "modify",
6595
- id: id2,
6596
- data
6597
- };
6598
- const { from, to } = await this.applyChange(change);
6599
- return { from, to };
6600
- }
6601
- async mutate(id2, editCallback) {
6602
- const result = await this.find({ where: { _id: id2 } });
6603
- const object2 = result[0];
6604
- const [draft, finalize] = create(object2 || {}, { enablePatches: true });
6605
- await editCallback(draft);
6606
- const [_, patches] = finalize();
6607
- const change = {
6608
- type: "mutate",
6609
- id: id2,
6610
- patches
6611
- };
6612
- const { from, to } = await this.applyChange(change);
6613
- return { from, to };
6614
- }
6615
- applySerializedChanges(changes) {
6616
- return Promise.all(changes.map((change) => this.applyChange(change)));
6617
- }
6618
- unsubscribe(listener) {
6619
- this.listeners.delete(listener);
6620
- }
6621
- notifyListeners(events) {
6622
- for (const listener of this.listeners.values()) {
6623
- listener.callback(events);
6624
- }
6625
- }
6626
- }
6627
- function deepMerge(target, source) {
6628
- const output = { ...target };
6629
- for (const key in source) {
6630
- if (source[key] === undefined) {
6631
- output[key] = undefined;
6632
- continue;
6633
- }
6634
- if (isObject(source[key]) && isObject(target[key])) {
6635
- output[key] = deepMerge(target[key], source[key]);
6636
- } else {
6637
- output[key] = source[key];
6638
- }
6639
- }
6640
- return output;
6641
- }
6642
- function isObject(item) {
6643
- return item && typeof item === "object" && !Array.isArray(item);
6644
- }
6645
-
6646
- class ForkedStoreState extends StoreState {
6647
- master;
6648
- changedItems = new Map;
6649
- changes = [];
6650
- constructor(storeName, dataStorage, master) {
6651
- super(storeName, dataStorage, master.deserialize);
6652
- this.master = master;
6653
- }
6654
- async applyChangeAndReturnEvent(change) {
6655
- this.changes.push(change);
6656
- if (change.type === "set") {
6657
- const item = this.deserialize ? this.deserialize(change.data) : change.data;
6658
- this.changedItems.set(change.data._id, item);
6659
- return {
6660
- from: null,
6661
- to: item,
6662
- event: {
6663
- type: "set",
6664
- item: change.data,
6665
- id: change.data._id
6666
- }
6667
- };
6668
- }
6669
- if (change.type === "delete") {
6670
- const from = await this.find({ where: { _id: change.id } }).then((results) => results[0] || null);
6671
- this.changedItems.set(change.id, null);
6672
- return {
6673
- from,
6674
- to: null,
6675
- event: {
6676
- type: "delete",
6677
- item: null,
6678
- id: change.id
6679
- }
6680
- };
6681
- }
6682
- if (change.type === "modify") {
6683
- const existing = await this.find({
6684
- where: { _id: change.id }
6685
- }).then((results) => results[0]);
6686
- const updated = existing ? deepMerge(existing, change.data) : { _id: change.id, ...change.data };
6687
- const item = this.deserialize ? this.deserialize(updated) : updated;
6688
- this.changedItems.set(change.id, item);
6689
- return {
6690
- from: existing || null,
6691
- to: item,
6692
- event: {
6693
- type: "set",
6694
- item,
6695
- id: change.id
6696
- }
6697
- };
6698
- }
6699
- if (change.type === "mutate") {
6700
- const existing = await this.find({
6701
- where: { _id: change.id }
6702
- }).then((results) => results[0]);
6703
- const updated = apply(existing || {}, change.patches);
6704
- const item = this.deserialize ? this.deserialize(updated) : updated;
6705
- this.changedItems.set(change.id, item);
6706
- return {
6707
- from: existing || null,
6708
- to: item,
6709
- event: {
6710
- type: "set",
6711
- item,
6712
- id: change.id
6713
- }
6714
- };
6715
- }
6716
- throw new Error("Unknown change type");
6717
- }
6718
- async applyChange(change) {
6719
- const { event: event3, from, to } = await this.applyChangeAndReturnEvent(change);
6720
- this.notifyListeners([event3]);
6721
- return { from, to };
6722
- }
6723
- async applyChanges(changes) {
6724
- const events = [];
6725
- for (const change of changes) {
6726
- const { event: event3 } = await this.applyChangeAndReturnEvent(change);
6727
- if (event3)
6728
- events.push(event3);
6729
- }
6730
- if (events.length > 0) {
6731
- this.notifyListeners(events);
6732
- }
6733
- }
6734
- async find(options, listener) {
6735
- if (listener) {
6736
- this.listeners.set(listener, { callback: listener });
6737
- }
6738
- const parentResults = await this.master.find(options);
6739
- const results = new Map;
6740
- parentResults.forEach((item) => results.set(item._id, item));
6741
- for (const [id2, changedItem] of this.changedItems) {
6742
- if (changedItem === null) {
6743
- results.delete(id2);
6744
- continue;
6745
- }
6746
- const matches = !options.where || Object.entries(options.where).every(([key, value]) => changedItem[key] === value);
6747
- if (matches) {
6748
- results.set(id2, changedItem);
6749
- } else {
6750
- results.delete(id2);
6751
- }
6752
- }
6753
- return Array.from(results.values());
6754
- }
6755
- }
6756
-
6757
- class ForkedDataStorage extends DataStorage {
6758
- master;
6759
- stores = new Map;
6760
- constructor(master) {
6761
- super();
6762
- this.master = master;
6763
- }
6764
- getReadTransaction() {
6765
- return this.master.getReadTransaction();
6766
- }
6767
- getReadWriteTransaction() {
6768
- return this.master.getReadWriteTransaction();
6769
- }
6770
- getStore(storeName) {
6771
- if (this.stores.has(storeName))
6772
- return this.stores.get(storeName);
6773
- const masterStorage = this.master.getStore(storeName);
6774
- const storage = new ForkedStoreState(storeName, this, masterStorage);
6775
- this.stores.set(storeName, storage);
6776
- return storage;
6777
- }
6778
- fork() {
6779
- return new ForkedDataStorage(this);
6780
- }
6781
- async merge() {
6782
- const changes = Array.from(this.stores.values()).filter((store) => store.changes.length > 0).map((store) => ({
6783
- store: store.storeName,
6784
- changes: store.changes
6785
- }));
6786
- await this.master.commitChanges(changes);
6787
- }
6788
- }
6789
-
6790
- class MasterStoreState extends StoreState {
6791
- constructor(storeName, dataStorage, deserialize) {
6792
- super(storeName, dataStorage, deserialize);
6793
- }
6794
- async applyChangeAndReturnEvent(transaction, change, transactionCache) {
6795
- if (change.type === "set") {
6796
- await transaction.set(this.storeName, change.data);
6797
- const item = this.deserialize ? this.deserialize(change.data) : change.data;
6798
- if (transactionCache) {
6799
- transactionCache.set(change.data._id, item);
6800
- }
6801
- return {
6802
- from: null,
6803
- to: item,
6804
- event: {
6805
- type: "set",
6806
- item: change.data,
6807
- id: change.data._id
6808
- }
6809
- };
6810
- }
6811
- if (change.type === "delete") {
6812
- await transaction.remove(this.storeName, change.id);
6813
- return {
6814
- from: null,
6815
- to: null,
6816
- event: {
6817
- type: "delete",
6818
- item: null,
6819
- id: change.id
6820
- }
6821
- };
6822
- }
6823
- if (change.type === "modify") {
6824
- let existing;
6825
- if (transactionCache && transactionCache.has(change.id)) {
6826
- existing = transactionCache.get(change.id);
6827
- } else {
6828
- existing = await transaction.find(this.storeName, { where: { _id: change.id } }).then((results) => results[0]);
6829
- }
6830
- const updated = existing ? deepMerge(existing, change.data) : { _id: change.id, ...change.data };
6831
- await transaction.set(this.storeName, updated);
6832
- const item = this.deserialize ? this.deserialize(updated) : updated;
6833
- if (transactionCache) {
6834
- transactionCache.set(change.id, item);
6835
- }
6836
- return {
6837
- from: null,
6838
- to: item,
6839
- event: {
6840
- type: "set",
6841
- item,
6842
- id: change.id
6843
- }
6844
- };
6845
- }
6846
- if (change.type === "mutate") {
6847
- let existing;
6848
- if (transactionCache && transactionCache.has(change.id)) {
6849
- existing = transactionCache.get(change.id);
6850
- } else {
6851
- existing = await transaction.find(this.storeName, { where: { _id: change.id } }).then((results) => results[0]);
6852
- }
6853
- const updated = apply(existing || {}, change.patches);
6854
- await transaction.set(this.storeName, updated);
6855
- const item = this.deserialize ? this.deserialize(updated) : updated;
6856
- if (transactionCache) {
6857
- transactionCache.set(change.id, item);
6858
- }
6859
- return {
6860
- from: null,
6861
- to: item,
6862
- event: {
6863
- type: "set",
6864
- item,
6865
- id: change.id
6866
- }
6867
- };
6868
- }
6869
- throw new Error("Unknown change type");
6870
- }
6871
- async applyChange(change) {
6872
- const transaction = await this.dataStorage.getReadWriteTransaction();
6873
- const transactionCache = new Map;
6874
- const { event: event3, from, to } = await this.applyChangeAndReturnEvent(transaction, change, transactionCache);
6875
- await transaction.commit();
6876
- this.notifyListeners([event3]);
6877
- return { from, to };
6878
- }
6879
- async applyChanges(changes) {
6880
- const transaction = await this.dataStorage.getReadWriteTransaction();
6881
- const transactionCache = new Map;
6882
- const events = [];
6883
- for (const change of changes) {
6884
- const { event: event3 } = await this.applyChangeAndReturnEvent(transaction, change, transactionCache);
6885
- if (event3)
6886
- events.push(event3);
6887
- }
6888
- await transaction.commit();
6889
- if (events.length > 0) {
6890
- this.notifyListeners(events);
6891
- }
6892
- }
6893
- async find(options, listener) {
6894
- if (listener) {
6895
- this.listeners.set(listener, { callback: listener });
6896
- }
6897
- const transaction = await this.dataStorage.getReadTransaction();
6898
- const results = await transaction.find(this.storeName, options);
6899
- return results.map((item) => this.deserialize ? this.deserialize(item) : item);
6900
- }
6901
- notifyListenersPublic(events) {
6902
- this.notifyListeners(events);
6903
- }
6904
- }
6905
-
6906
- class MasterDataStorage2 extends DataStorage {
6907
- dbAdapter;
6908
- stores = new Map;
6909
- reinitTablesExecuted = false;
6910
- constructor(dbAdapter) {
6911
- super();
6912
- this.dbAdapter = dbAdapter;
6913
- this.executeReinitTablesOnReady();
6914
- }
6915
- async executeReinitTablesOnReady() {
6916
- try {
6917
- const adapter = await this.dbAdapter;
6918
- if (!this.reinitTablesExecuted) {
6919
- await adapter.executeReinitTables(this);
6920
- this.reinitTablesExecuted = true;
6921
- }
6922
- } catch (error) {
6923
- console.error("Failed to execute reinitTable functions:", error);
6924
- }
6925
- }
6926
- async getReadTransaction() {
6927
- return (await this.dbAdapter).readTransaction();
6928
- }
6929
- async getReadWriteTransaction() {
6930
- return (await this.dbAdapter).readWriteTransaction();
6931
- }
6932
- getStore(storeName) {
6933
- if (!this.stores.has(storeName)) {
6934
- this.stores.set(storeName, new MasterStoreState(storeName, this));
6935
- }
6936
- return this.stores.get(storeName);
6937
- }
6938
- async applyChanges(changes) {
6939
- return Promise.all(changes.map(({ store, changes: changes2 }) => this.getStore(store).applyChanges(changes2)));
6940
- }
6941
- applySerializedChanges(changes) {
6942
- return Promise.all(changes.map(({ store, changes: changes2 }) => this.getStore(store).applySerializedChanges(changes2)));
6943
- }
6944
- async commitChanges(changes) {
6945
- const transaction = await this.getReadWriteTransaction();
6946
- const transactionCache = new Map;
6947
- const eventsByStore = new Map;
6948
- for (const { store, changes: storeChanges } of changes) {
6949
- const storeState = this.getStore(store);
6950
- const storeEvents = [];
6951
- for (const change of storeChanges) {
6952
- const { event: event3 } = await storeState.applyChangeAndReturnEvent(transaction, change, transactionCache);
6953
- if (event3)
6954
- storeEvents.push(event3);
6955
- }
6956
- if (storeEvents.length > 0) {
6957
- eventsByStore.set(store, storeEvents);
6958
- }
6959
- }
6960
- await transaction.commit();
6961
- for (const [store, events] of eventsByStore) {
6962
- const storeState = this.getStore(store);
6963
- storeState.notifyListenersPublic(events);
6964
- }
6965
- }
6966
- fork() {
6967
- return new ForkedDataStorage(this);
6968
- }
6969
- async destroy() {
6970
- const adapter = await this.dbAdapter;
6971
- if (adapter.destroy) {
6972
- await adapter.destroy();
6973
- }
6974
- this.stores.clear();
6975
- this.reinitTablesExecuted = false;
6976
- }
6977
- }
6978
- function resolveQueryChange(currentResult, event3, options) {
6979
- const index = currentResult.findIndex((e) => e._id === event3.id);
6980
- const isInCurrentResult = index !== -1;
6981
- if (event3.type === "delete") {
6982
- if (isInCurrentResult) {
6983
- return currentResult.toSpliced(index, 1);
6984
- }
6985
- return false;
6986
- }
6987
- const shouldBeInResult = checkItemMatchesWhere(event3.item, options.where);
6988
- if (isInCurrentResult && shouldBeInResult) {
6989
- const newResult = currentResult.toSpliced(index, 1, event3.item);
6990
- return applyOrderByAndLimit(newResult, options);
6991
- } else if (isInCurrentResult && !shouldBeInResult) {
6992
- return currentResult.toSpliced(index, 1);
6993
- } else if (!isInCurrentResult && shouldBeInResult) {
6994
- const newResult = [...currentResult, event3.item];
6995
- return applyOrderByAndLimit(newResult, options);
6996
- }
6997
- return false;
6998
- }
6999
- function checkItemMatchesWhere(item, where) {
7000
- if (!where) {
7001
- return true;
7002
- }
7003
- return Object.entries(where).every(([key, condition]) => {
7004
- const value = item[key];
7005
- if (typeof condition !== "object" || condition === null) {
7006
- return value === condition;
7007
- }
7008
- return Object.entries(condition).every(([operator, operand]) => {
7009
- switch (operator) {
7010
- case "$eq":
7011
- return value === operand;
7012
- case "$ne":
7013
- return value !== operand;
7014
- case "$gt":
7015
- return typeof value === "number" && typeof operand === "number" && value > operand;
7016
- case "$gte":
7017
- return typeof value === "number" && typeof operand === "number" && value >= operand;
7018
- case "$lt":
7019
- return typeof value === "number" && typeof operand === "number" && value < operand;
7020
- case "$lte":
7021
- return typeof value === "number" && typeof operand === "number" && value <= operand;
7022
- case "$in":
7023
- return Array.isArray(operand) && operand.includes(value);
7024
- case "$nin":
7025
- return Array.isArray(operand) && !operand.includes(value);
7026
- case "$exists":
7027
- return typeof operand === "boolean" ? operand ? value !== undefined : value === undefined : true;
7028
- default:
7029
- return true;
7030
- }
7031
- });
7032
- });
7033
- }
7034
- function applyOrderByAndLimit(result, options) {
7035
- let sorted = result;
7036
- if (options.orderBy) {
7037
- sorted = [...result].sort((a, b) => {
7038
- for (const [key, direction] of Object.entries(options.orderBy)) {
7039
- const aVal = a[key];
7040
- const bVal = b[key];
7041
- if (aVal < bVal)
7042
- return direction === "asc" ? -1 : 1;
7043
- if (aVal > bVal)
7044
- return direction === "asc" ? 1 : -1;
7045
- }
7046
- return 0;
7047
- });
7048
- }
7049
- if (options.limit !== undefined) {
7050
- sorted = sorted.slice(0, options.limit);
7051
- }
7052
- return sorted;
7053
- }
7054
-
7055
- class ObservableDataStorage {
7056
- source;
7057
- onChange;
7058
- trackedQueries = new Map;
7059
- stores = new Map;
7060
- constructor(source, onChange) {
7061
- this.source = source;
7062
- this.onChange = onChange;
7063
- }
7064
- getStore(storeName) {
7065
- if (!this.stores.has(storeName)) {
7066
- this.stores.set(storeName, new ObservableStoreState(storeName, this.source.getStore(storeName), this));
7067
- }
7068
- return this.stores.get(storeName);
7069
- }
7070
- fork() {
7071
- return this.source.fork();
7072
- }
7073
- getReadTransaction() {
7074
- return this.source.getReadTransaction();
7075
- }
7076
- getReadWriteTransaction() {
7077
- return this.source.getReadWriteTransaction();
7078
- }
7079
- commitChanges(changes) {
7080
- return this.source.commitChanges(changes);
7081
- }
7082
- trackQuery(storeName, options, result, listener) {
7083
- const key = this.getQueryKey(storeName, options);
7084
- this.trackedQueries.set(key, {
7085
- storeName,
7086
- options,
7087
- result,
7088
- listener
7089
- });
7090
- }
7091
- handleStoreChange(storeName, events) {
7092
- let hasChanges = false;
7093
- for (const query of this.trackedQueries.values()) {
7094
- if (query.storeName !== storeName)
7095
- continue;
7096
- let currentResult = query.result;
7097
- let queryChanged = false;
7098
- for (const event3 of events) {
7099
- const newResult = resolveQueryChange(currentResult, event3, query.options);
7100
- if (newResult !== false) {
7101
- currentResult = newResult;
7102
- queryChanged = true;
7103
- }
7104
- }
7105
- if (queryChanged) {
7106
- query.result = currentResult;
7107
- hasChanges = true;
7108
- }
7109
- }
7110
- if (hasChanges) {
7111
- this.onChange();
7112
- }
7113
- }
7114
- getCachedResult(storeName, options) {
7115
- const key = this.getQueryKey(storeName, options);
7116
- return this.trackedQueries.get(key)?.result;
7117
- }
7118
- clear() {
7119
- for (const query of this.trackedQueries.values()) {
7120
- const sourceStore = this.source.getStore(query.storeName);
7121
- sourceStore.unsubscribe(query.listener);
7122
- }
7123
- this.trackedQueries.clear();
7124
- this.stores.clear();
7125
- }
7126
- getQueryKey(storeName, options) {
7127
- return `${storeName}:${JSON.stringify(options || {})}`;
7128
- }
7129
- }
7130
-
7131
- class ObservableStoreState {
7132
- source;
7133
- observable;
7134
- storeName;
7135
- constructor(storeName, source, observable) {
7136
- this.source = source;
7137
- this.observable = observable;
7138
- this.storeName = storeName;
7139
- }
7140
- async find(options = {}, _existingListener) {
7141
- const cached = this.observable.getCachedResult(this.storeName, options);
7142
- if (cached !== undefined) {
7143
- return cached;
7144
- }
7145
- const listener = (events) => {
7146
- this.observable.handleStoreChange(this.storeName, events);
7147
- };
7148
- const result = await this.source.find(options, listener);
7149
- this.observable.trackQuery(this.storeName, options, result, listener);
7150
- return result;
7151
- }
7152
- unsubscribe(listener) {
7153
- this.source.unsubscribe(listener);
7154
- }
7155
- async set(item) {
7156
- return this.source.set(item);
7157
- }
7158
- async remove(id2) {
7159
- return this.source.remove(id2);
7160
- }
7161
- async modify(id2, data) {
7162
- return this.source.modify(id2, data);
7163
- }
7164
- async mutate(id2, editCallback) {
7165
- return this.source.mutate(id2, editCallback);
7166
- }
7167
- fork() {
7168
- return this.source.fork();
7169
- }
7170
- applyChange(change) {
7171
- return this.source.applyChange(change);
7172
- }
7173
- applyChanges(changes) {
7174
- return this.source.applyChanges(changes);
7175
- }
7176
- applySerializedChanges(changes) {
7177
- return this.source.applySerializedChanges(changes);
7178
- }
7179
- }
7180
- function extractDatabaseAgnosticSchema(arcObject, tableName) {
7181
- const columns = [];
7182
- for (const [fieldName, fieldSchema] of arcObject.entries()) {
7183
- const arcElement = fieldSchema;
7184
- if (typeof arcElement.getColumnData !== "function") {
7185
- throw new Error(`Element for field '${fieldName}' does not implement getColumnData() method. Element type: ${arcElement.constructor.name}`);
7186
- }
7187
- const columnInfo = arcElement.getColumnData();
7188
- const fullColumnInfo = {
7189
- name: fieldName,
7190
- ...columnInfo
7191
- };
7192
- columns.push(fullColumnInfo);
7193
- }
7194
- return {
7195
- tableName,
7196
- columns
7197
- };
7198
- }
7199
- var dateValidator = typeValidatorBuilder("Date", (value) => value instanceof Date);
7200
-
7201
- class SecuredStoreState {
7202
- store;
7203
- tokenInstance;
7204
- storeName;
7205
- context;
7206
- protection;
7207
- constructor(store, tokenInstance, storeName, context2) {
7208
- this.store = store;
7209
- this.tokenInstance = tokenInstance;
7210
- this.storeName = storeName;
7211
- this.context = context2;
7212
- this.protection = this.getProtectionFromContext();
7213
- }
7214
- getProtectionFromContext() {
7215
- if (!this.context) {
7216
- return null;
7217
- }
7218
- const view3 = this.context.elements.find((el) => el.name === this.storeName);
7219
- if (!view3 || !("getProtectionFor" in view3)) {
7220
- return null;
7221
- }
7222
- return view3.getProtectionFor(this.tokenInstance);
7223
- }
7224
- async find(options = {}) {
7225
- const securedOptions = this.applyTokenCondition(options, "read");
7226
- if (securedOptions === null) {
7227
- return [];
7228
- }
7229
- return this.store.find(securedOptions);
7230
- }
7231
- async set(item) {
7232
- if (!this.canWrite()) {
7233
- throw new Error(`Write access denied for store "${this.storeName}" with token "${this.tokenInstance.name}"`);
7234
- }
7235
- const writeCondition = this.getWriteCondition();
7236
- if (writeCondition) {
7237
- if (!this.itemMatchesCondition(item, writeCondition)) {
7238
- throw new Error(`Item does not match write condition for store "${this.storeName}"`);
7239
- }
7240
- }
7241
- return this.store.set(item);
7242
- }
7243
- async remove(id3) {
7244
- if (!this.canWrite()) {
7245
- throw new Error(`Write access denied for store "${this.storeName}" with token "${this.tokenInstance.name}"`);
7246
- }
7247
- return this.store.remove(id3);
7248
- }
7249
- async modify(id3, data) {
7250
- if (!this.canWrite()) {
7251
- throw new Error(`Write access denied for store "${this.storeName}" with token "${this.tokenInstance.name}"`);
7252
- }
7253
- return this.store.modify(id3, data);
7254
- }
7255
- async applyChanges(changes) {
7256
- if (!this.canWrite()) {
7257
- throw new Error(`Write access denied for store "${this.storeName}" with token "${this.tokenInstance.name}"`);
7258
- }
7259
- return this.store.applyChanges(changes);
7260
- }
7261
- fork() {
7262
- return this.store.fork();
7263
- }
7264
- applyTokenCondition(options, operation) {
7265
- if (!this.protection) {
7266
- return options;
7267
- }
7268
- const condition = operation === "read" ? this.protection.read : this.protection.write;
7269
- if (condition === false) {
7270
- return null;
7271
- }
7272
- const mergedWhere = {
7273
- ...options.where,
7274
- ...condition
7275
- };
7276
- return {
7277
- ...options,
7278
- where: mergedWhere
7279
- };
7280
- }
7281
- canWrite() {
7282
- if (!this.protection) {
7283
- return true;
7284
- }
7285
- return this.protection.write !== false;
7286
- }
7287
- getWriteCondition() {
7288
- if (!this.protection || this.protection.write === false) {
7289
- return null;
7290
- }
7291
- return this.protection.write || null;
7292
- }
7293
- itemMatchesCondition(item, condition) {
7294
- for (const [key, value] of Object.entries(condition)) {
7295
- if (item[key] !== value) {
7296
- return false;
7297
- }
7298
- }
7299
- return true;
7300
- }
7301
- }
7302
-
7303
- class SecuredDataStorage {
7304
- dataStorage;
7305
- tokenInstance;
7306
- context;
7307
- storeCache = new Map;
7308
- constructor(dataStorage, tokenInstance, context2) {
7309
- this.dataStorage = dataStorage;
7310
- this.tokenInstance = tokenInstance;
7311
- this.context = context2;
7312
- }
7313
- getStore(storeName) {
7314
- let securedStore = this.storeCache.get(storeName);
7315
- if (!securedStore) {
7316
- const store = this.dataStorage.getStore(storeName);
7317
- securedStore = new SecuredStoreState(store, this.tokenInstance, storeName, this.context);
7318
- this.storeCache.set(storeName, securedStore);
7319
- }
7320
- return securedStore;
7321
- }
7322
- getUnsecuredStorage() {
7323
- return this.dataStorage;
7324
- }
7325
- getTokenInstance() {
7326
- return this.tokenInstance;
7327
- }
7328
- fork() {
7329
- return this.dataStorage.fork();
7330
- }
7331
- }
7332
-
7333
- class TokenCache {
7334
- instanceCache = new Map;
7335
- permissionCache = new Map;
7336
- ttl;
7337
- maxSize;
7338
- constructor(options = {}) {
7339
- this.ttl = options.ttl ?? 5 * 60 * 1000;
7340
- this.maxSize = options.maxSize ?? 1000;
7341
- }
7342
- async getOrCreate(jwt2, factory) {
7343
- const cached = this.instanceCache.get(jwt2);
7344
- if (cached && cached.expiresAt > Date.now()) {
7345
- return cached.value;
7346
- }
7347
- const instance = await factory();
7348
- if (instance) {
7349
- this.setInstance(jwt2, instance);
7350
- }
7351
- return instance;
7352
- }
7353
- async getPermission(instance, permission, factory) {
7354
- const key = this.getPermissionKey(instance, permission);
7355
- const cached = this.permissionCache.get(key);
7356
- if (cached && cached.expiresAt > Date.now()) {
7357
- return cached.value;
7358
- }
7359
- const result = await factory();
7360
- this.setPermission(key, result);
7361
- return result;
7362
- }
7363
- setInstance(jwt2, instance) {
7364
- this.ensureCapacity(this.instanceCache);
7365
- this.instanceCache.set(jwt2, {
7366
- value: instance,
7367
- expiresAt: Date.now() + this.ttl
7368
- });
7369
- }
7370
- setPermission(key, result) {
7371
- this.ensureCapacity(this.permissionCache);
7372
- this.permissionCache.set(key, {
7373
- value: result,
7374
- expiresAt: Date.now() + this.ttl
7375
- });
7376
- }
7377
- getPermissionKey(instance, permission) {
7378
- return `${instance.name}:${JSON.stringify(instance.params)}:${permission}`;
7379
- }
7380
- ensureCapacity(cache) {
7381
- if (cache.size >= this.maxSize) {
7382
- const toRemove = Math.floor(this.maxSize * 0.1);
7383
- const keys = Array.from(cache.keys()).slice(0, toRemove);
7384
- for (const key of keys) {
7385
- cache.delete(key);
7386
- }
7387
- }
7388
- }
7389
- invalidateInstance(instance) {
7390
- const prefix = `${instance.name}:${JSON.stringify(instance.params)}:`;
7391
- for (const key of this.permissionCache.keys()) {
7392
- if (key.startsWith(prefix)) {
7393
- this.permissionCache.delete(key);
7394
- }
7395
- }
7396
- }
7397
- invalidateJWT(jwt2) {
7398
- const instance = this.instanceCache.get(jwt2)?.value;
7399
- this.instanceCache.delete(jwt2);
7400
- if (instance) {
7401
- this.invalidateInstance(instance);
7402
- }
7403
- }
7404
- clear() {
7405
- this.instanceCache.clear();
7406
- this.permissionCache.clear();
7407
- }
7408
- cleanup() {
7409
- const now = Date.now();
7410
- for (const [key, entry] of this.instanceCache) {
7411
- if (entry.expiresAt <= now) {
7412
- this.instanceCache.delete(key);
7413
- }
7414
- }
7415
- for (const [key, entry] of this.permissionCache) {
7416
- if (entry.expiresAt <= now) {
7417
- this.permissionCache.delete(key);
7418
- }
7419
- }
7420
- }
7421
- getStats() {
7422
- return {
7423
- instanceCount: this.instanceCache.size,
7424
- permissionCount: this.permissionCache.size,
7425
- maxSize: this.maxSize,
7426
- ttl: this.ttl
7427
- };
7428
- }
7429
- }
7430
-
7431
- class SQLiteReadTransaction {
7432
- db;
7433
- tables;
7434
- adapter;
7435
- constructor(db, tables, adapter) {
7436
- this.db = db;
7437
- this.tables = tables;
7438
- this.adapter = adapter;
7439
- }
7440
- hasSoftDelete(tableName) {
7441
- if (this.adapter) {
7442
- return this.adapter.hasSoftDelete(tableName);
7443
- }
7444
- const table = this.tables.get(tableName);
7445
- if (!table)
7446
- return false;
7447
- return table.columns.some((col) => col.name === "deleted");
7448
- }
7449
- deserializeValue(value, column) {
7450
- if (value === null || value === undefined)
7451
- return null;
7452
- switch (column.type.toLowerCase()) {
7453
- case "json":
7454
- if (typeof value === "string") {
7455
- try {
7456
- return JSON.parse(value);
7457
- } catch {
7458
- return value;
7459
- }
7460
- }
7461
- return value;
7462
- case "text":
7463
- if (typeof value === "string" && (value.startsWith("{") || value.startsWith("["))) {
7464
- try {
7465
- const parsed = JSON.parse(value);
7466
- if (typeof parsed === "object" || Array.isArray(parsed)) {
7467
- return parsed;
7468
- }
7469
- } catch {}
7470
- }
7471
- return value;
7472
- case "datetime":
7473
- case "timestamp":
7474
- return new Date(value);
7475
- default:
7476
- return value;
7477
- }
7478
- }
7479
- deserializeRow(row, table) {
7480
- const result = {};
7481
- for (const column of table.columns) {
7482
- const value = row[column.name];
7483
- result[column.name] = this.deserializeValue(value, column);
7484
- }
7485
- return result;
7486
- }
7487
- getId(store, id2) {
7488
- return id2;
7489
- }
7490
- buildWhereClause(where, tableName) {
7491
- const conditions = [];
7492
- const params = [];
7493
- if (tableName && this.hasSoftDelete(tableName)) {
7494
- conditions.push('"deleted" = 0');
7495
- }
7496
- if (!where) {
7497
- return {
7498
- sql: conditions.length > 0 ? conditions.join(" AND ") : "1=1",
7499
- params
7500
- };
7501
- }
7502
- Object.entries(where).forEach(([key, value]) => {
7503
- if (typeof value === "object" && value !== null) {
7504
- Object.entries(value).forEach(([operator, operand]) => {
7505
- switch (operator) {
7506
- case "$eq":
7507
- case "$ne":
7508
- case "$gt":
7509
- case "$gte":
7510
- case "$lt":
7511
- case "$lte":
7512
- conditions.push(`"${key}" ${this.getOperatorSymbol(operator)} ?`);
7513
- params.push(operand);
7514
- break;
7515
- case "$in":
7516
- case "$nin":
7517
- if (Array.isArray(operand)) {
7518
- conditions.push(`"${key}" ${operator === "$in" ? "IN" : "NOT IN"} (${operand.map(() => "?").join(", ")})`);
7519
- params.push(...operand);
7520
- }
7521
- break;
7522
- case "$exists":
7523
- if (typeof operand === "boolean") {
7524
- conditions.push(operand ? `"${key}" IS NOT NULL` : `"${key}" IS NULL`);
7525
- }
7526
- break;
7527
- }
7528
- });
7529
- } else {
7530
- conditions.push(`"${key}" = ?`);
7531
- params.push(value);
7532
- }
7533
- });
7534
- return {
7535
- sql: conditions.join(" AND "),
7536
- params
7537
- };
7538
- }
7539
- getOperatorSymbol(operator) {
7540
- const operators = {
7541
- $eq: "=",
7542
- $ne: "!=",
7543
- $gt: ">",
7544
- $gte: ">=",
7545
- $lt: "<",
7546
- $lte: "<="
7547
- };
7548
- return operators[operator] || "=";
7549
- }
7550
- buildOrderByClause(orderBy) {
7551
- if (!orderBy)
7552
- return "";
7553
- const orderClauses = Object.entries(orderBy).map(([key, direction]) => `"${key}" ${direction.toUpperCase()}`).join(", ");
7554
- return orderClauses ? `ORDER BY ${orderClauses}` : "";
7555
- }
7556
- async find(store, options) {
7557
- const { where, limit, offset, orderBy } = options || {};
7558
- const whereClause = this.buildWhereClause(where, store);
7559
- const orderByClause = this.buildOrderByClause(orderBy);
7560
- const table = this.tables.get(store);
7561
- if (!table) {
7562
- throw new Error(`Store ${store} not found`);
7563
- }
7564
- const query = `
7565
- SELECT *
7566
- FROM "${table.name}"
7567
- WHERE ${whereClause.sql}
7568
- ${orderByClause}
7569
- ${limit ? `LIMIT ${limit}` : ""}
7570
- ${offset ? `OFFSET ${offset}` : ""}
7571
- `;
7572
- const rows = await this.db.exec(query, whereClause.params);
7573
- return rows.map((row) => this.deserializeRow(row, table));
7574
- }
7575
- }
7576
-
7577
- class SQLiteReadWriteTransaction extends SQLiteReadTransaction {
7578
- adapter;
7579
- queries = [];
7580
- constructor(db, tables, adapter) {
7581
- super(db, tables);
7582
- this.adapter = adapter;
7583
- }
7584
- async remove(store, id2) {
7585
- const table = this.tables.get(store);
7586
- if (!table) {
7587
- throw new Error(`Store ${store} not found`);
7588
- }
7589
- const hasSoftDelete = this.adapter.hasSoftDelete(store);
7590
- if (hasSoftDelete) {
7591
- const query = `UPDATE "${table.name}" SET "deleted" = 1, "lastUpdate" = ? WHERE "${table.primaryKey}" = ?`;
7592
- this.queries.push({
7593
- sql: query,
7594
- params: [new Date().toISOString(), id2]
7595
- });
7596
- } else {
7597
- const query = `DELETE FROM "${table.name}" WHERE "${table.primaryKey}" = ?`;
7598
- this.queries.push({
7599
- sql: query,
7600
- params: [id2]
7601
- });
7602
- }
7603
- }
7604
- async set(store, item) {
7605
- const table = this.tables.get(store);
7606
- if (!table) {
7607
- throw new Error(`Store ${store} not found`);
7608
- }
7609
- const hasVersioning = this.adapter.hasVersioning(store);
7610
- if (hasVersioning) {
7611
- await this.setWithVersioning(store, item, table);
7612
- } else {
7613
- await this.setWithoutVersioning(store, item, table);
7614
- }
7615
- }
7616
- async setWithoutVersioning(store, item, table) {
7617
- const columnNames = table.columns.map((col) => col.name);
7618
- const values = table.columns.map((column) => {
7619
- let value = item[column.name];
7620
- if (value === undefined && column.default !== undefined) {
7621
- value = column.default;
7622
- }
7623
- return this.serializeValue(value, column);
7624
- });
7625
- const placeholders = columnNames.map(() => "?").join(", ");
7626
- if (store === "events") {
7627
- const simpleInsertSql = `
7628
- INSERT INTO "${table.name}"
7629
- (${columnNames.map((c) => `"${c}"`).join(", ")})
7630
- VALUES (${placeholders})
7631
- `;
7632
- this.queries.push({
7633
- sql: simpleInsertSql,
7634
- params: values
7635
- });
7636
- } else {
7637
- const sql = `
7638
- INSERT OR REPLACE INTO "${table.name}"
7639
- (${columnNames.map((c) => `"${c}"`).join(", ")})
7640
- VALUES (${placeholders})
7641
- `;
7642
- this.queries.push({
7643
- sql,
7644
- params: values
7645
- });
7646
- }
7647
- }
7648
- async setWithVersioning(store, item, table) {
7649
- const regularColumns = table.columns.filter((col) => col.name !== "__version");
7650
- const columnNames = regularColumns.map((col) => col.name);
7651
- const values = regularColumns.map((column) => {
7652
- let value = item[column.name];
7653
- if (value === undefined && column.default !== undefined) {
7654
- value = column.default;
7655
- }
7656
- return this.serializeValue(value, column);
7657
- });
7658
- columnNames.push("__version");
7659
- const placeholders = regularColumns.map(() => "?").join(", ");
7660
- const sql = `
7661
- WITH next_version AS (
7662
- INSERT INTO __arc_version_counters (table_name, last_version)
7663
- VALUES (?, 1)
7664
- ON CONFLICT(table_name)
7665
- DO UPDATE SET last_version = last_version + 1
7666
- RETURNING last_version
7667
- )
7668
- INSERT OR REPLACE INTO "${table.name}"
7669
- (${columnNames.map((c) => `"${c}"`).join(", ")})
7670
- VALUES (${placeholders}, (SELECT last_version FROM next_version))
7671
- `;
7672
- this.queries.push({
7673
- sql,
7674
- params: [...values, store]
7675
- });
7676
- }
7677
- async commit() {
7678
- if (this.queries.length === 0) {
7679
- return Promise.resolve();
7680
- }
7681
- try {
7682
- await this.db.execBatch(this.queries);
7683
- this.queries = [];
7684
- } catch (error) {
7685
- this.queries = [];
7686
- throw error;
7687
- }
7688
- }
7689
- serializeValue(value, column) {
7690
- if (value === null || value === undefined)
7691
- return null;
7692
- switch (column.type.toLowerCase()) {
7693
- case "timestamp":
7694
- case "datetime":
7695
- if (value instanceof Date) {
7696
- return value.toISOString();
7697
- }
7698
- if (typeof value === "number") {
7699
- const date = value > 10000000000 ? new Date(value) : new Date(value * 1000);
7700
- return date.toISOString();
7701
- }
7702
- if (typeof value === "string") {
7703
- const date = new Date(value);
7704
- if (!isNaN(date.getTime())) {
7705
- return date.toISOString();
7706
- }
7707
- }
7708
- return value;
7709
- case "json":
7710
- return JSON.stringify(value);
7711
- default:
7712
- if (value instanceof Date) {
7713
- return value.toISOString();
7714
- }
7715
- if (Array.isArray(value) || typeof value === "object") {
7716
- return JSON.stringify(value);
7717
- }
7718
- return value;
7719
- }
7720
- }
7721
- }
7722
-
7723
- class SQLiteAdapter {
7724
- db;
7725
- context;
7726
- tables = new Map;
7727
- tableSchemas = new Map;
7728
- pendingReinitTables = [];
7729
- mapType(arcType, storeData) {
7730
- if (storeData?.databaseType?.sqlite) {
7731
- return storeData.databaseType.sqlite;
7732
- }
7733
- switch (arcType) {
7734
- case "string":
7735
- case "id":
7736
- case "customId":
7737
- case "stringEnum":
7738
- return "TEXT";
7739
- case "number":
7740
- return "INTEGER";
7741
- case "boolean":
7742
- return "INTEGER";
7743
- case "date":
7744
- return "TIMESTAMP";
7745
- case "object":
7746
- case "array":
7747
- case "record":
7748
- return "JSON";
7749
- case "blob":
7750
- return "BLOB";
7751
- default:
7752
- return "TEXT";
7753
- }
7754
- }
7755
- buildConstraints(storeData) {
7756
- const constraints = [];
7757
- if (storeData?.isPrimaryKey) {
7758
- constraints.push("PRIMARY KEY");
7759
- }
7760
- if (storeData?.isAutoIncrement) {
7761
- constraints.push("AUTOINCREMENT");
7762
- }
7763
- if (storeData?.isUnique) {
7764
- constraints.push("UNIQUE");
7765
- }
7766
- if (storeData?.foreignKey) {
7767
- const { table, column, onDelete, onUpdate } = storeData.foreignKey;
7768
- let fkConstraint = `REFERENCES ${table}(${column})`;
7769
- if (onDelete)
7770
- fkConstraint += ` ON DELETE ${onDelete}`;
7771
- if (onUpdate)
7772
- fkConstraint += ` ON UPDATE ${onUpdate}`;
7773
- constraints.push(fkConstraint);
7774
- }
7775
- return constraints;
7776
- }
7777
- generateColumnSQL(columnInfo) {
7778
- const type = this.mapType(columnInfo.type, columnInfo.storeData);
7779
- const constraints = [];
7780
- if (!columnInfo.storeData?.isNullable) {
7781
- constraints.push("NOT NULL");
7782
- }
7783
- constraints.push(...this.buildConstraints(columnInfo.storeData));
7784
- if (columnInfo.defaultValue !== undefined) {
7785
- if (typeof columnInfo.defaultValue === "string") {
7786
- constraints.push(`DEFAULT '${columnInfo.defaultValue}'`);
7787
- } else {
7788
- constraints.push(`DEFAULT ${columnInfo.defaultValue}`);
7789
- }
7790
- }
7791
- return `"${columnInfo.name}" ${type} ${constraints.join(" ")}`.trim();
7792
- }
7793
- generateCreateTableSQL(tableName, columns) {
7794
- const columnDefinitions = columns.map((col) => this.generateColumnSQL(col));
7795
- const indexes = columns.filter((col) => col.storeData?.hasIndex && !col.storeData?.isPrimaryKey).map((col) => `CREATE INDEX IF NOT EXISTS idx_${tableName}_${col.name} ON "${tableName}"("${col.name}");`);
7796
- let sql = `CREATE TABLE IF NOT EXISTS "${tableName}" (
7797
- ${columnDefinitions.join(`,
7798
- `)}
7799
- )`;
7800
- if (indexes.length > 0) {
7801
- sql += `;
7802
- ` + indexes.join(`
7803
- `);
7804
- }
7805
- return sql;
7806
- }
7807
- constructor(db, context) {
7808
- this.db = db;
7809
- this.context = context;
7810
- this.context.elements.forEach((element) => {
7811
- if ("databaseStoreSchema" in element && typeof element.databaseStoreSchema === "function") {
7812
- const databaseSchema = element.databaseStoreSchema();
7813
- databaseSchema.tables.forEach((dbTable) => {
7814
- const agnosticSchema = extractDatabaseAgnosticSchema(dbTable.schema, dbTable.name);
7815
- const columns = agnosticSchema.columns.map((columnInfo) => ({
7816
- name: columnInfo.name,
7817
- type: this.mapType(columnInfo.type, columnInfo.storeData),
7818
- constraints: this.buildConstraints(columnInfo.storeData),
7819
- isNullable: columnInfo.storeData?.isNullable || false,
7820
- defaultValue: columnInfo.defaultValue,
7821
- isPrimaryKey: columnInfo.storeData?.isPrimaryKey || false,
7822
- isAutoIncrement: columnInfo.storeData?.isAutoIncrement || false,
7823
- isUnique: columnInfo.storeData?.isUnique || false,
7824
- hasIndex: columnInfo.storeData?.hasIndex || false,
7825
- foreignKey: columnInfo.storeData?.foreignKey
7826
- }));
7827
- this.tableSchemas.set(dbTable.name, columns);
7828
- const legacyTable = {
7829
- name: dbTable.name,
7830
- primaryKey: columns.find((col) => col.isPrimaryKey)?.name || "_id",
7831
- columns: columns.map((col) => ({
7832
- name: col.name,
7833
- type: col.type,
7834
- isOptional: col.isNullable,
7835
- default: col.defaultValue
7836
- }))
7837
- };
7838
- this.tables.set(dbTable.name, legacyTable);
7839
- });
7840
- }
7841
- });
7842
- }
7843
- async initialize() {
7844
- await this.createVersionCounterTable();
7845
- await this.createTableVersionsTable();
7846
- const processedSchemas = new Set;
7847
- const processedTables = new Set;
7848
- for (const element of this.context.elements) {
7849
- if ("databaseStoreSchema" in element && typeof element.databaseStoreSchema === "function") {
7850
- const databaseSchema = element.databaseStoreSchema();
7851
- if (processedSchemas.has(databaseSchema)) {
7852
- continue;
7853
- }
7854
- processedSchemas.add(databaseSchema);
7855
- for (const dbTable of databaseSchema.tables) {
7856
- const tableKey = dbTable.version ? `${dbTable.name}_v${dbTable.version}` : dbTable.name;
7857
- if (!processedTables.has(tableKey)) {
7858
- const agnosticSchema = extractDatabaseAgnosticSchema(dbTable.schema, dbTable.name);
7859
- let allColumns = [...agnosticSchema.columns];
7860
- if (dbTable.options?.versioning) {
7861
- allColumns.push({
7862
- name: "__version",
7863
- type: "number",
7864
- storeData: { isNullable: false, hasIndex: true },
7865
- defaultValue: 1
7866
- });
7867
- }
7868
- if (dbTable.options?.softDelete) {
7869
- allColumns.push({
7870
- name: "deleted",
7871
- type: "boolean",
7872
- storeData: { isNullable: false, hasIndex: true },
7873
- defaultValue: false
7874
- });
7875
- }
7876
- const physicalTableName = this.getPhysicalTableName(dbTable.name, dbTable.version);
7877
- if (dbTable.version && await this.checkVersionedTableExists(dbTable.name, dbTable.version)) {
7878
- console.log(`Versioned table ${physicalTableName} already exists, skipping creation`);
7879
- } else {
7880
- await this.createTableIfNotExistsNew(physicalTableName, allColumns);
7881
- if (dbTable.version) {
7882
- await this.registerTableVersion(dbTable.name, dbTable.version, physicalTableName);
7883
- }
7884
- }
7885
- if (dbTable.version && databaseSchema.reinitTable) {
7886
- this.pendingReinitTables.push({
7887
- tableName: physicalTableName,
7888
- reinitFn: databaseSchema.reinitTable
7889
- });
7890
- }
7891
- const legacyTable = {
7892
- name: physicalTableName,
7893
- primaryKey: allColumns.find((col) => col.storeData?.isPrimaryKey)?.name || "_id",
7894
- columns: allColumns.map((col) => ({
7895
- name: col.name,
7896
- type: this.mapType(col.type, col.storeData),
7897
- isOptional: col.storeData?.isNullable || false,
7898
- default: col.defaultValue
7899
- }))
7900
- };
7901
- this.tables.set(dbTable.name, legacyTable);
7902
- processedTables.add(tableKey);
7903
- }
7904
- }
7905
- }
7906
- }
7907
- }
7908
- async createTableIfNotExistsNew(tableName, columns) {
7909
- const createTableSQL = this.generateCreateTableSQL(tableName, columns);
7910
- await this.db.exec(createTableSQL);
7911
- }
7912
- async createVersionCounterTable() {
7913
- const sql = `
7914
- CREATE TABLE IF NOT EXISTS __arc_version_counters (
7915
- table_name TEXT PRIMARY KEY,
7916
- last_version INTEGER NOT NULL DEFAULT 0
7917
- )
7918
- `;
7919
- await this.db.exec(sql);
7920
- }
7921
- async createTableVersionsTable() {
7922
- const sql = `
7923
- CREATE TABLE IF NOT EXISTS __arc_table_versions (
7924
- table_name TEXT NOT NULL,
7925
- version INTEGER NOT NULL,
7926
- physical_table_name TEXT NOT NULL,
7927
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
7928
- is_active INTEGER DEFAULT 0,
7929
- PRIMARY KEY (table_name, version)
7930
- )
7931
- `;
7932
- await this.db.exec(sql);
7933
- }
7934
- getPhysicalTableName(logicalName, version) {
7935
- return version ? `${logicalName}_v${version}` : logicalName;
7936
- }
7937
- async checkVersionedTableExists(logicalName, version) {
7938
- const result = await this.db.exec("SELECT COUNT(*) as count FROM __arc_table_versions WHERE table_name = ? AND version = ?", [logicalName, version]);
7939
- return result[0]?.count > 0;
7940
- }
7941
- async registerTableVersion(logicalName, version, physicalName) {
7942
- await this.db.exec("INSERT INTO __arc_table_versions (table_name, version, physical_table_name, is_active) VALUES (?, ?, ?, ?)", [logicalName, version, physicalName, 1]);
7943
- }
7944
- hasVersioning(tableName) {
7945
- const table = this.tables.get(tableName);
7946
- if (!table)
7947
- return false;
7948
- return table.columns.some((col) => col.name === "__version");
7949
- }
7950
- hasSoftDelete(tableName) {
7951
- const table = this.tables.get(tableName);
7952
- if (!table)
7953
- return false;
7954
- return table.columns.some((col) => col.name === "deleted");
7955
- }
7956
- async executeReinitTables(dataStorage) {
7957
- for (const { tableName, reinitFn } of this.pendingReinitTables) {
7958
- await reinitFn(tableName, dataStorage);
7959
- }
7960
- this.pendingReinitTables = [];
7961
- }
7962
- readWriteTransaction(stores) {
7963
- return new SQLiteReadWriteTransaction(this.db, this.tables, this);
7964
- }
7965
- readTransaction(stores) {
7966
- return new SQLiteReadTransaction(this.db, this.tables, this);
7967
- }
7968
- async destroy() {
7969
- for (const tableName of this.tables.keys()) {
7970
- const table = this.tables.get(tableName);
7971
- if (table) {
7972
- await this.db.exec(`DROP TABLE IF EXISTS "${table.name}"`);
7973
- }
7974
- }
7975
- await this.db.exec("DROP TABLE IF EXISTS __arc_version_counters");
7976
- await this.db.exec("DROP TABLE IF EXISTS __arc_table_versions");
7977
- this.tables.clear();
7978
- this.tableSchemas.clear();
7979
- this.pendingReinitTables = [];
7980
- }
7981
- }
7982
- var createSQLiteAdapterFactory = (db) => {
7983
- return async (context) => {
7984
- const adapter = new SQLiteAdapter(db, context);
7985
- await adapter.initialize();
7986
- return adapter;
7987
- };
7988
- };
7989
-
7990
- class BunSQLiteDatabase {
7991
- db;
7992
- constructor(filename = ":memory:") {
7993
- this.db = new Database(filename);
7994
- }
7995
- async exec(sql, params) {
7996
- try {
7997
- if (params && params.length > 0) {
7998
- const stmt = this.db.prepare(sql);
7999
- if (sql.trim().toUpperCase().startsWith("SELECT")) {
8000
- return stmt.all(...params);
8001
- } else {
8002
- stmt.run(...params);
8003
- return [];
8004
- }
8005
- } else {
8006
- const statements = sql.split(";").filter((s) => s.trim());
8007
- let result = [];
8008
- for (const statement of statements) {
8009
- if (!statement.trim())
8010
- continue;
8011
- if (statement.trim().toUpperCase().startsWith("SELECT")) {
8012
- result = this.db.prepare(statement).all();
8013
- } else {
8014
- this.db.exec(statement);
8015
- }
8016
- }
8017
- return result;
8018
- }
8019
- } catch (error) {
8020
- console.error("SQL Error:", error, `
8021
- SQL:`, sql, `
8022
- Params:`, params);
8023
- throw error;
8024
- }
8025
- }
8026
- async execBatch(queries) {
8027
- this.db.exec("BEGIN TRANSACTION");
8028
- try {
8029
- for (const query of queries) {
8030
- if (query.params && query.params.length > 0) {
8031
- this.db.prepare(query.sql).run(...query.params);
8032
- } else {
8033
- this.db.exec(query.sql);
8034
- }
8035
- }
8036
- this.db.exec("COMMIT");
8037
- } catch (error) {
8038
- this.db.exec("ROLLBACK");
8039
- throw error;
8040
- }
8041
- }
8042
- close() {
8043
- this.db.close();
8044
- }
8045
- }
8046
- var createBunSQLiteAdapterFactory = (filename = ":memory:") => {
8047
- return async (context) => {
8048
- const db = new BunSQLiteDatabase(filename);
8049
- return createSQLiteAdapterFactory(db)(context);
8050
- };
8051
- };
8052
-
8053
- // sqliteAdapter.ts
8054
- var sqliteAdapterFactory = (dbName) => {
8055
- return createBunSQLiteAdapterFactory(dbName);
8056
- };
8057
4430
  // index.ts
8058
4431
  function hostLiveModel(context, dbAdapterFactory) {
8059
4432
  const host = new ArcHost({
@@ -8064,7 +4437,6 @@ function hostLiveModel(context, dbAdapterFactory) {
8064
4437
  return host;
8065
4438
  }
8066
4439
  export {
8067
- sqliteAdapterFactory,
8068
4440
  hostLiveModel,
8069
4441
  filterEventsForToken,
8070
4442
  canTokenReceiveEvent,
@@ -8074,5 +4446,5 @@ export {
8074
4446
  ArcHost
8075
4447
  };
8076
4448
 
8077
- //# debugId=9946DC76B081270E64756E2164756E21
4449
+ //# debugId=788AEA1D4DCA4B2C64756E2164756E21
8078
4450
  //# sourceMappingURL=index.js.map