@stndrds/schema 0.1.0-alpha.56 → 0.1.0-alpha.57

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.
@@ -543,7 +543,7 @@ var TenantContextError = class _TenantContextError extends Error {
543
543
  }
544
544
  };
545
545
 
546
- // src/runtime/context/schema-context.ts
546
+ // src/runtime/context/feature-flags-context.ts
547
547
  var browserStub = {
548
548
  getStore: () => void 0,
549
549
  run: (_store, callback) => callback()
@@ -581,22 +581,106 @@ function getStorage() {
581
581
  storageInstance = browserStub;
582
582
  return storageInstance;
583
583
  }
584
- function getSchemaFromContext(objectId) {
584
+ var FeatureFlagsContextError = class _FeatureFlagsContextError extends Error {
585
+ constructor(message) {
586
+ super(
587
+ _nullishCoalesce(message, () => ( "No feature flags context found. This usually means:\n - HTTP request: Missing FeatureFlagsInterceptor\n - Background job: Wrap with runWithFeatureFlags()\n - Test: Wrap test body with runWithFeatureFlags()\n\nTip: FeatureFlagsInterceptor must run AFTER TenantContextInterceptor."))
588
+ );
589
+ this.name = "FeatureFlagsContextError";
590
+ if ("captureStackTrace" in Error) {
591
+ Error.captureStackTrace(
592
+ this,
593
+ _FeatureFlagsContextError
594
+ );
595
+ }
596
+ }
597
+ };
598
+ function getContext() {
585
599
  const ctx = getStorage().getStore();
586
- return _optionalChain([ctx, 'optionalAccess', _5 => _5.objectsById, 'access', _6 => _6.get, 'call', _7 => _7(objectId)]);
600
+ if (!ctx) {
601
+ throw new FeatureFlagsContextError();
602
+ }
603
+ return ctx;
587
604
  }
588
- function getSchemaByNameFromContext(objectName) {
605
+ function isFeatureEnabled(flagName) {
606
+ return getContext().flags.get(flagName) === true;
607
+ }
608
+ function getFeatureValue(flagName, defaultValue) {
609
+ const value = getContext().flags.get(flagName);
610
+ return value !== void 0 ? value : defaultValue;
611
+ }
612
+ function getFeatureFlags() {
613
+ return getContext().flags;
614
+ }
615
+ function tryGetFeatureValue(flagName) {
589
616
  const ctx = getStorage().getStore();
590
- return _optionalChain([ctx, 'optionalAccess', _8 => _8.objectsByName, 'access', _9 => _9.get, 'call', _10 => _10(objectName)]);
617
+ return _optionalChain([ctx, 'optionalAccess', _5 => _5.flags, 'access', _6 => _6.get, 'call', _7 => _7(flagName)]);
591
618
  }
592
- function hasSchemaContext() {
619
+ function hasFeatureFlagsContext() {
593
620
  return getStorage().getStore() !== void 0;
594
621
  }
622
+ function runWithFeatureFlags(flags, fn) {
623
+ const frozenContext = Object.freeze({ flags });
624
+ return getStorage().run(frozenContext, fn);
625
+ }
626
+ function withFeatureFlags(resolvedFlags, fn) {
627
+ return runWithFeatureFlags(resolvedFlags, fn);
628
+ }
629
+
630
+ // src/runtime/context/schema-context.ts
631
+ var browserStub2 = {
632
+ getStore: () => void 0,
633
+ run: (_store, callback) => callback()
634
+ };
635
+ var AsyncLocalStorageClass2 = null;
636
+ if (typeof process !== "undefined" && _optionalChain([process, 'access', _8 => _8.versions, 'optionalAccess', _9 => _9.node])) {
637
+ try {
638
+ if (typeof _chunk3RG5ZIWIjs.__require !== "undefined") {
639
+ const asyncHooks = _chunk3RG5ZIWIjs.__require.call(void 0, "async_hooks");
640
+ AsyncLocalStorageClass2 = asyncHooks.AsyncLocalStorage;
641
+ }
642
+ } catch (e5) {
643
+ try {
644
+ const dynamicRequire = new Function(
645
+ "m",
646
+ 'return typeof require!=="undefined"?require(m):null'
647
+ );
648
+ const asyncHooks = dynamicRequire("node:async_hooks");
649
+ if (asyncHooks) {
650
+ AsyncLocalStorageClass2 = asyncHooks.AsyncLocalStorage;
651
+ }
652
+ } catch (e6) {
653
+ }
654
+ }
655
+ }
656
+ var storageInstance2 = null;
657
+ function getStorage2() {
658
+ if (storageInstance2 !== null) {
659
+ return storageInstance2;
660
+ }
661
+ if (AsyncLocalStorageClass2) {
662
+ storageInstance2 = new AsyncLocalStorageClass2();
663
+ return storageInstance2;
664
+ }
665
+ storageInstance2 = browserStub2;
666
+ return storageInstance2;
667
+ }
668
+ function getSchemaFromContext(objectId) {
669
+ const ctx = getStorage2().getStore();
670
+ return _optionalChain([ctx, 'optionalAccess', _10 => _10.objectsById, 'access', _11 => _11.get, 'call', _12 => _12(objectId)]);
671
+ }
672
+ function getSchemaByNameFromContext(objectName) {
673
+ const ctx = getStorage2().getStore();
674
+ return _optionalChain([ctx, 'optionalAccess', _13 => _13.objectsByName, 'access', _14 => _14.get, 'call', _15 => _15(objectName)]);
675
+ }
676
+ function hasSchemaContext() {
677
+ return getStorage2().getStore() !== void 0;
678
+ }
595
679
  function getSchemaContext() {
596
- return getStorage().getStore();
680
+ return getStorage2().getStore();
597
681
  }
598
682
  function addSchemaToContext(schema) {
599
- const ctx = getStorage().getStore();
683
+ const ctx = getStorage2().getStore();
600
684
  if (!ctx) {
601
685
  return;
602
686
  }
@@ -618,12 +702,12 @@ function buildSchemaContext(schemas) {
618
702
  }
619
703
  function runWithSchemaContext(schemas, fn) {
620
704
  const context = buildSchemaContext(schemas);
621
- return getStorage().run(context, fn);
705
+ return getStorage2().run(context, fn);
622
706
  }
623
707
  function runWithMergedSchemaContext(schemas, fn) {
624
- const existing = getStorage().getStore();
625
- const objectsById = new Map(_optionalChain([existing, 'optionalAccess', _11 => _11.objectsById]));
626
- const objectsByName = new Map(_optionalChain([existing, 'optionalAccess', _12 => _12.objectsByName]));
708
+ const existing = getStorage2().getStore();
709
+ const objectsById = new Map(_optionalChain([existing, 'optionalAccess', _16 => _16.objectsById]));
710
+ const objectsByName = new Map(_optionalChain([existing, 'optionalAccess', _17 => _17.objectsByName]));
627
711
  for (const schema of schemas) {
628
712
  if (schema.id) {
629
713
  objectsById.set(schema.id, schema);
@@ -634,22 +718,22 @@ function runWithMergedSchemaContext(schemas, fn) {
634
718
  objectsById,
635
719
  objectsByName
636
720
  };
637
- return getStorage().run(context, fn);
721
+ return getStorage2().run(context, fn);
638
722
  }
639
723
 
640
724
  // src/runtime/context/tenant-context.ts
641
- var browserStub2 = {
725
+ var browserStub3 = {
642
726
  getStore: () => void 0,
643
727
  run: (_store, callback) => callback()
644
728
  };
645
- var AsyncLocalStorageClass2 = null;
646
- if (typeof process !== "undefined" && _optionalChain([process, 'access', _13 => _13.versions, 'optionalAccess', _14 => _14.node])) {
729
+ var AsyncLocalStorageClass3 = null;
730
+ if (typeof process !== "undefined" && _optionalChain([process, 'access', _18 => _18.versions, 'optionalAccess', _19 => _19.node])) {
647
731
  try {
648
732
  if (typeof _chunk3RG5ZIWIjs.__require !== "undefined") {
649
733
  const asyncHooks = _chunk3RG5ZIWIjs.__require.call(void 0, "async_hooks");
650
- AsyncLocalStorageClass2 = asyncHooks.AsyncLocalStorage;
734
+ AsyncLocalStorageClass3 = asyncHooks.AsyncLocalStorage;
651
735
  }
652
- } catch (e5) {
736
+ } catch (e7) {
653
737
  try {
654
738
  const dynamicRequire = new Function(
655
739
  "m",
@@ -657,43 +741,43 @@ if (typeof process !== "undefined" && _optionalChain([process, 'access', _13 =>
657
741
  );
658
742
  const asyncHooks = dynamicRequire("node:async_hooks");
659
743
  if (asyncHooks) {
660
- AsyncLocalStorageClass2 = asyncHooks.AsyncLocalStorage;
744
+ AsyncLocalStorageClass3 = asyncHooks.AsyncLocalStorage;
661
745
  }
662
- } catch (e6) {
746
+ } catch (e8) {
663
747
  }
664
748
  }
665
749
  }
666
- var storageInstance2 = null;
667
- function getStorage2() {
668
- if (storageInstance2 !== null) {
669
- return storageInstance2;
750
+ var storageInstance3 = null;
751
+ function getStorage3() {
752
+ if (storageInstance3 !== null) {
753
+ return storageInstance3;
670
754
  }
671
- if (AsyncLocalStorageClass2) {
672
- storageInstance2 = new AsyncLocalStorageClass2();
673
- return storageInstance2;
755
+ if (AsyncLocalStorageClass3) {
756
+ storageInstance3 = new AsyncLocalStorageClass3();
757
+ return storageInstance3;
674
758
  }
675
- storageInstance2 = browserStub2;
676
- return storageInstance2;
759
+ storageInstance3 = browserStub3;
760
+ return storageInstance3;
677
761
  }
678
- function getContext() {
679
- const ctx = getStorage2().getStore();
762
+ function getContext2() {
763
+ const ctx = getStorage3().getStore();
680
764
  if (!ctx) {
681
765
  throw new TenantContextError();
682
766
  }
683
767
  return ctx;
684
768
  }
685
769
  function getTenantId() {
686
- return getContext().tenantId;
770
+ return getContext2().tenantId;
687
771
  }
688
772
  function getUserId() {
689
- return getContext().userId;
773
+ return getContext2().userId;
690
774
  }
691
775
  function hasContext() {
692
- return getStorage2().getStore() !== void 0;
776
+ return getStorage3().getStore() !== void 0;
693
777
  }
694
778
  function runWithContext(context, fn) {
695
779
  const frozenContext = Object.freeze({ ...context });
696
- return getStorage2().run(frozenContext, fn);
780
+ return getStorage3().run(frozenContext, fn);
697
781
  }
698
782
  function withTenantContext(tenantId, fn, userId) {
699
783
  return runWithContext({ tenantId, userId }, fn);
@@ -1101,9 +1185,9 @@ var QueryBuilder = class _QueryBuilder {
1101
1185
  objectId,
1102
1186
  data,
1103
1187
  {
1104
- allowDraft: _optionalChain([options, 'optionalAccess', _15 => _15.allowDraft]),
1105
- validate: _optionalChain([options, 'optionalAccess', _16 => _16.validate]),
1106
- metadata: _optionalChain([options, 'optionalAccess', _17 => _17.metadata])
1188
+ allowDraft: _optionalChain([options, 'optionalAccess', _20 => _20.allowDraft]),
1189
+ validate: _optionalChain([options, 'optionalAccess', _21 => _21.validate]),
1190
+ metadata: _optionalChain([options, 'optionalAccess', _22 => _22.metadata])
1107
1191
  }
1108
1192
  );
1109
1193
  if (this.state.raw) {
@@ -1138,7 +1222,7 @@ var QueryBuilder = class _QueryBuilder {
1138
1222
  data,
1139
1223
  {
1140
1224
  partial: true,
1141
- metadata: _optionalChain([options, 'optionalAccess', _18 => _18.metadata])
1225
+ metadata: _optionalChain([options, 'optionalAccess', _23 => _23.metadata])
1142
1226
  }
1143
1227
  );
1144
1228
  if (this.state.raw) {
@@ -1186,7 +1270,7 @@ var QueryBuilder = class _QueryBuilder {
1186
1270
  const existing = await this.findById(id);
1187
1271
  if (existing) {
1188
1272
  return this.eq("id", id).update(writeData, {
1189
- metadata: _optionalChain([options, 'optionalAccess', _19 => _19.metadata])
1273
+ metadata: _optionalChain([options, 'optionalAccess', _24 => _24.metadata])
1190
1274
  });
1191
1275
  }
1192
1276
  }
@@ -1195,10 +1279,10 @@ var QueryBuilder = class _QueryBuilder {
1195
1279
  };
1196
1280
  function createQueryBuilder(recordService, adapter, objectName, options) {
1197
1281
  const initialState = {};
1198
- if (_optionalChain([options, 'optionalAccess', _20 => _20.tenantId])) {
1282
+ if (_optionalChain([options, 'optionalAccess', _25 => _25.tenantId])) {
1199
1283
  initialState.tenantId = asTenantId(options.tenantId);
1200
1284
  }
1201
- if (_optionalChain([options, 'optionalAccess', _21 => _21.userId])) {
1285
+ if (_optionalChain([options, 'optionalAccess', _26 => _26.userId])) {
1202
1286
  initialState.userId = asUserId(options.userId);
1203
1287
  }
1204
1288
  return new QueryBuilder(recordService, adapter, objectName, initialState);
@@ -1648,7 +1732,7 @@ var WorkflowDefinitionSchema = _zod.z.object({
1648
1732
  ).refine(
1649
1733
  (def) => {
1650
1734
  const startNode = def.nodes[def.startNodeId];
1651
- return _optionalChain([startNode, 'optionalAccess', _22 => _22.type]) === "start";
1735
+ return _optionalChain([startNode, 'optionalAccess', _27 => _27.type]) === "start";
1652
1736
  },
1653
1737
  {
1654
1738
  message: "startNodeId must reference a node of type 'start'"
@@ -1880,8 +1964,8 @@ function wait(reason, options) {
1880
1964
  return {
1881
1965
  status: "wait",
1882
1966
  reason,
1883
- requiredParticipationId: _optionalChain([options, 'optionalAccess', _23 => _23.requiredParticipationId]),
1884
- expiresAt: _optionalChain([options, 'optionalAccess', _24 => _24.expiresAt])
1967
+ requiredParticipationId: _optionalChain([options, 'optionalAccess', _28 => _28.requiredParticipationId]),
1968
+ expiresAt: _optionalChain([options, 'optionalAccess', _29 => _29.expiresAt])
1885
1969
  };
1886
1970
  }
1887
1971
  function complete(finalStatus) {
@@ -2158,9 +2242,9 @@ var FormExecutor = class {
2158
2242
  const object2 = objects.find((o) => o.name === slot.objectName);
2159
2243
  if (!object2) continue;
2160
2244
  const attribute = object2.attributes.find((a) => a.name === fieldRef.attribute);
2161
- if (!_optionalChain([attribute, 'optionalAccess', _25 => _25.required])) continue;
2245
+ if (!_optionalChain([attribute, 'optionalAccess', _30 => _30.required])) continue;
2162
2246
  const slotInput = input[fieldRef.slotId];
2163
- const value = _optionalChain([slotInput, 'optionalAccess', _26 => _26[fieldRef.attribute]]);
2247
+ const value = _optionalChain([slotInput, 'optionalAccess', _31 => _31[fieldRef.attribute]]);
2164
2248
  if (value === void 0 || value === null || value === "") {
2165
2249
  errors.push(
2166
2250
  `Field "${_nullishCoalesce(attribute.label, () => ( fieldRef.attribute))}" is required for ${slot.label}`
@@ -2335,7 +2419,7 @@ function evaluateFormula(expression, values) {
2335
2419
  try {
2336
2420
  const parsed = formulaParser.parse(expression);
2337
2421
  return parsed.evaluate(values);
2338
- } catch (e7) {
2422
+ } catch (e9) {
2339
2423
  return null;
2340
2424
  }
2341
2425
  }
@@ -2395,7 +2479,7 @@ function extractFormulaVariables(expression) {
2395
2479
  try {
2396
2480
  const parsed = formulaParser.parse(expression);
2397
2481
  return parsed.variables();
2398
- } catch (e8) {
2482
+ } catch (e10) {
2399
2483
  return [];
2400
2484
  }
2401
2485
  }
@@ -2482,7 +2566,7 @@ async function parsePath(path, startSchema, getSchema, maxDepth = 5) {
2482
2566
  }
2483
2567
  if (attr.type === "relation") {
2484
2568
  const relationAttr = attr;
2485
- const targetObject = _optionalChain([relationAttr, 'access', _27 => _27.targets, 'access', _28 => _28[0], 'optionalAccess', _29 => _29.object]);
2569
+ const targetObject = _optionalChain([relationAttr, 'access', _32 => _32.targets, 'access', _33 => _33[0], 'optionalAccess', _34 => _34.object]);
2486
2570
  if (!targetObject) {
2487
2571
  throw new InvalidPathError(path, segmentName, "Relation has no target object");
2488
2572
  }
@@ -2523,7 +2607,7 @@ async function validatePath(path, startSchema, getSchema, maxDepth = 5) {
2523
2607
  try {
2524
2608
  await parsePath(path, startSchema, getSchema, maxDepth);
2525
2609
  return true;
2526
- } catch (e9) {
2610
+ } catch (e11) {
2527
2611
  return false;
2528
2612
  }
2529
2613
  }
@@ -2545,7 +2629,7 @@ function getRelationPath(path) {
2545
2629
 
2546
2630
  // src/runtime/formula/path-traversal.ts
2547
2631
  async function traversePath(record, path, startSchemaName, adapter, getSchema, options) {
2548
- const maxDepth = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _30 => _30.maxDepth]), () => ( 5));
2632
+ const maxDepth = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _35 => _35.maxDepth]), () => ( 5));
2549
2633
  const startSchema = await getSchema(startSchemaName);
2550
2634
  if (!startSchema) {
2551
2635
  return { values: [], recordCounts: [0] };
@@ -2641,12 +2725,12 @@ function createMockAIConversationsRepository(stores) {
2641
2725
  const userId = requireUserId();
2642
2726
  let results = Array.from(stores.aiConversations.values()).filter((c) => {
2643
2727
  if (c.tenantId !== tenantId || c.userId !== userId) return false;
2644
- if (!_optionalChain([options, 'optionalAccess', _31 => _31.includeDeleted]) && c.deletedAt) return false;
2728
+ if (!_optionalChain([options, 'optionalAccess', _36 => _36.includeDeleted]) && c.deletedAt) return false;
2645
2729
  return true;
2646
2730
  });
2647
2731
  results.sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());
2648
2732
  const total = results.length;
2649
- if (_optionalChain([options, 'optionalAccess', _32 => _32.limit])) {
2733
+ if (_optionalChain([options, 'optionalAccess', _37 => _37.limit])) {
2650
2734
  results = results.slice(_nullishCoalesce(options.offset, () => ( 0)), (_nullishCoalesce(options.offset, () => ( 0))) + options.limit);
2651
2735
  }
2652
2736
  return Promise.resolve({ conversations: results, total });
@@ -2721,7 +2805,7 @@ function createMockAIConversationsRepository(stores) {
2721
2805
  listMessages(conversationId, options) {
2722
2806
  let results = Array.from(stores.aiMessages.values()).filter((m) => m.conversationId === conversationId).sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
2723
2807
  const total = results.length;
2724
- if (_optionalChain([options, 'optionalAccess', _33 => _33.limit])) {
2808
+ if (_optionalChain([options, 'optionalAccess', _38 => _38.limit])) {
2725
2809
  results = results.slice(_nullishCoalesce(options.offset, () => ( 0)), (_nullishCoalesce(options.offset, () => ( 0))) + options.limit);
2726
2810
  }
2727
2811
  return Promise.resolve({ messages: results, total });
@@ -2750,12 +2834,12 @@ function createMockAIUserMemoryRepository(stores) {
2750
2834
  const now = /* @__PURE__ */ new Date();
2751
2835
  const existing = stores.aiUserMemory.get(key);
2752
2836
  const memory = {
2753
- id: _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _34 => _34.id]), () => ( generateId())),
2837
+ id: _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _39 => _39.id]), () => ( generateId())),
2754
2838
  tenantId,
2755
2839
  userId,
2756
- preferences: _nullishCoalesce(_nullishCoalesce(data.preferences, () => ( _optionalChain([existing, 'optionalAccess', _35 => _35.preferences]))), () => ( {})),
2757
- facts: _nullishCoalesce(_nullishCoalesce(data.facts, () => ( _optionalChain([existing, 'optionalAccess', _36 => _36.facts]))), () => ( [])),
2758
- createdAt: _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _37 => _37.createdAt]), () => ( now)),
2840
+ preferences: _nullishCoalesce(_nullishCoalesce(data.preferences, () => ( _optionalChain([existing, 'optionalAccess', _40 => _40.preferences]))), () => ( {})),
2841
+ facts: _nullishCoalesce(_nullishCoalesce(data.facts, () => ( _optionalChain([existing, 'optionalAccess', _41 => _41.facts]))), () => ( [])),
2842
+ createdAt: _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _42 => _42.createdAt]), () => ( now)),
2759
2843
  updatedAt: now
2760
2844
  };
2761
2845
  stores.aiUserMemory.set(key, memory);
@@ -2768,12 +2852,12 @@ function createMockAIUserMemoryRepository(stores) {
2768
2852
  const now = /* @__PURE__ */ new Date();
2769
2853
  const existing = stores.aiUserMemory.get(key);
2770
2854
  const memory = {
2771
- id: _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _38 => _38.id]), () => ( generateId())),
2855
+ id: _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _43 => _43.id]), () => ( generateId())),
2772
2856
  tenantId,
2773
2857
  userId,
2774
- preferences: _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _39 => _39.preferences]), () => ( {})),
2775
- facts: [..._nullishCoalesce(_optionalChain([existing, 'optionalAccess', _40 => _40.facts]), () => ( [])), fact],
2776
- createdAt: _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _41 => _41.createdAt]), () => ( now)),
2858
+ preferences: _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _44 => _44.preferences]), () => ( {})),
2859
+ facts: [..._nullishCoalesce(_optionalChain([existing, 'optionalAccess', _45 => _45.facts]), () => ( [])), fact],
2860
+ createdAt: _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _46 => _46.createdAt]), () => ( now)),
2777
2861
  updatedAt: now
2778
2862
  };
2779
2863
  stores.aiUserMemory.set(key, memory);
@@ -2786,12 +2870,12 @@ function createMockAIUserMemoryRepository(stores) {
2786
2870
  const now = /* @__PURE__ */ new Date();
2787
2871
  const existing = stores.aiUserMemory.get(key);
2788
2872
  const memory = {
2789
- id: _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _42 => _42.id]), () => ( generateId())),
2873
+ id: _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _47 => _47.id]), () => ( generateId())),
2790
2874
  tenantId,
2791
2875
  userId,
2792
- preferences: _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _43 => _43.preferences]), () => ( {})),
2793
- facts: (_nullishCoalesce(_optionalChain([existing, 'optionalAccess', _44 => _44.facts]), () => ( []))).filter((f) => f !== fact),
2794
- createdAt: _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _45 => _45.createdAt]), () => ( now)),
2876
+ preferences: _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _48 => _48.preferences]), () => ( {})),
2877
+ facts: (_nullishCoalesce(_optionalChain([existing, 'optionalAccess', _49 => _49.facts]), () => ( []))).filter((f) => f !== fact),
2878
+ createdAt: _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _50 => _50.createdAt]), () => ( now)),
2795
2879
  updatedAt: now
2796
2880
  };
2797
2881
  stores.aiUserMemory.set(key, memory);
@@ -2804,12 +2888,12 @@ function createMockAIUserMemoryRepository(stores) {
2804
2888
  const now = /* @__PURE__ */ new Date();
2805
2889
  const existing = stores.aiUserMemory.get(memoryKey);
2806
2890
  const memory = {
2807
- id: _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _46 => _46.id]), () => ( generateId())),
2891
+ id: _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _51 => _51.id]), () => ( generateId())),
2808
2892
  tenantId,
2809
2893
  userId,
2810
- preferences: { ..._nullishCoalesce(_optionalChain([existing, 'optionalAccess', _47 => _47.preferences]), () => ( {})), [prefKey]: value },
2811
- facts: _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _48 => _48.facts]), () => ( [])),
2812
- createdAt: _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _49 => _49.createdAt]), () => ( now)),
2894
+ preferences: { ..._nullishCoalesce(_optionalChain([existing, 'optionalAccess', _52 => _52.preferences]), () => ( {})), [prefKey]: value },
2895
+ facts: _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _53 => _53.facts]), () => ( [])),
2896
+ createdAt: _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _54 => _54.createdAt]), () => ( now)),
2813
2897
  updatedAt: now
2814
2898
  };
2815
2899
  stores.aiUserMemory.set(memoryKey, memory);
@@ -2834,24 +2918,24 @@ function createMockAIUsageMetricsRepository(stores) {
2834
2918
  const now = /* @__PURE__ */ new Date();
2835
2919
  const key = getDateKey(now);
2836
2920
  const existing = stores.aiUsageMetrics.get(key);
2837
- const providerBreakdown = _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _50 => _50.providerBreakdown]), () => ( {}));
2921
+ const providerBreakdown = _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _55 => _55.providerBreakdown]), () => ( {}));
2838
2922
  if (!providerBreakdown[data.provider]) {
2839
2923
  providerBreakdown[data.provider] = { requests: 0, tokens: 0, cost: 0 };
2840
2924
  }
2841
2925
  providerBreakdown[data.provider].requests++;
2842
2926
  providerBreakdown[data.provider].tokens += data.tokens;
2843
2927
  providerBreakdown[data.provider].cost += data.cost;
2844
- const toolUsage = _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _51 => _51.toolUsage]), () => ( {}));
2928
+ const toolUsage = _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _56 => _56.toolUsage]), () => ( {}));
2845
2929
  if (data.toolName) {
2846
2930
  toolUsage[data.toolName] = (_nullishCoalesce(toolUsage[data.toolName], () => ( 0))) + 1;
2847
2931
  }
2848
2932
  const metrics = {
2849
- id: _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _52 => _52.id]), () => ( generateId())),
2933
+ id: _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _57 => _57.id]), () => ( generateId())),
2850
2934
  tenantId,
2851
2935
  date: new Date(_nullishCoalesce(now.toISOString().split("T")[0], () => ( now.toISOString()))),
2852
- requestCount: (_nullishCoalesce(_optionalChain([existing, 'optionalAccess', _53 => _53.requestCount]), () => ( 0))) + 1,
2853
- totalTokens: (_nullishCoalesce(_optionalChain([existing, 'optionalAccess', _54 => _54.totalTokens]), () => ( 0))) + data.tokens,
2854
- totalCost: (_nullishCoalesce(_optionalChain([existing, 'optionalAccess', _55 => _55.totalCost]), () => ( 0))) + data.cost,
2936
+ requestCount: (_nullishCoalesce(_optionalChain([existing, 'optionalAccess', _58 => _58.requestCount]), () => ( 0))) + 1,
2937
+ totalTokens: (_nullishCoalesce(_optionalChain([existing, 'optionalAccess', _59 => _59.totalTokens]), () => ( 0))) + data.tokens,
2938
+ totalCost: (_nullishCoalesce(_optionalChain([existing, 'optionalAccess', _60 => _60.totalCost]), () => ( 0))) + data.cost,
2855
2939
  providerBreakdown,
2856
2940
  toolUsage
2857
2941
  };
@@ -2904,7 +2988,7 @@ function createMockFilesRepository(stores) {
2904
2988
  return {
2905
2989
  findById(id) {
2906
2990
  const file2 = stores.files.get(id);
2907
- if (_optionalChain([file2, 'optionalAccess', _56 => _56.deletedAt])) return Promise.resolve(null);
2991
+ if (_optionalChain([file2, 'optionalAccess', _61 => _61.deletedAt])) return Promise.resolve(null);
2908
2992
  return Promise.resolve(_nullishCoalesce(file2, () => ( null)));
2909
2993
  },
2910
2994
  findByIds(ids) {
@@ -2965,10 +3049,10 @@ function createMockFilesRepository(stores) {
2965
3049
  let results = Array.from(stores.files.values()).filter(
2966
3050
  (f) => f.tenantId === tenantId && !f.deletedAt
2967
3051
  );
2968
- if (_optionalChain([options, 'optionalAccess', _57 => _57.mimeType])) {
3052
+ if (_optionalChain([options, 'optionalAccess', _62 => _62.mimeType])) {
2969
3053
  results = results.filter((f) => f.mimeType === options.mimeType);
2970
3054
  }
2971
- if (_optionalChain([options, 'optionalAccess', _58 => _58.limit])) {
3055
+ if (_optionalChain([options, 'optionalAccess', _63 => _63.limit])) {
2972
3056
  results = results.slice(_nullishCoalesce(options.offset, () => ( 0)), (_nullishCoalesce(options.offset, () => ( 0))) + options.limit);
2973
3057
  }
2974
3058
  return Promise.resolve(results);
@@ -3302,7 +3386,7 @@ var SyncError = class extends SchemaError {
3302
3386
  constructor(objectName, message, cause) {
3303
3387
  super(`Failed to sync object "${objectName}": ${message}`, SchemaErrorCode.SYNC_FAILED, {
3304
3388
  objectName,
3305
- cause: _optionalChain([cause, 'optionalAccess', _59 => _59.message])
3389
+ cause: _optionalChain([cause, 'optionalAccess', _64 => _64.message])
3306
3390
  });
3307
3391
  this.name = "SyncError";
3308
3392
  this.objectName = objectName;
@@ -3449,7 +3533,7 @@ function formatPhone(value) {
3449
3533
  if (!("phoneNumber" in phone2)) return String(value);
3450
3534
  if (phone2.countryCode) {
3451
3535
  const country = _constants.getCountryByIso3.call(void 0, phone2.countryCode);
3452
- const dial = _nullishCoalesce(_optionalChain([country, 'optionalAccess', _60 => _60.phoneCode]), () => ( ""));
3536
+ const dial = _nullishCoalesce(_optionalChain([country, 'optionalAccess', _65 => _65.phoneCode]), () => ( ""));
3453
3537
  return `${dial} ${phone2.phoneNumber}`.trim();
3454
3538
  }
3455
3539
  return phone2.phoneNumber;
@@ -3495,13 +3579,13 @@ function formatLocation(value, attribute) {
3495
3579
  }
3496
3580
  function formatSelect(value, attribute) {
3497
3581
  if (typeof value !== "string") return String(value);
3498
- const option = _optionalChain([attribute, 'access', _61 => _61.options, 'optionalAccess', _62 => _62.find, 'call', _63 => _63((o) => o.value === value)]);
3499
- return _nullishCoalesce(_optionalChain([option, 'optionalAccess', _64 => _64.label]), () => ( String(value)));
3582
+ const option = _optionalChain([attribute, 'access', _66 => _66.options, 'optionalAccess', _67 => _67.find, 'call', _68 => _68((o) => o.value === value)]);
3583
+ return _nullishCoalesce(_optionalChain([option, 'optionalAccess', _69 => _69.label]), () => ( String(value)));
3500
3584
  }
3501
3585
  function formatMultiselect(value, attribute) {
3502
3586
  if (!Array.isArray(value)) return String(value);
3503
3587
  if (attribute.options) {
3504
- const labels = value.map((v) => _optionalChain([attribute, 'access', _65 => _65.options, 'access', _66 => _66.find, 'call', _67 => _67((o) => o.value === v), 'optionalAccess', _68 => _68.label])).filter(Boolean);
3588
+ const labels = value.map((v) => _optionalChain([attribute, 'access', _70 => _70.options, 'access', _71 => _71.find, 'call', _72 => _72((o) => o.value === v), 'optionalAccess', _73 => _73.label])).filter(Boolean);
3505
3589
  return labels.join(", ");
3506
3590
  }
3507
3591
  return value.join(", ");
@@ -3798,7 +3882,7 @@ function createMockObjectRecordsRepository(stores) {
3798
3882
  (r) => r.tenantId === tenantId && r.objectId === objectId
3799
3883
  );
3800
3884
  const total = results.length;
3801
- if (_optionalChain([options, 'optionalAccess', _69 => _69.limit])) {
3885
+ if (_optionalChain([options, 'optionalAccess', _74 => _74.limit])) {
3802
3886
  results = results.slice(_nullishCoalesce(options.offset, () => ( 0)), (_nullishCoalesce(options.offset, () => ( 0))) + options.limit);
3803
3887
  }
3804
3888
  const records = results.map(({ tenantId: _t, ...r }) => r);
@@ -3814,7 +3898,7 @@ function createMockObjectRecordsRepository(stores) {
3814
3898
  );
3815
3899
  });
3816
3900
  const total = results.length;
3817
- if (_optionalChain([options, 'optionalAccess', _70 => _70.limit])) {
3901
+ if (_optionalChain([options, 'optionalAccess', _75 => _75.limit])) {
3818
3902
  results = results.slice(_nullishCoalesce(options.offset, () => ( 0)), (_nullishCoalesce(options.offset, () => ( 0))) + options.limit);
3819
3903
  }
3820
3904
  const records = results.map(({ tenantId: _t, ...r }) => r);
@@ -3830,7 +3914,7 @@ function createMockObjectRecordsRepository(stores) {
3830
3914
  }
3831
3915
  }
3832
3916
  const allowedObjectIds = /* @__PURE__ */ new Set();
3833
- if (_optionalChain([options, 'optionalAccess', _71 => _71.objectNames]) && options.objectNames.length > 0) {
3917
+ if (_optionalChain([options, 'optionalAccess', _76 => _76.objectNames]) && options.objectNames.length > 0) {
3834
3918
  for (const obj of objectsMap.values()) {
3835
3919
  if (options.objectNames.includes(obj.name)) {
3836
3920
  allowedObjectIds.add(obj.id);
@@ -3849,7 +3933,7 @@ function createMockObjectRecordsRepository(stores) {
3849
3933
  );
3850
3934
  });
3851
3935
  const total = matchingRecords.length;
3852
- if (_optionalChain([options, 'optionalAccess', _72 => _72.limit])) {
3936
+ if (_optionalChain([options, 'optionalAccess', _77 => _77.limit])) {
3853
3937
  matchingRecords = matchingRecords.slice(
3854
3938
  _nullishCoalesce(options.offset, () => ( 0)),
3855
3939
  (_nullishCoalesce(options.offset, () => ( 0))) + options.limit
@@ -3860,11 +3944,11 @@ function createMockObjectRecordsRepository(stores) {
3860
3944
  if (!attributesByObjectId.has(attr.objectId)) {
3861
3945
  attributesByObjectId.set(attr.objectId, []);
3862
3946
  }
3863
- _optionalChain([attributesByObjectId, 'access', _73 => _73.get, 'call', _74 => _74(attr.objectId), 'optionalAccess', _75 => _75.push, 'call', _76 => _76(attr)]);
3947
+ _optionalChain([attributesByObjectId, 'access', _78 => _78.get, 'call', _79 => _79(attr.objectId), 'optionalAccess', _80 => _80.push, 'call', _81 => _81(attr)]);
3864
3948
  }
3865
3949
  const results = matchingRecords.map((r) => {
3866
3950
  const obj = objectsMap.get(r.objectId);
3867
- const labelExpression = _nullishCoalesce(_optionalChain([obj, 'optionalAccess', _77 => _77.labelExpression]), () => ( "{{ name }}"));
3951
+ const labelExpression = _nullishCoalesce(_optionalChain([obj, 'optionalAccess', _82 => _82.labelExpression]), () => ( "{{ name }}"));
3868
3952
  const dbAttrs = _nullishCoalesce(attributesByObjectId.get(r.objectId), () => ( []));
3869
3953
  const attrs = dbAttrs.map((a) => ({
3870
3954
  ...a.config,
@@ -3877,8 +3961,8 @@ function createMockObjectRecordsRepository(stores) {
3877
3961
  const enrichedValues = enrichValuesForDisplay(r.values, attrs);
3878
3962
  return {
3879
3963
  objectId: r.objectId,
3880
- objectName: _nullishCoalesce(_optionalChain([obj, 'optionalAccess', _78 => _78.name]), () => ( "unknown")),
3881
- objectLabel: _nullishCoalesce(_optionalChain([obj, 'optionalAccess', _79 => _79.label]), () => ( "Unknown")),
3964
+ objectName: _nullishCoalesce(_optionalChain([obj, 'optionalAccess', _83 => _83.name]), () => ( "unknown")),
3965
+ objectLabel: _nullishCoalesce(_optionalChain([obj, 'optionalAccess', _84 => _84.label]), () => ( "Unknown")),
3882
3966
  label: renderLabelExpression(labelExpression, enrichedValues),
3883
3967
  recordId: r.id,
3884
3968
  values: r.values,
@@ -4000,6 +4084,7 @@ function createEmptyStores() {
4000
4084
  files: /* @__PURE__ */ new Map(),
4001
4085
  objectRecords: /* @__PURE__ */ new Map(),
4002
4086
  views: /* @__PURE__ */ new Map(),
4087
+ viewOverlays: /* @__PURE__ */ new Map(),
4003
4088
  roles: /* @__PURE__ */ new Map(),
4004
4089
  permissions: /* @__PURE__ */ new Map(),
4005
4090
  userRoles: /* @__PURE__ */ new Map(),
@@ -4086,7 +4171,7 @@ function createMockUserProfilesRepository(stores) {
4086
4171
  list(options) {
4087
4172
  const tenantId = getTenantId();
4088
4173
  let results = Array.from(stores.userProfiles.values()).filter((p) => p.tenantId === tenantId);
4089
- if (_optionalChain([options, 'optionalAccess', _80 => _80.limit])) {
4174
+ if (_optionalChain([options, 'optionalAccess', _85 => _85.limit])) {
4090
4175
  results = results.slice(_nullishCoalesce(options.offset, () => ( 0)), (_nullishCoalesce(options.offset, () => ( 0))) + options.limit);
4091
4176
  }
4092
4177
  return Promise.resolve(results);
@@ -4174,7 +4259,7 @@ function createMockPermissionsRepository(stores) {
4174
4259
  },
4175
4260
  deleteRole(roleId) {
4176
4261
  const role = stores.roles.get(roleId);
4177
- if (_optionalChain([role, 'optionalAccess', _81 => _81.system])) {
4262
+ if (_optionalChain([role, 'optionalAccess', _86 => _86.system])) {
4178
4263
  return Promise.reject(new Error(`Cannot delete system role ${roleId}`));
4179
4264
  }
4180
4265
  stores.roles.delete(roleId);
@@ -4297,32 +4382,38 @@ function createMockViewsRepository(stores) {
4297
4382
  ), () => ( null))
4298
4383
  );
4299
4384
  },
4300
- findByObjectName(objectName) {
4385
+ findByNameAndType(objectName, viewName, type) {
4386
+ const tenantId = getTenantId();
4387
+ return Promise.resolve(
4388
+ _nullishCoalesce(Array.from(stores.views.values()).find(
4389
+ (v) => v.tenantId === tenantId && v.objectName === objectName && v.name === viewName && v.type === type
4390
+ ), () => ( null))
4391
+ );
4392
+ },
4393
+ findByObjectName(objectName, type) {
4301
4394
  const tenantId = getTenantId();
4302
4395
  return Promise.resolve(
4303
4396
  Array.from(stores.views.values()).filter(
4304
- (v) => v.tenantId === tenantId && v.objectName === objectName
4397
+ (v) => v.tenantId === tenantId && v.objectName === objectName && (type === void 0 || v.type === type)
4305
4398
  )
4306
4399
  );
4307
4400
  },
4308
- findAllForTenant() {
4401
+ findAllForTenant(type) {
4309
4402
  const tenantId = getTenantId();
4310
4403
  return Promise.resolve(
4311
- Array.from(stores.views.values()).filter((v) => v.tenantId === tenantId)
4404
+ Array.from(stores.views.values()).filter(
4405
+ (v) => v.tenantId === tenantId && (type === void 0 || v.type === type)
4406
+ )
4312
4407
  );
4313
4408
  },
4314
- findSystemByName(objectName, viewName) {
4409
+ findDefault(objectName, type) {
4410
+ const tenantId = getTenantId();
4315
4411
  return Promise.resolve(
4316
4412
  _nullishCoalesce(Array.from(stores.views.values()).find(
4317
- (v) => v.objectName === objectName && v.name === viewName && v.system
4413
+ (v) => v.tenantId === tenantId && v.objectName === objectName && v.type === type && v.default === true
4318
4414
  ), () => ( null))
4319
4415
  );
4320
4416
  },
4321
- findSystemByObjectName(objectName) {
4322
- return Promise.resolve(
4323
- Array.from(stores.views.values()).filter((v) => v.objectName === objectName && v.system)
4324
- );
4325
- },
4326
4417
  create(data) {
4327
4418
  const tenantId = getTenantId();
4328
4419
  const id = generateId();
@@ -4331,13 +4422,13 @@ function createMockViewsRepository(stores) {
4331
4422
  id,
4332
4423
  tenantId,
4333
4424
  objectName: data.objectName,
4425
+ type: data.type,
4334
4426
  name: data.name,
4335
4427
  label: data.label,
4336
4428
  description: data.description,
4337
4429
  icon: data.icon,
4338
- tabs: data.tabs,
4430
+ config: data.config,
4339
4431
  default: _nullishCoalesce(data.default, () => ( false)),
4340
- system: _nullishCoalesce(data.system, () => ( false)),
4341
4432
  metadata: data.metadata,
4342
4433
  createdAt: now,
4343
4434
  updatedAt: now
@@ -4362,10 +4453,11 @@ function createMockViewsRepository(stores) {
4362
4453
  stores.views.delete(id);
4363
4454
  return Promise.resolve();
4364
4455
  },
4365
- deleteNotIn(objectName, keepViewNames) {
4456
+ deleteNotIn(objectName, type, keepViewNames) {
4457
+ const tenantId = getTenantId();
4366
4458
  let deleted = 0;
4367
4459
  for (const [id, view2] of stores.views.entries()) {
4368
- if (view2.objectName === objectName && view2.system && !keepViewNames.includes(view2.name)) {
4460
+ if (view2.tenantId === tenantId && view2.objectName === objectName && view2.type === type && !keepViewNames.includes(view2.name)) {
4369
4461
  stores.views.delete(id);
4370
4462
  deleted++;
4371
4463
  }
@@ -4373,18 +4465,151 @@ function createMockViewsRepository(stores) {
4373
4465
  return Promise.resolve(deleted);
4374
4466
  },
4375
4467
  async upsert(data) {
4376
- const existing = data.system ? await this.findSystemByName(data.objectName, data.name) : await this.findByName(data.objectName, data.name);
4468
+ const existing = await this.findByNameAndType(data.objectName, data.name, data.type);
4377
4469
  if (existing) {
4378
4470
  return this.update(existing.id, {
4379
4471
  label: data.label,
4380
4472
  description: data.description,
4381
4473
  icon: data.icon,
4382
- tabs: data.tabs,
4474
+ config: data.config,
4383
4475
  default: data.default,
4384
4476
  metadata: data.metadata
4385
4477
  });
4386
4478
  }
4387
4479
  return this.create(data);
4480
+ },
4481
+ async exists(objectName, viewName, type) {
4482
+ const existing = await this.findByNameAndType(objectName, viewName, type);
4483
+ return existing !== null;
4484
+ }
4485
+ };
4486
+ }
4487
+ function createMockViewOverlaysRepository(stores) {
4488
+ return {
4489
+ findById(id) {
4490
+ return Promise.resolve(_nullishCoalesce(stores.viewOverlays.get(id), () => ( null)));
4491
+ },
4492
+ findByViewAndUser(viewId, userId) {
4493
+ const tenantId = getTenantId();
4494
+ return Promise.resolve(
4495
+ _nullishCoalesce(Array.from(stores.viewOverlays.values()).find(
4496
+ (o) => o.tenantId === tenantId && o.viewId === viewId && o.userId === userId
4497
+ ), () => ( null))
4498
+ );
4499
+ },
4500
+ findByUser(userId) {
4501
+ const tenantId = getTenantId();
4502
+ return Promise.resolve(
4503
+ Array.from(stores.viewOverlays.values()).filter(
4504
+ (o) => o.tenantId === tenantId && o.userId === userId
4505
+ )
4506
+ );
4507
+ },
4508
+ findByView(viewId) {
4509
+ const tenantId = getTenantId();
4510
+ return Promise.resolve(
4511
+ Array.from(stores.viewOverlays.values()).filter(
4512
+ (o) => o.tenantId === tenantId && o.viewId === viewId
4513
+ )
4514
+ );
4515
+ },
4516
+ async findUserDefault(userId, objectName, type) {
4517
+ const tenantId = getTenantId();
4518
+ const views = Array.from(stores.views.values()).filter(
4519
+ (v) => v.tenantId === tenantId && v.objectName === objectName && v.type === type
4520
+ );
4521
+ const viewIds = new Set(views.map((v) => v.id));
4522
+ return Promise.resolve(
4523
+ _nullishCoalesce(Array.from(stores.viewOverlays.values()).find(
4524
+ (o) => o.tenantId === tenantId && o.userId === userId && o.isUserDefault === true && viewIds.has(o.viewId)
4525
+ ), () => ( null))
4526
+ );
4527
+ },
4528
+ create(data) {
4529
+ const tenantId = getTenantId();
4530
+ const id = generateId();
4531
+ const now = /* @__PURE__ */ new Date();
4532
+ const overlay = {
4533
+ id,
4534
+ tenantId,
4535
+ viewId: data.viewId,
4536
+ userId: data.userId,
4537
+ configOverrides: data.configOverrides,
4538
+ isUserDefault: data.isUserDefault,
4539
+ createdAt: now,
4540
+ updatedAt: now
4541
+ };
4542
+ stores.viewOverlays.set(id, overlay);
4543
+ return Promise.resolve(overlay);
4544
+ },
4545
+ update(id, data) {
4546
+ const overlay = stores.viewOverlays.get(id);
4547
+ if (!overlay) {
4548
+ return Promise.reject(new Error(`ViewOverlay not found: ${id}`));
4549
+ }
4550
+ const updated = {
4551
+ ...overlay,
4552
+ ...data,
4553
+ updatedAt: /* @__PURE__ */ new Date()
4554
+ };
4555
+ stores.viewOverlays.set(id, updated);
4556
+ return Promise.resolve(updated);
4557
+ },
4558
+ delete(id) {
4559
+ stores.viewOverlays.delete(id);
4560
+ return Promise.resolve();
4561
+ },
4562
+ async deleteByViewAndUser(viewId, userId) {
4563
+ const overlay = await this.findByViewAndUser(viewId, userId);
4564
+ if (overlay) {
4565
+ stores.viewOverlays.delete(overlay.id);
4566
+ }
4567
+ },
4568
+ deleteByView(viewId) {
4569
+ const tenantId = getTenantId();
4570
+ let deleted = 0;
4571
+ for (const [id, overlay] of stores.viewOverlays.entries()) {
4572
+ if (overlay.tenantId === tenantId && overlay.viewId === viewId) {
4573
+ stores.viewOverlays.delete(id);
4574
+ deleted++;
4575
+ }
4576
+ }
4577
+ return Promise.resolve(deleted);
4578
+ },
4579
+ migrateViewId(fromViewId, toViewId) {
4580
+ const tenantId = getTenantId();
4581
+ let migrated = 0;
4582
+ for (const overlay of stores.viewOverlays.values()) {
4583
+ if (overlay.tenantId === tenantId && overlay.viewId === fromViewId) {
4584
+ overlay.viewId = toViewId;
4585
+ overlay.updatedAt = /* @__PURE__ */ new Date();
4586
+ migrated++;
4587
+ }
4588
+ }
4589
+ return Promise.resolve(migrated);
4590
+ },
4591
+ async upsert(data) {
4592
+ const existing = await this.findByViewAndUser(data.viewId, data.userId);
4593
+ if (existing) {
4594
+ return this.update(existing.id, {
4595
+ configOverrides: data.configOverrides,
4596
+ isUserDefault: data.isUserDefault
4597
+ });
4598
+ }
4599
+ return this.create(data);
4600
+ },
4601
+ async clearUserDefault(userId, objectName, type) {
4602
+ const tenantId = getTenantId();
4603
+ const views = Array.from(stores.views.values()).filter(
4604
+ (v) => v.tenantId === tenantId && v.objectName === objectName && v.type === type
4605
+ );
4606
+ const viewIds = new Set(views.map((v) => v.id));
4607
+ for (const overlay of stores.viewOverlays.values()) {
4608
+ if (overlay.tenantId === tenantId && overlay.userId === userId && overlay.isUserDefault === true && viewIds.has(overlay.viewId)) {
4609
+ overlay.isUserDefault = false;
4610
+ overlay.updatedAt = /* @__PURE__ */ new Date();
4611
+ }
4612
+ }
4388
4613
  }
4389
4614
  };
4390
4615
  }
@@ -4522,7 +4747,7 @@ function createMockWorkflowInstancesRepository(stores) {
4522
4747
  (i) => i.tenant_id === tenantId
4523
4748
  );
4524
4749
  const total = results.length;
4525
- if (_optionalChain([options, 'optionalAccess', _82 => _82.limit])) {
4750
+ if (_optionalChain([options, 'optionalAccess', _87 => _87.limit])) {
4526
4751
  results = results.slice(_nullishCoalesce(options.offset, () => ( 0)), (_nullishCoalesce(options.offset, () => ( 0))) + options.limit);
4527
4752
  }
4528
4753
  return Promise.resolve({ instances: results, total });
@@ -4550,7 +4775,7 @@ function createMockWorkflowInstancesRepository(stores) {
4550
4775
  pending_action: _nullishCoalesce(data.pendingAction, () => ( null)),
4551
4776
  error: null,
4552
4777
  started_by: data.startedBy,
4553
- expires_at: _nullishCoalesce(_optionalChain([data, 'access', _83 => _83.expiresAt, 'optionalAccess', _84 => _84.toISOString, 'call', _85 => _85()]), () => ( null)),
4778
+ expires_at: _nullishCoalesce(_optionalChain([data, 'access', _88 => _88.expiresAt, 'optionalAccess', _89 => _89.toISOString, 'call', _90 => _90()]), () => ( null)),
4554
4779
  created_at: now,
4555
4780
  updated_at: now,
4556
4781
  completed_at: null
@@ -4571,8 +4796,8 @@ function createMockWorkflowInstancesRepository(stores) {
4571
4796
  history: _nullishCoalesce(data.history, () => ( existing.history)),
4572
4797
  pending_action: data.pendingAction !== void 0 ? data.pendingAction : existing.pending_action,
4573
4798
  error: data.error !== void 0 ? data.error : existing.error,
4574
- expires_at: data.expiresAt !== void 0 ? _nullishCoalesce(_optionalChain([data, 'access', _86 => _86.expiresAt, 'optionalAccess', _87 => _87.toISOString, 'call', _88 => _88()]), () => ( null)) : existing.expires_at,
4575
- completed_at: data.completedAt !== void 0 ? _nullishCoalesce(_optionalChain([data, 'access', _89 => _89.completedAt, 'optionalAccess', _90 => _90.toISOString, 'call', _91 => _91()]), () => ( null)) : existing.completed_at,
4799
+ expires_at: data.expiresAt !== void 0 ? _nullishCoalesce(_optionalChain([data, 'access', _91 => _91.expiresAt, 'optionalAccess', _92 => _92.toISOString, 'call', _93 => _93()]), () => ( null)) : existing.expires_at,
4800
+ completed_at: data.completedAt !== void 0 ? _nullishCoalesce(_optionalChain([data, 'access', _94 => _94.completedAt, 'optionalAccess', _95 => _95.toISOString, 'call', _96 => _96()]), () => ( null)) : existing.completed_at,
4576
4801
  updated_at: (/* @__PURE__ */ new Date()).toISOString()
4577
4802
  };
4578
4803
  stores.workflowInstances.set(id, updated);
@@ -4605,7 +4830,7 @@ function createMockWorkflowInstancesRepository(stores) {
4605
4830
  pending_action: _nullishCoalesce(data.pendingAction, () => ( null)),
4606
4831
  error: null,
4607
4832
  started_by: data.startedBy,
4608
- expires_at: _nullishCoalesce(_optionalChain([data, 'access', _92 => _92.expiresAt, 'optionalAccess', _93 => _93.toISOString, 'call', _94 => _94()]), () => ( null)),
4833
+ expires_at: _nullishCoalesce(_optionalChain([data, 'access', _97 => _97.expiresAt, 'optionalAccess', _98 => _98.toISOString, 'call', _99 => _99()]), () => ( null)),
4609
4834
  created_at: now,
4610
4835
  updated_at: now,
4611
4836
  completed_at: null
@@ -4628,13 +4853,13 @@ function createMockWorkflowInstancesRepository(stores) {
4628
4853
  return slotData.id === recordId;
4629
4854
  });
4630
4855
  });
4631
- if (_optionalChain([options, 'optionalAccess', _95 => _95.status])) {
4856
+ if (_optionalChain([options, 'optionalAccess', _100 => _100.status])) {
4632
4857
  results = results.filter((i) => i.status === options.status);
4633
4858
  }
4634
4859
  const total = results.length;
4635
- if (_optionalChain([options, 'optionalAccess', _96 => _96.offset]) !== void 0 || _optionalChain([options, 'optionalAccess', _97 => _97.limit]) !== void 0) {
4636
- const start = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _98 => _98.offset]), () => ( 0));
4637
- const end = _optionalChain([options, 'optionalAccess', _99 => _99.limit]) ? start + options.limit : void 0;
4860
+ if (_optionalChain([options, 'optionalAccess', _101 => _101.offset]) !== void 0 || _optionalChain([options, 'optionalAccess', _102 => _102.limit]) !== void 0) {
4861
+ const start = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _103 => _103.offset]), () => ( 0));
4862
+ const end = _optionalChain([options, 'optionalAccess', _104 => _104.limit]) ? start + options.limit : void 0;
4638
4863
  results = results.slice(start, end);
4639
4864
  }
4640
4865
  return Promise.resolve({ instances: results, total });
@@ -4690,7 +4915,7 @@ function createMockWorkflowInvitationsRepository(stores) {
4690
4915
  const updated = {
4691
4916
  ...existing,
4692
4917
  status: _nullishCoalesce(data.status, () => ( existing.status)),
4693
- accepted_at: data.acceptedAt !== void 0 ? _nullishCoalesce(_optionalChain([data, 'access', _100 => _100.acceptedAt, 'optionalAccess', _101 => _101.toISOString, 'call', _102 => _102()]), () => ( null)) : existing.accepted_at,
4918
+ accepted_at: data.acceptedAt !== void 0 ? _nullishCoalesce(_optionalChain([data, 'access', _105 => _105.acceptedAt, 'optionalAccess', _106 => _106.toISOString, 'call', _107 => _107()]), () => ( null)) : existing.accepted_at,
4694
4919
  expires_at: data.expiresAt !== void 0 ? data.expiresAt.toISOString() : existing.expires_at
4695
4920
  };
4696
4921
  stores.workflowInvitations.set(id, updated);
@@ -4756,7 +4981,7 @@ function createMockWorkflowAccessGrantsRepository(stores) {
4756
4981
  ...existing,
4757
4982
  last_used_at: data.lastUsedAt !== void 0 ? data.lastUsedAt.toISOString() : existing.last_used_at,
4758
4983
  revoked_token_jtis: _nullishCoalesce(data.revokedTokenJtis, () => ( existing.revoked_token_jtis)),
4759
- revoked_at: data.revokedAt !== void 0 ? _nullishCoalesce(_optionalChain([data, 'access', _103 => _103.revokedAt, 'optionalAccess', _104 => _104.toISOString, 'call', _105 => _105()]), () => ( null)) : existing.revoked_at
4984
+ revoked_at: data.revokedAt !== void 0 ? _nullishCoalesce(_optionalChain([data, 'access', _108 => _108.revokedAt, 'optionalAccess', _109 => _109.toISOString, 'call', _110 => _110()]), () => ( null)) : existing.revoked_at
4760
4985
  };
4761
4986
  stores.workflowAccessGrants.set(id, updated);
4762
4987
  return Promise.resolve(updated);
@@ -4774,6 +4999,7 @@ function createMockAdapter() {
4774
4999
  files: createMockFilesRepository(stores),
4775
5000
  objectRecords: createMockObjectRecordsRepository(stores),
4776
5001
  views: createMockViewsRepository(stores),
5002
+ viewOverlays: createMockViewOverlaysRepository(stores),
4777
5003
  permissions: createMockPermissionsRepository(stores),
4778
5004
  workflows: createMockWorkflowsRepository(stores),
4779
5005
  workflowInstances: createMockWorkflowInstancesRepository(stores),
@@ -4796,6 +5022,7 @@ function createMockAdapter() {
4796
5022
  stores.files.clear();
4797
5023
  stores.objectRecords.clear();
4798
5024
  stores.views.clear();
5025
+ stores.viewOverlays.clear();
4799
5026
  stores.roles.clear();
4800
5027
  stores.permissions.clear();
4801
5028
  stores.userRoles.clear();
@@ -4900,7 +5127,7 @@ var notesPolicy = {
4900
5127
  { attribute: "visibility", operator: "is", value: "shared" },
4901
5128
  { attribute: "createdBy", operator: "is", value: ctx.userId }
4902
5129
  ];
4903
- if (!_optionalChain([options, 'optionalAccess', _106 => _106.filters]) || options.filters.rules.length === 0) {
5130
+ if (!_optionalChain([options, 'optionalAccess', _111 => _111.filters]) || options.filters.rules.length === 0) {
4904
5131
  return {
4905
5132
  ...options,
4906
5133
  filters: { combinator: "or", rules: visibilityRules }
@@ -5046,7 +5273,7 @@ var BaseService = class {
5046
5273
  * @param key - Cache key to invalidate
5047
5274
  */
5048
5275
  async invalidateCache(key) {
5049
- await _optionalChain([this, 'access', _107 => _107.cache, 'optionalAccess', _108 => _108.delete, 'call', _109 => _109(key)]);
5276
+ await _optionalChain([this, 'access', _112 => _112.cache, 'optionalAccess', _113 => _113.delete, 'call', _114 => _114(key)]);
5050
5277
  }
5051
5278
  /**
5052
5279
  * Invalidate all cache keys matching a pattern.
@@ -5054,7 +5281,7 @@ var BaseService = class {
5054
5281
  * @param pattern - Glob-style pattern (e.g., "schema:tenant-123:*")
5055
5282
  */
5056
5283
  async invalidateCachePattern(pattern) {
5057
- await _optionalChain([this, 'access', _110 => _110.cache, 'optionalAccess', _111 => _111.deletePattern, 'call', _112 => _112(pattern)]);
5284
+ await _optionalChain([this, 'access', _115 => _115.cache, 'optionalAccess', _116 => _116.deletePattern, 'call', _117 => _117(pattern)]);
5058
5285
  }
5059
5286
  /**
5060
5287
  * Invalidate all cached lists for a resource.
@@ -5252,17 +5479,17 @@ function validateOptions(options, attributeName) {
5252
5479
  const ids = /* @__PURE__ */ new Set();
5253
5480
  const values = /* @__PURE__ */ new Set();
5254
5481
  for (const option of options) {
5255
- if (!_optionalChain([option, 'access', _113 => _113.id, 'optionalAccess', _114 => _114.trim, 'call', _115 => _115()])) {
5482
+ if (!_optionalChain([option, 'access', _118 => _118.id, 'optionalAccess', _119 => _119.trim, 'call', _120 => _120()])) {
5256
5483
  throw new Error(
5257
5484
  `[AttributeBuilder] Option in "${attributeName}" has an empty or missing id.`
5258
5485
  );
5259
5486
  }
5260
- if (!_optionalChain([option, 'access', _116 => _116.value, 'optionalAccess', _117 => _117.trim, 'call', _118 => _118()])) {
5487
+ if (!_optionalChain([option, 'access', _121 => _121.value, 'optionalAccess', _122 => _122.trim, 'call', _123 => _123()])) {
5261
5488
  throw new Error(
5262
5489
  `[AttributeBuilder] Option "${option.id}" in "${attributeName}" has an empty or missing value.`
5263
5490
  );
5264
5491
  }
5265
- if (!_optionalChain([option, 'access', _119 => _119.label, 'optionalAccess', _120 => _120.trim, 'call', _121 => _121()])) {
5492
+ if (!_optionalChain([option, 'access', _124 => _124.label, 'optionalAccess', _125 => _125.trim, 'call', _126 => _126()])) {
5266
5493
  throw new Error(
5267
5494
  `[AttributeBuilder] Option "${option.id}" in "${attributeName}" has an empty or missing label.`
5268
5495
  );
@@ -5339,6 +5566,32 @@ var BaseAttributeBuilder = class {
5339
5566
  this.attr.metadata = value;
5340
5567
  return this;
5341
5568
  }
5569
+ /**
5570
+ * Add a feature gate to conditionally show/hide/disable this attribute.
5571
+ *
5572
+ * @param flagName - Name of the feature flag to check
5573
+ * @param options - Optional configuration for expected value and fallback behavior
5574
+ *
5575
+ * @example Hide attribute when flag is disabled
5576
+ * ```typescript
5577
+ * text({ name: "aiSummary", label: "AI Summary" })
5578
+ * .featureGate("ai-features")
5579
+ * ```
5580
+ *
5581
+ * @example Disable attribute when tier is not enterprise
5582
+ * ```typescript
5583
+ * text({ name: "advancedField", label: "Advanced Field" })
5584
+ * .featureGate("tier", { expectedValue: "enterprise", fallback: "disable" })
5585
+ * ```
5586
+ */
5587
+ featureGate(flagName, options) {
5588
+ this.attr.featureGate = {
5589
+ flag: flagName,
5590
+ expectedValue: _optionalChain([options, 'optionalAccess', _127 => _127.expectedValue]),
5591
+ fallback: _optionalChain([options, 'optionalAccess', _128 => _128.fallback])
5592
+ };
5593
+ return this;
5594
+ }
5342
5595
  build() {
5343
5596
  return this.attr;
5344
5597
  }
@@ -5783,7 +6036,7 @@ var SingleRelationAttributeBuilder = class extends BaseAttributeBuilder {
5783
6036
  object: objectName,
5784
6037
  ...options
5785
6038
  };
5786
- _optionalChain([this, 'access', _122 => _122.attr, 'access', _123 => _123.targets, 'optionalAccess', _124 => _124.push, 'call', _125 => _125(target)]);
6039
+ _optionalChain([this, 'access', _129 => _129.attr, 'access', _130 => _130.targets, 'optionalAccess', _131 => _131.push, 'call', _132 => _132(target)]);
5787
6040
  return this;
5788
6041
  }
5789
6042
  /**
@@ -5828,9 +6081,9 @@ var MultiRelationAttributeBuilder = class extends BaseAttributeBuilder {
5828
6081
  constructor(name, label, initOptions) {
5829
6082
  super("relation", name, label);
5830
6083
  this.attr.cardinality = "many";
5831
- this.attr.targets = _nullishCoalesce(_optionalChain([initOptions, 'optionalAccess', _126 => _126.targets]), () => ( []));
6084
+ this.attr.targets = _nullishCoalesce(_optionalChain([initOptions, 'optionalAccess', _133 => _133.targets]), () => ( []));
5832
6085
  this.attr.defaultValue = [];
5833
- if (_optionalChain([initOptions, 'optionalAccess', _127 => _127.isRequired])) {
6086
+ if (_optionalChain([initOptions, 'optionalAccess', _134 => _134.isRequired])) {
5834
6087
  this.setRequired(true);
5835
6088
  }
5836
6089
  }
@@ -5844,7 +6097,7 @@ var MultiRelationAttributeBuilder = class extends BaseAttributeBuilder {
5844
6097
  object: objectName,
5845
6098
  ...options
5846
6099
  };
5847
- _optionalChain([this, 'access', _128 => _128.attr, 'access', _129 => _129.targets, 'optionalAccess', _130 => _130.push, 'call', _131 => _131(target)]);
6100
+ _optionalChain([this, 'access', _135 => _135.attr, 'access', _136 => _136.targets, 'optionalAccess', _137 => _137.push, 'call', _138 => _138(target)]);
5848
6101
  return this;
5849
6102
  }
5850
6103
  /**
@@ -6261,6 +6514,7 @@ function object(config) {
6261
6514
  }
6262
6515
 
6263
6516
  // src/builders/view-builder.ts
6517
+ var _crypto = require('crypto');
6264
6518
 
6265
6519
  var GroupBuilder = class {
6266
6520
  constructor(id, label) {
@@ -6297,7 +6551,7 @@ var GroupBuilder = class {
6297
6551
  */
6298
6552
  fields(...names) {
6299
6553
  for (const name of names) {
6300
- _optionalChain([this, 'access', _132 => _132.data, 'access', _133 => _133.fields, 'optionalAccess', _134 => _134.push, 'call', _135 => _135({ attribute: name })]);
6554
+ _optionalChain([this, 'access', _139 => _139.data, 'access', _140 => _140.fields, 'optionalAccess', _141 => _141.push, 'call', _142 => _142({ attribute: name })]);
6301
6555
  }
6302
6556
  return this;
6303
6557
  }
@@ -6306,7 +6560,7 @@ var GroupBuilder = class {
6306
6560
  * @example .field("name", { span: 8, readOnly: true })
6307
6561
  */
6308
6562
  field(attribute, options) {
6309
- _optionalChain([this, 'access', _136 => _136.data, 'access', _137 => _137.fields, 'optionalAccess', _138 => _138.push, 'call', _139 => _139({ attribute, ...options })]);
6563
+ _optionalChain([this, 'access', _143 => _143.data, 'access', _144 => _144.fields, 'optionalAccess', _145 => _145.push, 'call', _146 => _146({ attribute, ...options })]);
6310
6564
  return this;
6311
6565
  }
6312
6566
  /**
@@ -6315,7 +6569,7 @@ var GroupBuilder = class {
6315
6569
  * @example .attributeGroup({ id: "address", label: "Address", attributes: ["street", "city", "postal_code"], displayTemplate: "{street}, {city}" })
6316
6570
  */
6317
6571
  attributeGroup(config, options) {
6318
- _optionalChain([this, 'access', _140 => _140.data, 'access', _141 => _141.fields, 'optionalAccess', _142 => _142.push, 'call', _143 => _143({ attributeGroup: config, ...options })]);
6572
+ _optionalChain([this, 'access', _147 => _147.data, 'access', _148 => _148.fields, 'optionalAccess', _149 => _149.push, 'call', _150 => _150({ attributeGroup: config, ...options })]);
6319
6573
  return this;
6320
6574
  }
6321
6575
  /**
@@ -6411,7 +6665,7 @@ var BaseTableTabConfig = class {
6411
6665
  return new TabBuilder(this.view, name, label);
6412
6666
  }
6413
6667
  /**
6414
- * Finish this tab and return to ViewBuilder
6668
+ * Finish this tab and return to DetailViewBuilder
6415
6669
  */
6416
6670
  done() {
6417
6671
  this.finalize();
@@ -6477,7 +6731,7 @@ var CustomTabConfig = class {
6477
6731
  return new TabBuilder(this.view, name, label);
6478
6732
  }
6479
6733
  /**
6480
- * Finish this tab and return to ViewBuilder
6734
+ * Finish this tab and return to DetailViewBuilder
6481
6735
  */
6482
6736
  done() {
6483
6737
  this.view._addTab(this.tabData);
@@ -6519,7 +6773,7 @@ var NotesTabConfig = class {
6519
6773
  return new TabBuilder(this.view, name, label);
6520
6774
  }
6521
6775
  /**
6522
- * Finish this tab and return to ViewBuilder
6776
+ * Finish this tab and return to DetailViewBuilder
6523
6777
  */
6524
6778
  done() {
6525
6779
  this.view._addTab(this.tabData);
@@ -6554,7 +6808,7 @@ var ActivityTabConfig = class {
6554
6808
  return new TabBuilder(this.view, name, label);
6555
6809
  }
6556
6810
  /**
6557
- * Finish this tab and return to ViewBuilder
6811
+ * Finish this tab and return to DetailViewBuilder
6558
6812
  */
6559
6813
  done() {
6560
6814
  this.view._addTab(this.tabData);
@@ -6617,7 +6871,7 @@ var FlowsTabConfig = class {
6617
6871
  return new TabBuilder(this.view, name, label);
6618
6872
  }
6619
6873
  /**
6620
- * Finish this tab and return to ViewBuilder
6874
+ * Finish this tab and return to DetailViewBuilder
6621
6875
  */
6622
6876
  done() {
6623
6877
  this.view._addTab(this.tabData);
@@ -6688,7 +6942,7 @@ var DocumentsTabConfig = class {
6688
6942
  return new TabBuilder(this.view, name, label);
6689
6943
  }
6690
6944
  /**
6691
- * Finish this tab and return to ViewBuilder
6945
+ * Finish this tab and return to DetailViewBuilder
6692
6946
  */
6693
6947
  done() {
6694
6948
  this.view._addTab(this.tabData);
@@ -6726,13 +6980,6 @@ var TabBuilder = class {
6726
6980
  this.base.order = value;
6727
6981
  return this;
6728
6982
  }
6729
- /**
6730
- * Mark as system tab (protected)
6731
- */
6732
- system() {
6733
- this.base.system = true;
6734
- return this;
6735
- }
6736
6983
  // ─────────────────────────────────────────────────────────────────────────
6737
6984
  // TYPE DISCRIMINATORS
6738
6985
  // ─────────────────────────────────────────────────────────────────────────
@@ -6812,13 +7059,15 @@ var TabBuilder = class {
6812
7059
  return new DocumentsTabConfig(this.view, this.base);
6813
7060
  }
6814
7061
  };
6815
- var ViewBuilder = class {
7062
+ var DetailViewBuilder = class {
6816
7063
  constructor(name, label) {
6817
- this.data = { tabs: [] };
6818
- this.validated = false;
6819
7064
  this.validateName(name);
6820
- this.data.name = name;
6821
- this.data.label = label;
7065
+ this.data = {
7066
+ name,
7067
+ label,
7068
+ layout: "page",
7069
+ tabs: []
7070
+ };
6822
7071
  }
6823
7072
  /**
6824
7073
  * Set view description
@@ -6843,19 +7092,12 @@ var ViewBuilder = class {
6843
7092
  return this;
6844
7093
  }
6845
7094
  /**
6846
- * Mark as default view for the object (within its layout)
7095
+ * Mark as default view for the object
6847
7096
  */
6848
7097
  default() {
6849
7098
  this.data.default = true;
6850
7099
  return this;
6851
7100
  }
6852
- /**
6853
- * Mark as system view (protected, defined by developer)
6854
- */
6855
- system() {
6856
- this.data.system = true;
6857
- return this;
6858
- }
6859
7101
  /**
6860
7102
  * Set the layout mode for the view
6861
7103
  * @param value - "page" for full tabs, "modal" for single form
@@ -6890,14 +7132,14 @@ var ViewBuilder = class {
6890
7132
  * Add a pre-built tab
6891
7133
  */
6892
7134
  addTab(tab) {
6893
- _optionalChain([this, 'access', _144 => _144.data, 'access', _145 => _145.tabs, 'optionalAccess', _146 => _146.push, 'call', _147 => _147(tab)]);
7135
+ this.data.tabs.push(tab);
6894
7136
  return this;
6895
7137
  }
6896
7138
  /**
6897
7139
  * @internal Used by TabBuilder to add tabs
6898
7140
  */
6899
7141
  _addTab(tab) {
6900
- _optionalChain([this, 'access', _148 => _148.data, 'access', _149 => _149.tabs, 'optionalAccess', _150 => _150.push, 'call', _151 => _151(tab)]);
7142
+ this.data.tabs.push(tab);
6901
7143
  return this;
6902
7144
  }
6903
7145
  /**
@@ -6905,28 +7147,41 @@ var ViewBuilder = class {
6905
7147
  */
6906
7148
  build() {
6907
7149
  if (!this.data.object) {
6908
- throw new Error("[ViewBuilder] for() is required - specify the target object");
7150
+ throw new Error("[DetailViewBuilder] for() is required - specify the target object");
6909
7151
  }
6910
- if (!this.data.tabs || this.data.tabs.length === 0) {
6911
- throw new Error("[ViewBuilder] At least one tab is required");
7152
+ if (this.data.tabs.length === 0) {
7153
+ throw new Error("[DetailViewBuilder] At least one tab is required");
6912
7154
  }
6913
7155
  const tabNames = /* @__PURE__ */ new Set();
6914
7156
  for (const tab of this.data.tabs) {
6915
7157
  if (tabNames.has(tab.name)) {
6916
- throw new Error(`[ViewBuilder] Duplicate tab name "${tab.name}"`);
7158
+ throw new Error(`[DetailViewBuilder] Duplicate tab name "${tab.name}"`);
6917
7159
  }
6918
7160
  tabNames.add(tab.name);
6919
7161
  }
6920
7162
  if (this.data.layout === "modal") {
6921
7163
  if (this.data.tabs.length !== 1) {
6922
- throw new Error("[ViewBuilder] Modal views must have exactly one tab");
7164
+ throw new Error("[DetailViewBuilder] Modal views must have exactly one tab");
6923
7165
  }
6924
7166
  if (this.data.tabs[0].type !== "form") {
6925
- throw new Error("[ViewBuilder] Modal views must have a form tab");
7167
+ throw new Error("[DetailViewBuilder] Modal views must have a form tab");
6926
7168
  }
6927
7169
  }
6928
- this.validated = true;
6929
- return this.data;
7170
+ const config = {
7171
+ layout: this.data.layout,
7172
+ tabs: this.data.tabs
7173
+ };
7174
+ return {
7175
+ name: this.data.name,
7176
+ label: this.data.label,
7177
+ description: this.data.description,
7178
+ icon: this.data.icon,
7179
+ object: this.data.object,
7180
+ type: "detail",
7181
+ config,
7182
+ default: this.data.default,
7183
+ metadata: this.data.metadata
7184
+ };
6930
7185
  }
6931
7186
  /**
6932
7187
  * Validate view name format (kebab-case)
@@ -6939,14 +7194,285 @@ var ViewBuilder = class {
6939
7194
  viewNameSchema.parse(name);
6940
7195
  } catch (error2) {
6941
7196
  if (error2 instanceof _zod.z.ZodError) {
6942
- throw new Error(`[ViewBuilder] ${error2.issues[0].message}`);
7197
+ throw new Error(`[DetailViewBuilder] ${error2.issues[0].message}`);
6943
7198
  }
6944
7199
  throw error2;
6945
7200
  }
6946
7201
  }
6947
7202
  };
7203
+ var ViewBuilder = DetailViewBuilder;
7204
+ function detailView(name, label) {
7205
+ return new DetailViewBuilder(name, label);
7206
+ }
6948
7207
  function view(name, label) {
6949
- return new ViewBuilder(name, label);
7208
+ return new DetailViewBuilder(name, label);
7209
+ }
7210
+ var ListViewBuilder = class {
7211
+ constructor(name, label) {
7212
+ this.validateName(name);
7213
+ this.data = {
7214
+ name,
7215
+ label,
7216
+ layout: "table",
7217
+ columns: [],
7218
+ tabs: []
7219
+ };
7220
+ }
7221
+ /**
7222
+ * Set view description
7223
+ */
7224
+ description(value) {
7225
+ this.data.description = value;
7226
+ return this;
7227
+ }
7228
+ /**
7229
+ * Set view icon
7230
+ */
7231
+ icon(value) {
7232
+ this.data.icon = value;
7233
+ return this;
7234
+ }
7235
+ /**
7236
+ * Associate view with an object
7237
+ * @param objectName - Object name (kebab-case)
7238
+ */
7239
+ for(objectName) {
7240
+ this.data.object = objectName;
7241
+ return this;
7242
+ }
7243
+ /**
7244
+ * Mark as default view for the object
7245
+ */
7246
+ default() {
7247
+ this.data.default = true;
7248
+ return this;
7249
+ }
7250
+ /**
7251
+ * Set metadata
7252
+ */
7253
+ metadata(value) {
7254
+ this.data.metadata = value;
7255
+ return this;
7256
+ }
7257
+ /**
7258
+ * Set the layout to table (default)
7259
+ */
7260
+ table() {
7261
+ this.data.layout = "table";
7262
+ return this;
7263
+ }
7264
+ /**
7265
+ * Set the layout to kanban and specify the grouping attribute
7266
+ * @param groupByAttribute - Attribute to group by (must be a select/status type)
7267
+ */
7268
+ kanban(groupByAttribute) {
7269
+ this.data.layout = "kanban";
7270
+ this.data.groupByAttribute = groupByAttribute;
7271
+ return this;
7272
+ }
7273
+ /**
7274
+ * Set columns to display
7275
+ * @example .columns("name", "email", "status", "createdAt")
7276
+ */
7277
+ columns(...names) {
7278
+ this.data.columns = names;
7279
+ return this;
7280
+ }
7281
+ /**
7282
+ * Set width for a specific column in pixels
7283
+ * @example .columnWidth("email", 200)
7284
+ */
7285
+ columnWidth(columnName, width) {
7286
+ if (!this.data.columnSizing) {
7287
+ this.data.columnSizing = {};
7288
+ }
7289
+ this.data.columnSizing[columnName] = width;
7290
+ return this;
7291
+ }
7292
+ /**
7293
+ * Set widths for multiple columns
7294
+ * @example .columnWidths({ email: 200, name: 300, status: 100 })
7295
+ */
7296
+ columnWidths(widths) {
7297
+ this.data.columnSizing = { ...this.data.columnSizing, ...widths };
7298
+ return this;
7299
+ }
7300
+ /**
7301
+ * Set default filters
7302
+ * @example .filter({ combinator: "and", rules: [{ attribute: "status", operator: "is", value: "active" }] })
7303
+ */
7304
+ filter(filters) {
7305
+ this.data.defaultFilters = filters;
7306
+ return this;
7307
+ }
7308
+ /**
7309
+ * Add a single sort rule
7310
+ * @example .sort("lastName", "asc")
7311
+ */
7312
+ sort(attribute, direction = "asc") {
7313
+ if (!this.data.defaultSorts) {
7314
+ this.data.defaultSorts = [];
7315
+ }
7316
+ this.data.defaultSorts.push({ attribute, direction });
7317
+ return this;
7318
+ }
7319
+ /**
7320
+ * Set multiple sort rules
7321
+ * @example .sorts([{ attribute: "lastName", direction: "asc" }, { attribute: "firstName", direction: "asc" }])
7322
+ */
7323
+ sorts(rules) {
7324
+ this.data.defaultSorts = rules;
7325
+ return this;
7326
+ }
7327
+ /**
7328
+ * Add an internal tab (filter preset)
7329
+ * Returns a TabConfigBuilder for chaining tab configuration
7330
+ * @example
7331
+ * ```typescript
7332
+ * .tab("all", "All Contacts").icon("users").default()
7333
+ * .tab("active", "Active").icon("check").filter({ ... })
7334
+ * ```
7335
+ */
7336
+ tab(id, label) {
7337
+ return new ListViewTabConfigBuilder(this, id, label);
7338
+ }
7339
+ /**
7340
+ * @internal Used by ListViewTabConfigBuilder to add tabs
7341
+ */
7342
+ _addTab(tab) {
7343
+ this.data.tabs.push(tab);
7344
+ return this;
7345
+ }
7346
+ /**
7347
+ * Build the final list view definition
7348
+ */
7349
+ build() {
7350
+ if (!this.data.object) {
7351
+ throw new Error("[ListViewBuilder] for() is required - specify the target object");
7352
+ }
7353
+ if (this.data.columns.length === 0) {
7354
+ throw new Error("[ListViewBuilder] columns() is required - specify at least one column");
7355
+ }
7356
+ if (this.data.layout === "kanban" && !this.data.groupByAttribute) {
7357
+ throw new Error(
7358
+ "[ListViewBuilder] kanban() requires a groupByAttribute - specify the attribute to group by"
7359
+ );
7360
+ }
7361
+ const tabIds = /* @__PURE__ */ new Set();
7362
+ for (const tab of this.data.tabs) {
7363
+ if (tabIds.has(tab.id)) {
7364
+ throw new Error(`[ListViewBuilder] Duplicate tab id "${tab.id}"`);
7365
+ }
7366
+ tabIds.add(tab.id);
7367
+ }
7368
+ const defaultTabs = this.data.tabs.filter((t) => t.default);
7369
+ if (defaultTabs.length > 1) {
7370
+ throw new Error("[ListViewBuilder] Only one tab can be marked as default");
7371
+ }
7372
+ const config = {
7373
+ layout: this.data.layout,
7374
+ columns: this.data.columns,
7375
+ columnSizing: this.data.columnSizing,
7376
+ defaultFilters: this.data.defaultFilters ? {
7377
+ id: _crypto.randomUUID.call(void 0, ),
7378
+ combinator: this.data.defaultFilters.combinator,
7379
+ rules: this.data.defaultFilters.rules
7380
+ } : void 0,
7381
+ defaultSorts: this.data.defaultSorts,
7382
+ groupByAttribute: this.data.groupByAttribute,
7383
+ tabs: this.data.tabs.length > 0 ? this.data.tabs.map((tab) => ({
7384
+ id: tab.id,
7385
+ label: tab.label,
7386
+ icon: tab.icon,
7387
+ filters: tab.filters ? {
7388
+ id: _crypto.randomUUID.call(void 0, ),
7389
+ combinator: tab.filters.combinator,
7390
+ rules: tab.filters.rules
7391
+ } : void 0,
7392
+ default: tab.default
7393
+ })) : void 0
7394
+ };
7395
+ return {
7396
+ name: this.data.name,
7397
+ label: this.data.label,
7398
+ description: this.data.description,
7399
+ icon: this.data.icon,
7400
+ object: this.data.object,
7401
+ type: "list",
7402
+ config,
7403
+ default: this.data.default,
7404
+ metadata: this.data.metadata
7405
+ };
7406
+ }
7407
+ /**
7408
+ * Validate view name format (kebab-case)
7409
+ */
7410
+ validateName(name) {
7411
+ const viewNameSchema = _zod.z.string().min(1, "View name cannot be empty").max(63, "View name is too long (max 63 characters)").regex(/^[a-z][a-z0-9-]*$/, {
7412
+ message: "Invalid view name format.\nName must be in kebab-case:\n \u2705 Valid: 'default', 'list-view', 'active-contacts'\n \u274C Invalid: 'Default', 'listView', 'list_view'"
7413
+ });
7414
+ try {
7415
+ viewNameSchema.parse(name);
7416
+ } catch (error2) {
7417
+ if (error2 instanceof _zod.z.ZodError) {
7418
+ throw new Error(`[ListViewBuilder] ${error2.issues[0].message}`);
7419
+ }
7420
+ throw error2;
7421
+ }
7422
+ }
7423
+ };
7424
+ var ListViewTabConfigBuilder = class _ListViewTabConfigBuilder {
7425
+ /** @internal */
7426
+ constructor(view2, id, label) {
7427
+ this.view = view2;
7428
+ this.tabData = { id, label };
7429
+ }
7430
+ /**
7431
+ * Set tab icon
7432
+ */
7433
+ icon(value) {
7434
+ this.tabData.icon = value;
7435
+ return this;
7436
+ }
7437
+ /**
7438
+ * Set filters for this tab (filter preset)
7439
+ * @example .filter({ combinator: "and", rules: [{ attribute: "status", operator: "is", value: "active" }] })
7440
+ */
7441
+ filter(filters) {
7442
+ this.tabData.filters = filters;
7443
+ return this;
7444
+ }
7445
+ /**
7446
+ * Mark this tab as the default tab
7447
+ */
7448
+ default() {
7449
+ this.tabData.default = true;
7450
+ return this;
7451
+ }
7452
+ /**
7453
+ * Continue building with a new tab
7454
+ */
7455
+ tab(id, label) {
7456
+ this.view._addTab(this.tabData);
7457
+ return new _ListViewTabConfigBuilder(this.view, id, label);
7458
+ }
7459
+ /**
7460
+ * Finish this tab and return to ListViewBuilder
7461
+ */
7462
+ done() {
7463
+ this.view._addTab(this.tabData);
7464
+ return this.view;
7465
+ }
7466
+ /**
7467
+ * Build the final view definition
7468
+ */
7469
+ build() {
7470
+ this.view._addTab(this.tabData);
7471
+ return this.view.build();
7472
+ }
7473
+ };
7474
+ function listView(name, label) {
7475
+ return new ListViewBuilder(name, label);
6950
7476
  }
6951
7477
  function group(id, label) {
6952
7478
  return new GroupBuilder(id, label);
@@ -6975,8 +7501,8 @@ var WorkflowFormRowBuilder = class {
6975
7501
  id: `${this.rowData.id}-${slotId}-${attribute}`,
6976
7502
  slotId,
6977
7503
  attribute,
6978
- label: _optionalChain([options, 'optionalAccess', _152 => _152.label]),
6979
- required: _optionalChain([options, 'optionalAccess', _153 => _153.required])
7504
+ label: _optionalChain([options, 'optionalAccess', _151 => _151.label]),
7505
+ required: _optionalChain([options, 'optionalAccess', _152 => _152.required])
6980
7506
  };
6981
7507
  this.rowData.fields.push(field);
6982
7508
  return this;
@@ -7267,7 +7793,7 @@ var WorkflowBuilder = class {
7267
7793
  * @param options - Slot configuration
7268
7794
  */
7269
7795
  slot(id, objectName, options) {
7270
- if (_optionalChain([this, 'access', _154 => _154.data, 'access', _155 => _155.slots, 'optionalAccess', _156 => _156.some, 'call', _157 => _157((s) => s.id === id)])) {
7796
+ if (_optionalChain([this, 'access', _153 => _153.data, 'access', _154 => _154.slots, 'optionalAccess', _155 => _155.some, 'call', _156 => _156((s) => s.id === id)])) {
7271
7797
  throw new Error(`[WorkflowBuilder] Duplicate slot id: "${id}"`);
7272
7798
  }
7273
7799
  const slot = {
@@ -7278,7 +7804,7 @@ var WorkflowBuilder = class {
7278
7804
  color: options.color,
7279
7805
  icon: options.icon
7280
7806
  };
7281
- _optionalChain([this, 'access', _158 => _158.data, 'access', _159 => _159.slots, 'optionalAccess', _160 => _160.push, 'call', _161 => _161(slot)]);
7807
+ _optionalChain([this, 'access', _157 => _157.data, 'access', _158 => _158.slots, 'optionalAccess', _159 => _159.push, 'call', _160 => _160(slot)]);
7282
7808
  return this;
7283
7809
  }
7284
7810
  // ============================================================================
@@ -7410,7 +7936,7 @@ var WorkflowBuilder = class {
7410
7936
  }
7411
7937
  }
7412
7938
  validateSlotReferences() {
7413
- const slotIds = new Set(_nullishCoalesce(_optionalChain([this, 'access', _162 => _162.data, 'access', _163 => _163.slots, 'optionalAccess', _164 => _164.map, 'call', _165 => _165((s) => s.id)]), () => ( [])));
7939
+ const slotIds = new Set(_nullishCoalesce(_optionalChain([this, 'access', _161 => _161.data, 'access', _162 => _162.slots, 'optionalAccess', _163 => _163.map, 'call', _164 => _164((s) => s.id)]), () => ( [])));
7414
7940
  for (const node of Object.values(_nullishCoalesce(this.data.nodes, () => ( {})))) {
7415
7941
  if (node.type === "form") {
7416
7942
  const referencedSlots = /* @__PURE__ */ new Set();
@@ -7492,6 +8018,46 @@ function workflow(name, label) {
7492
8018
  return new WorkflowBuilder(name, label);
7493
8019
  }
7494
8020
 
8021
+ // src/types/attribute-protection.ts
8022
+ var IDENTITY_PROPERTIES = ["name", "type"];
8023
+ var BEHAVIOR_PROPERTIES = [
8024
+ "required",
8025
+ "disabled",
8026
+ "hidden",
8027
+ "archived",
8028
+ "deprecated",
8029
+ "defaultValue",
8030
+ "config",
8031
+ "order",
8032
+ "unique"
8033
+ ];
8034
+ var PRESENTATION_PROPERTIES = ["label", "description", "placeholder", "icon"];
8035
+ function isIdentityProperty(property) {
8036
+ return IDENTITY_PROPERTIES.includes(property);
8037
+ }
8038
+ function isBehaviorProperty(property) {
8039
+ return BEHAVIOR_PROPERTIES.includes(property);
8040
+ }
8041
+ function isPresentationProperty(property) {
8042
+ return PRESENTATION_PROPERTIES.includes(property);
8043
+ }
8044
+ function getPropertyProtectionLevel(property) {
8045
+ if (isIdentityProperty(property)) return "identity";
8046
+ if (isBehaviorProperty(property)) return "behavior";
8047
+ if (isPresentationProperty(property)) return "presentation";
8048
+ return "unknown";
8049
+ }
8050
+ function filterPropertiesByCategory(properties, category) {
8051
+ switch (category) {
8052
+ case "identity":
8053
+ return properties.filter(isIdentityProperty);
8054
+ case "behavior":
8055
+ return properties.filter(isBehaviorProperty);
8056
+ case "presentation":
8057
+ return properties.filter(isPresentationProperty);
8058
+ }
8059
+ }
8060
+
7495
8061
  // src/types/errors.ts
7496
8062
  var RecordReferencedError = class extends Error {
7497
8063
  constructor(recordId, references) {
@@ -8091,7 +8657,7 @@ function validateObject(objectDef, data) {
8091
8657
  function validateObjectOrThrow(objectDef, data) {
8092
8658
  const result = validateObject(objectDef, data);
8093
8659
  if (!result.success) {
8094
- const errorMessages = _optionalChain([result, 'access', _166 => _166.errors, 'optionalAccess', _167 => _167.map, 'call', _168 => _168((err) => `${err.path.join(".")}: ${err.message}`), 'access', _169 => _169.join, 'call', _170 => _170("\n")]) || "Unknown validation error";
8660
+ const errorMessages = _optionalChain([result, 'access', _165 => _165.errors, 'optionalAccess', _166 => _166.map, 'call', _167 => _167((err) => `${err.path.join(".")}: ${err.message}`), 'access', _168 => _168.join, 'call', _169 => _169("\n")]) || "Unknown validation error";
8095
8661
  throw new Error(`Validation failed for ${objectDef.label}:
8096
8662
  ${errorMessages}`);
8097
8663
  }
@@ -8125,7 +8691,7 @@ function validateDraft(objectDef, data) {
8125
8691
  function validateDraftOrThrow(objectDef, data) {
8126
8692
  const result = validateDraft(objectDef, data);
8127
8693
  if (!result.success) {
8128
- const errorMessages = _optionalChain([result, 'access', _171 => _171.errors, 'optionalAccess', _172 => _172.map, 'call', _173 => _173((err) => `${err.path.join(".")}: ${err.message}`), 'access', _174 => _174.join, 'call', _175 => _175("\n")]) || "Unknown validation error";
8694
+ const errorMessages = _optionalChain([result, 'access', _170 => _170.errors, 'optionalAccess', _171 => _171.map, 'call', _172 => _172((err) => `${err.path.join(".")}: ${err.message}`), 'access', _173 => _173.join, 'call', _174 => _174("\n")]) || "Unknown validation error";
8129
8695
  throw new Error(`Draft validation failed for ${objectDef.label}:
8130
8696
  ${errorMessages}`);
8131
8697
  }
@@ -8181,7 +8747,7 @@ var ObjectSchemaService = class extends BaseService {
8181
8747
  constructor(adapter, nativeRegistry, options) {
8182
8748
  super(adapter);
8183
8749
  this.nativeRegistry = nativeRegistry;
8184
- this.auditService = _optionalChain([options, 'optionalAccess', _176 => _176.auditService]);
8750
+ this.auditService = _optionalChain([options, 'optionalAccess', _175 => _175.auditService]);
8185
8751
  }
8186
8752
  /**
8187
8753
  * Create a new custom object.
@@ -8321,7 +8887,8 @@ var ObjectSchemaService = class extends BaseService {
8321
8887
  }
8322
8888
  /**
8323
8889
  * Update an attribute.
8324
- * Can only update custom attributes (system=false).
8890
+ * Custom attributes can be fully updated.
8891
+ * System attributes can only have presentation properties modified (label, description, placeholder, icon).
8325
8892
  * Automatically uses tenant context from AsyncLocalStorage.
8326
8893
  *
8327
8894
  * @param attributeId - Attribute UUID
@@ -8333,20 +8900,34 @@ var ObjectSchemaService = class extends BaseService {
8333
8900
  if (!dbAttr) {
8334
8901
  throw new Error(`Attribute with id "${attributeId}" not found`);
8335
8902
  }
8336
- if (dbAttr.system) {
8337
- throw new Error(
8338
- `Cannot modify system attribute "${dbAttr.name}". System attributes are protected.`
8339
- );
8340
- }
8341
- if (updates.name && updates.name !== dbAttr.name) {
8342
- throw new Error(
8343
- "Attribute name cannot be changed after creation. Create a new attribute instead."
8344
- );
8903
+ const requestedKeys = Object.keys(updates);
8904
+ const identityChanges = requestedKeys.filter(
8905
+ (k) => IDENTITY_PROPERTIES.includes(k)
8906
+ );
8907
+ if (identityChanges.length > 0) {
8908
+ const actualChanges = identityChanges.filter((k) => {
8909
+ const key = k;
8910
+ return updates[key] !== void 0 && updates[key] !== dbAttr[key];
8911
+ });
8912
+ if (actualChanges.length > 0) {
8913
+ throw new Error(
8914
+ `Cannot modify identity properties: ${actualChanges.join(", ")}. These properties cannot be changed after creation.`
8915
+ );
8916
+ }
8345
8917
  }
8346
- if (updates.type && updates.type !== dbAttr.type) {
8347
- throw new Error(
8348
- "Attribute type cannot be changed after creation. Create a new attribute instead."
8918
+ if (dbAttr.system) {
8919
+ const behaviorChanges = requestedKeys.filter(
8920
+ (k) => BEHAVIOR_PROPERTIES.includes(k)
8349
8921
  );
8922
+ const actualBehaviorChanges = behaviorChanges.filter((k) => {
8923
+ const key = k;
8924
+ return updates[key] !== void 0;
8925
+ });
8926
+ if (actualBehaviorChanges.length > 0) {
8927
+ throw new Error(
8928
+ `Cannot modify behavior properties on system attribute "${dbAttr.name}": ${actualBehaviorChanges.join(", ")}. Only presentation properties (${PRESENTATION_PROPERTIES.join(", ")}) are editable.`
8929
+ );
8930
+ }
8350
8931
  }
8351
8932
  const mergedInput = {
8352
8933
  name: dbAttr.name,
@@ -8379,7 +8960,7 @@ var ObjectSchemaService = class extends BaseService {
8379
8960
  resourceType: "attribute",
8380
8961
  resourceId: attributeId,
8381
8962
  resourceLabel: updatedDbAttr.label,
8382
- objectName: _optionalChain([dbObject, 'optionalAccess', _177 => _177.name]),
8963
+ objectName: _optionalChain([dbObject, 'optionalAccess', _176 => _176.name]),
8383
8964
  objectId: dbAttr.objectId,
8384
8965
  changes
8385
8966
  });
@@ -8412,7 +8993,7 @@ var ObjectSchemaService = class extends BaseService {
8412
8993
  );
8413
8994
  }
8414
8995
  const dbObject = await this.adapter.objects.findById(dbAttr.objectId);
8415
- if (_optionalChain([dbObject, 'optionalAccess', _178 => _178.labelExpression])) {
8996
+ if (_optionalChain([dbObject, 'optionalAccess', _177 => _177.labelExpression])) {
8416
8997
  const usedAttributes = extractAttributeNames(dbObject.labelExpression);
8417
8998
  if (usedAttributes.includes(dbAttr.name)) {
8418
8999
  throw new AttributeInUseError(dbAttr.name, "labelExpression");
@@ -8428,7 +9009,7 @@ var ObjectSchemaService = class extends BaseService {
8428
9009
  resourceType: "attribute",
8429
9010
  resourceId: attributeId,
8430
9011
  resourceLabel: dbAttr.label,
8431
- objectName: _optionalChain([dbObject, 'optionalAccess', _179 => _179.name]),
9012
+ objectName: _optionalChain([dbObject, 'optionalAccess', _178 => _178.name]),
8432
9013
  objectId: dbAttr.objectId
8433
9014
  });
8434
9015
  }
@@ -8443,9 +9024,9 @@ var ObjectSchemaService = class extends BaseService {
8443
9024
  async listAttributes(objectId, options) {
8444
9025
  const dbAttributes = await this.adapter.attributes.findByObjectId(objectId);
8445
9026
  let filtered = dbAttributes;
8446
- if (_optionalChain([options, 'optionalAccess', _180 => _180.systemOnly])) {
9027
+ if (_optionalChain([options, 'optionalAccess', _179 => _179.systemOnly])) {
8447
9028
  filtered = dbAttributes.filter((attr) => attr.system);
8448
- } else if (_optionalChain([options, 'optionalAccess', _181 => _181.customOnly])) {
9029
+ } else if (_optionalChain([options, 'optionalAccess', _180 => _180.customOnly])) {
8449
9030
  filtered = dbAttributes.filter((attr) => !attr.system);
8450
9031
  }
8451
9032
  return filtered.map((attr) => this.convertDBAttributeToAttribute(attr));
@@ -8481,14 +9062,14 @@ var ObjectSchemaService = class extends BaseService {
8481
9062
  pluralLabel: dbObject.pluralLabel,
8482
9063
  description: dbObject.description,
8483
9064
  labelExpression: dbObject.labelExpression,
8484
- icon: _optionalChain([dbObject, 'access', _182 => _182.metadata, 'optionalAccess', _183 => _183.icon])
9065
+ icon: _optionalChain([dbObject, 'access', _181 => _181.metadata, 'optionalAccess', _182 => _182.icon])
8485
9066
  };
8486
9067
  let metadata = dbObject.metadata;
8487
9068
  if (updates.icon !== void 0 || updates.metadata !== void 0) {
8488
9069
  metadata = {
8489
9070
  ...dbObject.metadata,
8490
9071
  ...updates.metadata,
8491
- icon: _nullishCoalesce(updates.icon, () => ( _optionalChain([dbObject, 'access', _184 => _184.metadata, 'optionalAccess', _185 => _185.icon])))
9072
+ icon: _nullishCoalesce(updates.icon, () => ( _optionalChain([dbObject, 'access', _183 => _183.metadata, 'optionalAccess', _184 => _184.icon])))
8492
9073
  };
8493
9074
  }
8494
9075
  const updatedDbObject = await this.adapter.objects.update(objectId, {
@@ -8768,7 +9349,7 @@ Reserved names: ${RESERVED_ATTRIBUTE_NAMES.join(", ")}`
8768
9349
  label: dbObject.label,
8769
9350
  pluralLabel: dbObject.pluralLabel,
8770
9351
  description: dbObject.description,
8771
- icon: _optionalChain([dbObject, 'access', _186 => _186.metadata, 'optionalAccess', _187 => _187.icon]),
9352
+ icon: _optionalChain([dbObject, 'access', _185 => _185.metadata, 'optionalAccess', _186 => _186.icon]),
8772
9353
  labelExpression: dbObject.labelExpression,
8773
9354
  attributes,
8774
9355
  system: dbObject.system,
@@ -8868,7 +9449,7 @@ Reserved names: ${RESERVED_ATTRIBUTE_NAMES.join(", ")}`
8868
9449
  const hasRelationToTarget = attrs.some((attr) => {
8869
9450
  if (attr.type !== "relation") return false;
8870
9451
  const config = attr.config;
8871
- return _nullishCoalesce(_optionalChain([config, 'optionalAccess', _188 => _188.targets, 'optionalAccess', _189 => _189.some, 'call', _190 => _190((t) => t.object === targetObjectName)]), () => ( false));
9452
+ return _nullishCoalesce(_optionalChain([config, 'optionalAccess', _187 => _187.targets, 'optionalAccess', _188 => _188.some, 'call', _189 => _189((t) => t.object === targetObjectName)]), () => ( false));
8872
9453
  });
8873
9454
  if (hasRelationToTarget) {
8874
9455
  referencing.push(obj.name);
@@ -8946,7 +9527,7 @@ Native objects must have system=true. Did you forget to call .system() in your b
8946
9527
  const existing = this.objects.get(object2.name);
8947
9528
  throw new Error(
8948
9529
  `[NativeObjectRegistry] Duplicate object name "${object2.name}":
8949
- - Existing: "${_optionalChain([existing, 'optionalAccess', _191 => _191.label])}" (id: ${_optionalChain([existing, 'optionalAccess', _192 => _192.id])})
9530
+ - Existing: "${_optionalChain([existing, 'optionalAccess', _190 => _190.label])}" (id: ${_optionalChain([existing, 'optionalAccess', _191 => _191.id])})
8950
9531
  - New: "${object2.label}" (id: ${object2.id})
8951
9532
  Please use unique names for each native object.`
8952
9533
  );
@@ -9063,7 +9644,7 @@ var AuditService = class extends BaseService {
9063
9644
  this.isFlushing = false;
9064
9645
  /** Pending flush promise to allow waiting on concurrent flush */
9065
9646
  this.flushPromise = null;
9066
- if (_optionalChain([options, 'optionalAccess', _193 => _193.async]) && options.flushIntervalMs) {
9647
+ if (_optionalChain([options, 'optionalAccess', _192 => _192.async]) && options.flushIntervalMs) {
9067
9648
  this.startFlushTimer();
9068
9649
  }
9069
9650
  }
@@ -9260,7 +9841,7 @@ var AuditService = class extends BaseService {
9260
9841
  if (!this.adapter.audit) {
9261
9842
  return;
9262
9843
  }
9263
- if (_optionalChain([this, 'access', _194 => _194.options, 'optionalAccess', _195 => _195.async])) {
9844
+ if (_optionalChain([this, 'access', _193 => _193.options, 'optionalAccess', _194 => _194.async])) {
9264
9845
  this.buffer.push(entry);
9265
9846
  const batchSize = _nullishCoalesce(this.options.batchSize, () => ( 10));
9266
9847
  if (this.buffer.length >= batchSize) {
@@ -9274,7 +9855,7 @@ var AuditService = class extends BaseService {
9274
9855
  * Start the flush timer for async mode
9275
9856
  */
9276
9857
  startFlushTimer() {
9277
- const intervalMs = _nullishCoalesce(_optionalChain([this, 'access', _196 => _196.options, 'optionalAccess', _197 => _197.flushIntervalMs]), () => ( 1e3));
9858
+ const intervalMs = _nullishCoalesce(_optionalChain([this, 'access', _195 => _195.options, 'optionalAccess', _196 => _196.flushIntervalMs]), () => ( 1e3));
9278
9859
  this.flushTimer = setInterval(() => {
9279
9860
  this.flush().catch(() => {
9280
9861
  });
@@ -9382,7 +9963,7 @@ var UserService = class extends BaseService {
9382
9963
  if (roleErrors.length > 0) {
9383
9964
  errors.push({
9384
9965
  attribute: attrName,
9385
- message: `Users do not have required role for ${attr.label}. Allowed roles: ${_optionalChain([attr, 'access', _198 => _198.allowedRoles, 'optionalAccess', _199 => _199.join, 'call', _200 => _200(", ")])}`,
9966
+ message: `Users do not have required role for ${attr.label}. Allowed roles: ${_optionalChain([attr, 'access', _197 => _197.allowedRoles, 'optionalAccess', _198 => _198.join, 'call', _199 => _199(", ")])}`,
9386
9967
  invalidIds: roleErrors
9387
9968
  });
9388
9969
  }
@@ -9704,7 +10285,7 @@ var RecordQueryService = class extends BaseService {
9704
10285
  super(adapter);
9705
10286
  this.schemaService = schemaService;
9706
10287
  this.options = options;
9707
- this.policyRegistry = _optionalChain([options, 'optionalAccess', _201 => _201.policyRegistry]) === null ? null : _nullishCoalesce(_optionalChain([options, 'optionalAccess', _202 => _202.policyRegistry]), () => ( defaultPolicyRegistry));
10288
+ this.policyRegistry = _optionalChain([options, 'optionalAccess', _200 => _200.policyRegistry]) === null ? null : _nullishCoalesce(_optionalChain([options, 'optionalAccess', _201 => _201.policyRegistry]), () => ( defaultPolicyRegistry));
9708
10289
  }
9709
10290
  // ============================================================================
9710
10291
  // LIST
@@ -9754,12 +10335,12 @@ var RecordQueryService = class extends BaseService {
9754
10335
  * Internal list query execution
9755
10336
  */
9756
10337
  async executeListQuery(schema, objectId, options) {
9757
- if (_optionalChain([this, 'access', _203 => _203.options, 'optionalAccess', _204 => _204.permissionService]) && this.userId) {
10338
+ if (_optionalChain([this, 'access', _202 => _202.options, 'optionalAccess', _203 => _203.permissionService]) && this.userId) {
9758
10339
  await checkPermission(this.options.permissionService, this.userId, schema.name, "read");
9759
10340
  }
9760
- const policy = _optionalChain([options, 'optionalAccess', _205 => _205.skipPolicyFilter]) ? void 0 : getPolicy(this.policyRegistry, this.userId, schema.name);
10341
+ const policy = _optionalChain([options, 'optionalAccess', _204 => _204.skipPolicyFilter]) ? void 0 : getPolicy(this.policyRegistry, this.userId, schema.name);
9761
10342
  let effectiveOptions = options;
9762
- if (_optionalChain([policy, 'optionalAccess', _206 => _206.applyListFilter]) && this.userId) {
10343
+ if (_optionalChain([policy, 'optionalAccess', _205 => _205.applyListFilter]) && this.userId) {
9763
10344
  const ctx = buildPolicyContext(schema.name, this.userId, this.tenantId);
9764
10345
  effectiveOptions = policy.applyListFilter(ctx, options);
9765
10346
  }
@@ -9769,10 +10350,10 @@ var RecordQueryService = class extends BaseService {
9769
10350
  );
9770
10351
  let filteredRecords = result.records;
9771
10352
  let effectiveTotal = result.total;
9772
- if (_optionalChain([policy, 'optionalAccess', _207 => _207.canAccessRecord]) && this.userId) {
10353
+ if (_optionalChain([policy, 'optionalAccess', _206 => _206.canAccessRecord]) && this.userId) {
9773
10354
  const ctx = buildPolicyContext(schema.name, this.userId, this.tenantId);
9774
- const requestedLimit = _nullishCoalesce(_optionalChain([effectiveOptions, 'optionalAccess', _208 => _208.limit]), () => ( 20));
9775
- const requestedOffset = _nullishCoalesce(_optionalChain([effectiveOptions, 'optionalAccess', _209 => _209.offset]), () => ( 0));
10355
+ const requestedLimit = _nullishCoalesce(_optionalChain([effectiveOptions, 'optionalAccess', _207 => _207.limit]), () => ( 20));
10356
+ const requestedOffset = _nullishCoalesce(_optionalChain([effectiveOptions, 'optionalAccess', _208 => _208.offset]), () => ( 0));
9776
10357
  const overfetchMultiplier = 5;
9777
10358
  const batchSize = requestedLimit * overfetchMultiplier;
9778
10359
  const maxScanRecords = 1e4;
@@ -9794,7 +10375,7 @@ var RecordQueryService = class extends BaseService {
9794
10375
  exhausted = true;
9795
10376
  break;
9796
10377
  }
9797
- const filtered = batch.records.filter((record) => _optionalChain([policy, 'access', _210 => _210.canAccessRecord, 'optionalCall', _211 => _211(ctx, record)]));
10378
+ const filtered = batch.records.filter((record) => _optionalChain([policy, 'access', _209 => _209.canAccessRecord, 'optionalCall', _210 => _210(ctx, record)]));
9798
10379
  collected.push(...filtered);
9799
10380
  dbOffset += batch.records.length;
9800
10381
  totalScanned += batch.records.length;
@@ -9806,7 +10387,7 @@ var RecordQueryService = class extends BaseService {
9806
10387
  effectiveTotal = exhausted ? collected.length : Math.max(collected.length, result.total);
9807
10388
  filteredRecords = collected.slice(requestedOffset, requestedOffset + requestedLimit);
9808
10389
  }
9809
- if (!_optionalChain([options, 'optionalAccess', _212 => _212.skipFormulas])) {
10390
+ if (!_optionalChain([options, 'optionalAccess', _211 => _211.skipFormulas])) {
9810
10391
  return {
9811
10392
  records: enrichRecordsWithFormulas(filteredRecords, schema),
9812
10393
  total: effectiveTotal
@@ -9866,14 +10447,14 @@ var RecordQueryService = class extends BaseService {
9866
10447
  * Internal search query execution
9867
10448
  */
9868
10449
  async executeSearchQuery(schema, objectId, query, options) {
9869
- if (_optionalChain([this, 'access', _213 => _213.options, 'optionalAccess', _214 => _214.permissionService]) && this.userId) {
10450
+ if (_optionalChain([this, 'access', _212 => _212.options, 'optionalAccess', _213 => _213.permissionService]) && this.userId) {
9870
10451
  await checkPermission(this.options.permissionService, this.userId, schema.name, "read");
9871
10452
  }
9872
10453
  const result = await runWithSchemaContext(
9873
10454
  [schema],
9874
10455
  () => this.adapter.objectRecords.search(objectId, query, options)
9875
10456
  );
9876
- if (!_optionalChain([options, 'optionalAccess', _215 => _215.skipFormulas])) {
10457
+ if (!_optionalChain([options, 'optionalAccess', _214 => _214.skipFormulas])) {
9877
10458
  return {
9878
10459
  records: enrichRecordsWithFormulas(result.records, schema),
9879
10460
  total: result.total
@@ -10052,7 +10633,7 @@ var RelationService = class extends BaseService {
10052
10633
  }
10053
10634
  const isUniversal = attr.targets.length === 1 && attr.targets[0].object === RELATION_TARGET_ANY;
10054
10635
  const validObjectIds = isUniversal ? null : await this.getValidObjectIds(attr.targets);
10055
- if (!isUniversal && _optionalChain([validObjectIds, 'optionalAccess', _216 => _216.size]) === 0) {
10636
+ if (!isUniversal && _optionalChain([validObjectIds, 'optionalAccess', _215 => _215.size]) === 0) {
10056
10637
  errors.push({
10057
10638
  attribute: attr.name,
10058
10639
  message: `No valid target objects found for ${attr.label}`
@@ -10105,10 +10686,10 @@ var RelationService = class extends BaseService {
10105
10686
  for (const target of targets) {
10106
10687
  try {
10107
10688
  const objectSchema = await this.schemaService.getObjectSchemaByName(target.object);
10108
- if (_optionalChain([objectSchema, 'optionalAccess', _217 => _217.id])) {
10689
+ if (_optionalChain([objectSchema, 'optionalAccess', _216 => _216.id])) {
10109
10690
  objectIds.add(objectSchema.id);
10110
10691
  }
10111
- } catch (e10) {
10692
+ } catch (e12) {
10112
10693
  }
10113
10694
  }
10114
10695
  return objectIds;
@@ -10174,7 +10755,7 @@ var RelationService = class extends BaseService {
10174
10755
  const targetResults = await Promise.all(
10175
10756
  filteredTargets.map(async (target) => {
10176
10757
  const objectSchema = await this.schemaService.getObjectSchemaByName(target.object);
10177
- if (!_optionalChain([objectSchema, 'optionalAccess', _218 => _218.id])) return { options: [], total: 0 };
10758
+ if (!_optionalChain([objectSchema, 'optionalAccess', _217 => _217.id])) return { options: [], total: 0 };
10178
10759
  const objectId = objectSchema.id;
10179
10760
  const result = query ? await queryService.searchRecords(objectId, query, queryOptions) : await queryService.listRecords(objectId, queryOptions);
10180
10761
  const options = await Promise.all(
@@ -10329,8 +10910,8 @@ var RelationService = class extends BaseService {
10329
10910
  continue;
10330
10911
  }
10331
10912
  const attribute = attributeMap.get(attributeId);
10332
- const targetConfig = _optionalChain([attribute, 'optionalAccess', _219 => _219.targets, 'optionalAccess', _220 => _220.find, 'call', _221 => _221((t) => t.object === objectSchema.name)]);
10333
- const customTemplate = _optionalChain([targetConfig, 'optionalAccess', _222 => _222.displayTemplate]);
10913
+ const targetConfig = _optionalChain([attribute, 'optionalAccess', _218 => _218.targets, 'optionalAccess', _219 => _219.find, 'call', _220 => _220((t) => t.object === objectSchema.name)]);
10914
+ const customTemplate = _optionalChain([targetConfig, 'optionalAccess', _221 => _221.displayTemplate]);
10334
10915
  const label = await this.resolveLabel(record, objectSchema, customTemplate);
10335
10916
  resolved.push({
10336
10917
  _compositeId: compositeId,
@@ -10480,14 +11061,14 @@ var RollupService = class extends BaseService {
10480
11061
  const sourceSchema = getSchemaByNameFromContext(sourceObjectName);
10481
11062
  let sourceObjectId;
10482
11063
  let reverseRelationAttrName;
10483
- if (_optionalChain([sourceSchema, 'optionalAccess', _223 => _223.id])) {
11064
+ if (_optionalChain([sourceSchema, 'optionalAccess', _222 => _222.id])) {
10484
11065
  sourceObjectId = sourceSchema.id;
10485
11066
  const reverseRelationAttr = sourceSchema.attributes.find((attr) => {
10486
11067
  if (attr.type !== "relation") return false;
10487
11068
  const relationConfig = attr;
10488
- return _optionalChain([relationConfig, 'optionalAccess', _224 => _224.targets, 'optionalAccess', _225 => _225.some, 'call', _226 => _226((t) => t.object === schema.name)]);
11069
+ return _optionalChain([relationConfig, 'optionalAccess', _223 => _223.targets, 'optionalAccess', _224 => _224.some, 'call', _225 => _225((t) => t.object === schema.name)]);
10489
11070
  });
10490
- reverseRelationAttrName = _optionalChain([reverseRelationAttr, 'optionalAccess', _227 => _227.name]);
11071
+ reverseRelationAttrName = _optionalChain([reverseRelationAttr, 'optionalAccess', _226 => _226.name]);
10491
11072
  } else {
10492
11073
  const sourceObject = await this.adapter.objects.findByName(sourceObjectName);
10493
11074
  if (!sourceObject) {
@@ -10498,9 +11079,9 @@ var RollupService = class extends BaseService {
10498
11079
  const reverseRelationAttr = sourceAttributes.find((attr) => {
10499
11080
  if (attr.type !== "relation") return false;
10500
11081
  const relationConfig = attr.config;
10501
- return _optionalChain([relationConfig, 'optionalAccess', _228 => _228.targets, 'optionalAccess', _229 => _229.some, 'call', _230 => _230((t) => t.object === schema.name)]);
11082
+ return _optionalChain([relationConfig, 'optionalAccess', _227 => _227.targets, 'optionalAccess', _228 => _228.some, 'call', _229 => _229((t) => t.object === schema.name)]);
10502
11083
  });
10503
- reverseRelationAttrName = _optionalChain([reverseRelationAttr, 'optionalAccess', _231 => _231.name]);
11084
+ reverseRelationAttrName = _optionalChain([reverseRelationAttr, 'optionalAccess', _230 => _230.name]);
10504
11085
  }
10505
11086
  if (!reverseRelationAttrName) {
10506
11087
  return { value: null, recordCount: 0 };
@@ -10753,13 +11334,13 @@ var RollupService = class extends BaseService {
10753
11334
  if (!obj) continue;
10754
11335
  for (const rollupDbAttr of rollupAttrs) {
10755
11336
  const rollupConfig = rollupDbAttr.config;
10756
- if (!_optionalChain([rollupConfig, 'optionalAccess', _232 => _232.relationAttribute])) continue;
11337
+ if (!_optionalChain([rollupConfig, 'optionalAccess', _231 => _231.relationAttribute])) continue;
10757
11338
  const relationAttr = attributes.find(
10758
11339
  (a) => a.type === "relation" && a.name === rollupConfig.relationAttribute
10759
11340
  );
10760
11341
  if (!relationAttr) continue;
10761
11342
  const relationConfig = relationAttr.config;
10762
- const targetsChangedObject = _optionalChain([relationConfig, 'optionalAccess', _233 => _233.targets, 'optionalAccess', _234 => _234.some, 'call', _235 => _235(
11343
+ const targetsChangedObject = _optionalChain([relationConfig, 'optionalAccess', _232 => _232.targets, 'optionalAccess', _233 => _233.some, 'call', _234 => _234(
10763
11344
  (t) => t.object === changedSchema.name
10764
11345
  )]);
10765
11346
  if (!targetsChangedObject) continue;
@@ -10784,11 +11365,11 @@ var RecordService = class extends BaseService {
10784
11365
  constructor(adapter, options) {
10785
11366
  super(adapter);
10786
11367
  this.schemaService = new ObjectSchemaService(adapter, registry, {
10787
- auditService: _optionalChain([options, 'optionalAccess', _236 => _236.auditService])
11368
+ auditService: _optionalChain([options, 'optionalAccess', _235 => _235.auditService])
10788
11369
  });
10789
- this.permissionService = _optionalChain([options, 'optionalAccess', _237 => _237.permissionService]);
10790
- this.auditService = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _238 => _238.auditService]), () => ( (adapter.audit ? new AuditService(adapter) : void 0)));
10791
- this.policyRegistry = _optionalChain([options, 'optionalAccess', _239 => _239.policyRegistry]) === null ? null : _nullishCoalesce(_optionalChain([options, 'optionalAccess', _240 => _240.policyRegistry]), () => ( defaultPolicyRegistry));
11370
+ this.permissionService = _optionalChain([options, 'optionalAccess', _236 => _236.permissionService]);
11371
+ this.auditService = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _237 => _237.auditService]), () => ( (adapter.audit ? new AuditService(adapter) : void 0)));
11372
+ this.policyRegistry = _optionalChain([options, 'optionalAccess', _238 => _238.policyRegistry]) === null ? null : _nullishCoalesce(_optionalChain([options, 'optionalAccess', _239 => _239.policyRegistry]), () => ( defaultPolicyRegistry));
10792
11373
  this.recordResolver = new RecordResolverService(adapter);
10793
11374
  this.queryService = new RecordQueryService(adapter, this.schemaService, {
10794
11375
  permissionService: this.permissionService,
@@ -10802,7 +11383,7 @@ var RecordService = class extends BaseService {
10802
11383
  recordResolver: this.recordResolver
10803
11384
  });
10804
11385
  this.userService = new UserService(adapter);
10805
- this.hookRegistry = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _241 => _241.hookRegistry]), () => ( new NoopHookRegistry()));
11386
+ this.hookRegistry = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _240 => _240.hookRegistry]), () => ( new NoopHookRegistry()));
10806
11387
  this.labelResolver = this.recordResolver.createLabelResolver(this.relationService);
10807
11388
  this.rollupContext = this.recordResolver.createRollupContext(
10808
11389
  this.rollupService,
@@ -10837,21 +11418,21 @@ var RecordService = class extends BaseService {
10837
11418
  schema,
10838
11419
  this.tenantId,
10839
11420
  dataWithDefaults,
10840
- _optionalChain([options, 'optionalAccess', _242 => _242.hookMetadata])
11421
+ _optionalChain([options, 'optionalAccess', _241 => _241.hookMetadata])
10841
11422
  );
10842
- if (!_optionalChain([options, 'optionalAccess', _243 => _243.skipHooks])) {
11423
+ if (!_optionalChain([options, 'optionalAccess', _242 => _242.skipHooks])) {
10843
11424
  await this.hookRegistry.execute("beforeCreate", schema.name, hookCtx);
10844
11425
  }
10845
- if (_optionalChain([options, 'optionalAccess', _244 => _244.validate]) !== false) {
10846
- if (_optionalChain([options, 'optionalAccess', _245 => _245.allowDraft])) {
11426
+ if (_optionalChain([options, 'optionalAccess', _243 => _243.validate]) !== false) {
11427
+ if (_optionalChain([options, 'optionalAccess', _244 => _244.allowDraft])) {
10847
11428
  validateDraftOrThrow(schema, dataWithDefaults);
10848
11429
  } else {
10849
11430
  validateObjectOrThrow(schema, dataWithDefaults);
10850
11431
  }
10851
- if (!_optionalChain([options, 'optionalAccess', _246 => _246.skipRelationValidation])) {
11432
+ if (!_optionalChain([options, 'optionalAccess', _245 => _245.skipRelationValidation])) {
10852
11433
  await this.relationService.validateRelationsOrThrow(schema, dataWithDefaults);
10853
11434
  }
10854
- if (!_optionalChain([options, 'optionalAccess', _247 => _247.skipUserValidation])) {
11435
+ if (!_optionalChain([options, 'optionalAccess', _246 => _246.skipUserValidation])) {
10855
11436
  await this.userService.validateUsersOrThrow(schema, dataWithDefaults);
10856
11437
  }
10857
11438
  }
@@ -10862,10 +11443,10 @@ var RecordService = class extends BaseService {
10862
11443
  data: dataWithDefaults,
10863
11444
  label,
10864
11445
  completionStatus,
10865
- metadata: _optionalChain([options, 'optionalAccess', _248 => _248.metadata]),
11446
+ metadata: _optionalChain([options, 'optionalAccess', _247 => _247.metadata]),
10866
11447
  createdBy: this.userId
10867
11448
  });
10868
- if (!_optionalChain([options, 'optionalAccess', _249 => _249.skipHooks])) {
11449
+ if (!_optionalChain([options, 'optionalAccess', _248 => _248.skipHooks])) {
10869
11450
  const afterCtx = {
10870
11451
  ...hookCtx,
10871
11452
  recordId: record.id,
@@ -10883,7 +11464,7 @@ var RecordService = class extends BaseService {
10883
11464
  objectId: schema.id,
10884
11465
  recordId: record.id,
10885
11466
  recordLabel: record.label,
10886
- metadata: _optionalChain([options, 'optionalAccess', _250 => _250.hookMetadata])
11467
+ metadata: _optionalChain([options, 'optionalAccess', _249 => _249.hookMetadata])
10887
11468
  }).catch((err) => {
10888
11469
  console.error(
10889
11470
  "Audit log failed (record.created):",
@@ -10909,7 +11490,7 @@ var RecordService = class extends BaseService {
10909
11490
  return null;
10910
11491
  }
10911
11492
  const schema = await this.schemaService.getObjectSchema(record.objectId);
10912
- if (!_optionalChain([options, 'optionalAccess', _251 => _251.skipPolicyCheck])) {
11493
+ if (!_optionalChain([options, 'optionalAccess', _250 => _250.skipPolicyCheck])) {
10913
11494
  const policy = getPolicy(this.policyRegistry, this.userId, schema.name);
10914
11495
  if (policy) {
10915
11496
  const ctx = buildPolicyContext(schema.name, this.userId, this.tenantId);
@@ -10919,10 +11500,10 @@ var RecordService = class extends BaseService {
10919
11500
  }
10920
11501
  }
10921
11502
  let enrichedRecord = record;
10922
- if (!_optionalChain([options, 'optionalAccess', _252 => _252.skipFormulas])) {
11503
+ if (!_optionalChain([options, 'optionalAccess', _251 => _251.skipFormulas])) {
10923
11504
  enrichedRecord = enrichWithFormulas(record, schema);
10924
11505
  }
10925
- if (_optionalChain([options, 'optionalAccess', _253 => _253.includeSchema])) {
11506
+ if (_optionalChain([options, 'optionalAccess', _252 => _252.includeSchema])) {
10926
11507
  const recordWithSchema = enrichedRecord;
10927
11508
  recordWithSchema.schema = schema;
10928
11509
  return recordWithSchema;
@@ -10972,7 +11553,7 @@ var RecordService = class extends BaseService {
10972
11553
  if (oldVal !== null && newVal !== null && typeof oldVal === "object" && typeof newVal === "object") {
10973
11554
  try {
10974
11555
  return JSON.stringify(oldVal) !== JSON.stringify(newVal);
10975
- } catch (e11) {
11556
+ } catch (e13) {
10976
11557
  return true;
10977
11558
  }
10978
11559
  }
@@ -10984,9 +11565,9 @@ var RecordService = class extends BaseService {
10984
11565
  existing,
10985
11566
  mergedData,
10986
11567
  changedAttributes,
10987
- _optionalChain([options, 'optionalAccess', _254 => _254.hookMetadata])
11568
+ _optionalChain([options, 'optionalAccess', _253 => _253.hookMetadata])
10988
11569
  );
10989
- if (!_optionalChain([options, 'optionalAccess', _255 => _255.skipHooks])) {
11570
+ if (!_optionalChain([options, 'optionalAccess', _254 => _254.skipHooks])) {
10990
11571
  await this.hookRegistry.execute("beforeUpdate", schema.name, hookCtx);
10991
11572
  }
10992
11573
  const hookModifiedValues = {};
@@ -10995,19 +11576,19 @@ var RecordService = class extends BaseService {
10995
11576
  hookModifiedValues[key] = hookCtx.newValues[key];
10996
11577
  }
10997
11578
  }
10998
- if (_optionalChain([options, 'optionalAccess', _256 => _256.validate]) !== false) {
10999
- if (_optionalChain([options, 'optionalAccess', _257 => _257.partial])) {
11579
+ if (_optionalChain([options, 'optionalAccess', _255 => _255.validate]) !== false) {
11580
+ if (_optionalChain([options, 'optionalAccess', _256 => _256.partial])) {
11000
11581
  validateDraftOrThrow(schema, mergedData);
11001
11582
  } else {
11002
11583
  validateObjectOrThrow(schema, mergedData);
11003
11584
  }
11004
- if (!_optionalChain([options, 'optionalAccess', _258 => _258.skipRelationValidation])) {
11585
+ if (!_optionalChain([options, 'optionalAccess', _257 => _257.skipRelationValidation])) {
11005
11586
  await this.relationService.validateRelationsOrThrow(schema, {
11006
11587
  ...data,
11007
11588
  ...hookModifiedValues
11008
11589
  });
11009
11590
  }
11010
- if (!_optionalChain([options, 'optionalAccess', _259 => _259.skipUserValidation])) {
11591
+ if (!_optionalChain([options, 'optionalAccess', _258 => _258.skipUserValidation])) {
11011
11592
  await this.userService.validateUsersOrThrow(schema, {
11012
11593
  ...data,
11013
11594
  ...hookModifiedValues
@@ -11024,7 +11605,7 @@ var RecordService = class extends BaseService {
11024
11605
  __lastUpdatedBy: this.userId,
11025
11606
  __expectedUpdatedAt: existing.updatedAt instanceof Date ? existing.updatedAt.toISOString() : existing.updatedAt
11026
11607
  };
11027
- if (_optionalChain([options, 'optionalAccess', _260 => _260.metadata]) !== void 0) {
11608
+ if (_optionalChain([options, 'optionalAccess', _259 => _259.metadata]) !== void 0) {
11028
11609
  const existingMetadata = _nullishCoalesce(existing.metadata, () => ( {}));
11029
11610
  const mergedMetadata = { ...existingMetadata, ...options.metadata };
11030
11611
  const cleanedMetadata = Object.fromEntries(
@@ -11034,7 +11615,7 @@ var RecordService = class extends BaseService {
11034
11615
  }
11035
11616
  const updated = await this.adapter.objectRecords.update(recordId, updatePayload);
11036
11617
  await this.invalidateRecordCaches(recordId, existing.objectId);
11037
- if (!_optionalChain([options, 'optionalAccess', _261 => _261.skipHooks])) {
11618
+ if (!_optionalChain([options, 'optionalAccess', _260 => _260.skipHooks])) {
11038
11619
  const afterCtx = {
11039
11620
  ...hookCtx,
11040
11621
  record: updated
@@ -11049,7 +11630,7 @@ var RecordService = class extends BaseService {
11049
11630
  if (this.auditService && this.userId && allChangedAttributes.length > 0) {
11050
11631
  const changes = allChangedAttributes.map((attr) => ({
11051
11632
  field: attr,
11052
- oldValue: _optionalChain([hookCtx, 'access', _262 => _262.oldValues, 'optionalAccess', _263 => _263[attr]]),
11633
+ oldValue: _optionalChain([hookCtx, 'access', _261 => _261.oldValues, 'optionalAccess', _262 => _262[attr]]),
11053
11634
  newValue: hookCtx.newValues[attr]
11054
11635
  }));
11055
11636
  this.auditService.logRecordAction({
@@ -11060,7 +11641,7 @@ var RecordService = class extends BaseService {
11060
11641
  recordId: updated.id,
11061
11642
  recordLabel: updated.label,
11062
11643
  changes,
11063
- metadata: _optionalChain([options, 'optionalAccess', _264 => _264.hookMetadata])
11644
+ metadata: _optionalChain([options, 'optionalAccess', _263 => _263.hookMetadata])
11064
11645
  }).catch((err) => {
11065
11646
  console.error(
11066
11647
  "Audit log failed (record.updated):",
@@ -11095,22 +11676,22 @@ var RecordService = class extends BaseService {
11095
11676
  const ctx = buildPolicyContext(schema.name, this.userId, this.tenantId);
11096
11677
  checkRecordDeleteOrThrow(policy, record, ctx);
11097
11678
  }
11098
- if (_optionalChain([options, 'optionalAccess', _265 => _265.checkSystem]) && schema.system) {
11679
+ if (_optionalChain([options, 'optionalAccess', _264 => _264.checkSystem]) && schema.system) {
11099
11680
  throw new ProtectedResourceError("object", schema.name, "delete");
11100
11681
  }
11101
- if (!_optionalChain([options, 'optionalAccess', _266 => _266.skipReferenceCheck])) {
11682
+ if (!_optionalChain([options, 'optionalAccess', _265 => _265.skipReferenceCheck])) {
11102
11683
  const references = await this.adapter.objectRecords.countRecordsReferencingId(recordId);
11103
11684
  if (references.length > 0) {
11104
11685
  throw new RecordReferencedError(recordId, references);
11105
11686
  }
11106
11687
  }
11107
- const hookCtx = createContextForDelete(schema, this.tenantId, record, _optionalChain([options, 'optionalAccess', _267 => _267.hookMetadata]));
11108
- if (!_optionalChain([options, 'optionalAccess', _268 => _268.skipHooks])) {
11688
+ const hookCtx = createContextForDelete(schema, this.tenantId, record, _optionalChain([options, 'optionalAccess', _266 => _266.hookMetadata]));
11689
+ if (!_optionalChain([options, 'optionalAccess', _267 => _267.skipHooks])) {
11109
11690
  await this.hookRegistry.execute("beforeDelete", schema.name, hookCtx);
11110
11691
  }
11111
11692
  await this.adapter.objectRecords.delete(recordId);
11112
11693
  await this.invalidateRecordCaches(recordId, record.objectId);
11113
- if (!_optionalChain([options, 'optionalAccess', _269 => _269.skipHooks])) {
11694
+ if (!_optionalChain([options, 'optionalAccess', _268 => _268.skipHooks])) {
11114
11695
  await this.hookRegistry.execute("afterDelete", schema.name, hookCtx);
11115
11696
  }
11116
11697
  await recalculateParentRollups(record, schema, this.rollupContext);
@@ -11122,7 +11703,7 @@ var RecordService = class extends BaseService {
11122
11703
  objectId: schema.id,
11123
11704
  recordId: record.id,
11124
11705
  recordLabel: record.label,
11125
- metadata: _optionalChain([options, 'optionalAccess', _270 => _270.hookMetadata])
11706
+ metadata: _optionalChain([options, 'optionalAccess', _269 => _269.hookMetadata])
11126
11707
  }).catch((err) => {
11127
11708
  console.error(
11128
11709
  "Audit log failed (record.deleted):",
@@ -11165,13 +11746,13 @@ var RecordService = class extends BaseService {
11165
11746
  this.tenantId
11166
11747
  );
11167
11748
  await checkPermission(this.permissionService, this.userId, schema.name, "update");
11168
- const hookCtx = createContextForRestore(schema, this.tenantId, record, _optionalChain([options, 'optionalAccess', _271 => _271.hookMetadata]));
11169
- if (!_optionalChain([options, 'optionalAccess', _272 => _272.skipHooks])) {
11749
+ const hookCtx = createContextForRestore(schema, this.tenantId, record, _optionalChain([options, 'optionalAccess', _270 => _270.hookMetadata]));
11750
+ if (!_optionalChain([options, 'optionalAccess', _271 => _271.skipHooks])) {
11170
11751
  await this.hookRegistry.execute("beforeRestore", schema.name, hookCtx);
11171
11752
  }
11172
11753
  const restored = await this.adapter.objectRecords.restore(recordId);
11173
11754
  await this.invalidateRecordCaches(recordId, record.objectId);
11174
- if (!_optionalChain([options, 'optionalAccess', _273 => _273.skipHooks])) {
11755
+ if (!_optionalChain([options, 'optionalAccess', _272 => _272.skipHooks])) {
11175
11756
  const afterCtx = {
11176
11757
  ...hookCtx,
11177
11758
  record: restored
@@ -11186,7 +11767,7 @@ var RecordService = class extends BaseService {
11186
11767
  objectId: schema.id,
11187
11768
  recordId: restored.id,
11188
11769
  recordLabel: restored.label,
11189
- metadata: _optionalChain([options, 'optionalAccess', _274 => _274.hookMetadata])
11770
+ metadata: _optionalChain([options, 'optionalAccess', _273 => _273.hookMetadata])
11190
11771
  }).catch((err) => {
11191
11772
  console.error(
11192
11773
  "Audit log failed (record.restored):",
@@ -11567,7 +12148,7 @@ var DocumentRendererService = class {
11567
12148
  throw new StorageDownloadNotSupportedError();
11568
12149
  }
11569
12150
  let storagePath = fileId;
11570
- if (_optionalChain([this, 'access', _275 => _275.options, 'optionalAccess', _276 => _276.filesRepository])) {
12151
+ if (_optionalChain([this, 'access', _274 => _274.options, 'optionalAccess', _275 => _275.filesRepository])) {
11571
12152
  const file2 = await this.options.filesRepository.findById(fileId);
11572
12153
  if (!file2) {
11573
12154
  throw new Error(`Template file not found: ${fileId}`);
@@ -11585,8 +12166,8 @@ var DocumentRendererService = class {
11585
12166
  for (const field of fields) {
11586
12167
  const rawValue = getContextValue(context, field.contextPath);
11587
12168
  const attrInfo = await this.getAttributeInfo(field.contextPath, workflow2);
11588
- if (_optionalChain([attrInfo, 'optionalAccess', _277 => _277.attribute])) {
11589
- if (attrInfo.attribute.type === "relation" && rawValue && _optionalChain([this, 'access', _278 => _278.options, 'optionalAccess', _279 => _279.relationService])) {
12169
+ if (_optionalChain([attrInfo, 'optionalAccess', _276 => _276.attribute])) {
12170
+ if (attrInfo.attribute.type === "relation" && rawValue && _optionalChain([this, 'access', _277 => _277.options, 'optionalAccess', _278 => _278.relationService])) {
11590
12171
  const ids = Array.isArray(rawValue) ? rawValue : [rawValue];
11591
12172
  const stringIds = ids.filter((id) => typeof id === "string");
11592
12173
  if (stringIds.length > 0) {
@@ -11607,7 +12188,7 @@ var DocumentRendererService = class {
11607
12188
  resolved.set(field.id, this.formatValueSimple(rawValue, field.fallback));
11608
12189
  }
11609
12190
  }
11610
- if (relationBatch.length > 0 && _optionalChain([this, 'access', _280 => _280.options, 'optionalAccess', _281 => _281.relationService])) {
12191
+ if (relationBatch.length > 0 && _optionalChain([this, 'access', _279 => _279.options, 'optionalAccess', _280 => _280.relationService])) {
11611
12192
  try {
11612
12193
  const batchResult = await this.options.relationService.resolveIdsBatch(
11613
12194
  relationBatch.map((r) => ({ attributeId: r.attributeId, ids: r.ids }))
@@ -11616,12 +12197,12 @@ var DocumentRendererService = class {
11616
12197
  const options = _nullishCoalesce(batchResult[attributeId], () => ( []));
11617
12198
  const labels = options.map((o) => o.label);
11618
12199
  const field = fields.find((f) => f.id === fieldId);
11619
- resolved.set(fieldId, labels.join(", ") || _optionalChain([field, 'optionalAccess', _282 => _282.fallback]) || "");
12200
+ resolved.set(fieldId, labels.join(", ") || _optionalChain([field, 'optionalAccess', _281 => _281.fallback]) || "");
11620
12201
  }
11621
- } catch (e12) {
12202
+ } catch (e14) {
11622
12203
  for (const { fieldId, ids } of relationBatch) {
11623
12204
  const field = fields.find((f) => f.id === fieldId);
11624
- resolved.set(fieldId, ids.join(", ") || _optionalChain([field, 'optionalAccess', _283 => _283.fallback]) || "");
12205
+ resolved.set(fieldId, ids.join(", ") || _optionalChain([field, 'optionalAccess', _282 => _282.fallback]) || "");
11625
12206
  }
11626
12207
  }
11627
12208
  }
@@ -11632,7 +12213,7 @@ var DocumentRendererService = class {
11632
12213
  * Parses paths like "slots.client.firstName" to find the attribute definition
11633
12214
  */
11634
12215
  async getAttributeInfo(contextPath, workflow2) {
11635
- const schemaService = _optionalChain([this, 'access', _284 => _284.options, 'optionalAccess', _285 => _285.schemaService]);
12216
+ const schemaService = _optionalChain([this, 'access', _283 => _283.options, 'optionalAccess', _284 => _284.schemaService]);
11636
12217
  if (!schemaService) {
11637
12218
  return null;
11638
12219
  }
@@ -11645,7 +12226,7 @@ var DocumentRendererService = class {
11645
12226
  }
11646
12227
  const slotId = parts[1];
11647
12228
  const attributeName = parts[2];
11648
- const slot = _optionalChain([workflow2, 'access', _286 => _286.slots, 'optionalAccess', _287 => _287.find, 'call', _288 => _288((s) => s.id === slotId)]);
12229
+ const slot = _optionalChain([workflow2, 'access', _285 => _285.slots, 'optionalAccess', _286 => _286.find, 'call', _287 => _287((s) => s.id === slotId)]);
11649
12230
  if (!slot) {
11650
12231
  return null;
11651
12232
  }
@@ -11654,7 +12235,7 @@ var DocumentRendererService = class {
11654
12235
  try {
11655
12236
  schema = await schemaService.getObjectSchemaByName(slot.objectName);
11656
12237
  this.schemaCache.set(slot.objectName, schema);
11657
- } catch (e13) {
12238
+ } catch (e15) {
11658
12239
  return null;
11659
12240
  }
11660
12241
  }
@@ -11844,7 +12425,7 @@ var DocumentProcessingHook = class extends BaseService {
11844
12425
  const pendingIds = [];
11845
12426
  for (const [nodeId, doc] of Object.entries(context.documents)) {
11846
12427
  const metadata = doc.metadata;
11847
- if (_optionalChain([metadata, 'optionalAccess', _289 => _289.status]) === "pending") {
12428
+ if (_optionalChain([metadata, 'optionalAccess', _288 => _288.status]) === "pending") {
11848
12429
  pendingIds.push(nodeId);
11849
12430
  }
11850
12431
  }
@@ -11895,12 +12476,12 @@ var DocumentProcessingHook = class extends BaseService {
11895
12476
  }
11896
12477
  for (const slotId of targetSlotIds) {
11897
12478
  try {
11898
- const recordId = _optionalChain([context, 'access', _290 => _290.createdRecordIds, 'optionalAccess', _291 => _291[slotId]]);
12479
+ const recordId = _optionalChain([context, 'access', _289 => _289.createdRecordIds, 'optionalAccess', _290 => _290[slotId]]);
11899
12480
  if (!recordId) {
11900
12481
  continue;
11901
12482
  }
11902
- const slotDef = _optionalChain([workflow2, 'access', _292 => _292.slots, 'optionalAccess', _293 => _293.find, 'call', _294 => _294((s) => s.id === slotId)]);
11903
- const objectName = _optionalChain([slotDef, 'optionalAccess', _295 => _295.objectName]);
12483
+ const slotDef = _optionalChain([workflow2, 'access', _291 => _291.slots, 'optionalAccess', _292 => _292.find, 'call', _293 => _293((s) => s.id === slotId)]);
12484
+ const objectName = _optionalChain([slotDef, 'optionalAccess', _294 => _294.objectName]);
11904
12485
  if (!objectName) {
11905
12486
  continue;
11906
12487
  }
@@ -11917,14 +12498,14 @@ var DocumentProcessingHook = class extends BaseService {
11917
12498
  attachedDocumentIds.push(result.document.id);
11918
12499
  const record = await recordService.getRecord(recordId);
11919
12500
  if (record) {
11920
- const attachments = _nullishCoalesce(_optionalChain([record, 'access', _296 => _296.values, 'optionalAccess', _297 => _297.attachments]), () => ( []));
12501
+ const attachments = _nullishCoalesce(_optionalChain([record, 'access', _295 => _295.values, 'optionalAccess', _296 => _296.attachments]), () => ( []));
11921
12502
  await recordService.updateRecord(
11922
12503
  recordId,
11923
12504
  { attachments: [...attachments, result.document.id] },
11924
12505
  { partial: true }
11925
12506
  );
11926
12507
  }
11927
- } catch (e14) {
12508
+ } catch (e16) {
11928
12509
  }
11929
12510
  }
11930
12511
  return attachedDocumentIds;
@@ -12183,7 +12764,7 @@ var WorkflowAccessGrantService = class extends BaseService {
12183
12764
  * Check if a specific token has been revoked.
12184
12765
  */
12185
12766
  isTokenRevoked(dbGrant, jti) {
12186
- return _nullishCoalesce(_optionalChain([dbGrant, 'access', _298 => _298.revoked_token_jtis, 'optionalAccess', _299 => _299.includes, 'call', _300 => _300(jti)]), () => ( false));
12767
+ return _nullishCoalesce(_optionalChain([dbGrant, 'access', _297 => _297.revoked_token_jtis, 'optionalAccess', _298 => _298.includes, 'call', _299 => _299(jti)]), () => ( false));
12187
12768
  }
12188
12769
  /**
12189
12770
  * Validate access token payload against the grant.
@@ -12231,15 +12812,14 @@ var WorkflowAccessGrantService = class extends BaseService {
12231
12812
  };
12232
12813
 
12233
12814
  // src/runtime/services/workflow/instance.service.ts
12234
- var _crypto = require('crypto');
12235
12815
  var WorkflowInstanceService = class extends BaseService {
12236
12816
  constructor(adapter, workflowService, options) {
12237
12817
  super(adapter);
12238
12818
  this.workflowService = workflowService;
12239
- this.executorRegistry = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _301 => _301.executorRegistry]), () => ( getDefaultExecutorRegistry()));
12240
- this.schemaService = _optionalChain([options, 'optionalAccess', _302 => _302.schemaService]);
12241
- this.recordService = _optionalChain([options, 'optionalAccess', _303 => _303.recordService]);
12242
- this.documentProcessingHook = _optionalChain([options, 'optionalAccess', _304 => _304.documentProcessingHook]);
12819
+ this.executorRegistry = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _300 => _300.executorRegistry]), () => ( getDefaultExecutorRegistry()));
12820
+ this.schemaService = _optionalChain([options, 'optionalAccess', _301 => _301.schemaService]);
12821
+ this.recordService = _optionalChain([options, 'optionalAccess', _302 => _302.recordService]);
12822
+ this.documentProcessingHook = _optionalChain([options, 'optionalAccess', _303 => _303.documentProcessingHook]);
12243
12823
  }
12244
12824
  /**
12245
12825
  * Start a new workflow instance
@@ -12421,7 +13001,7 @@ var WorkflowInstanceService = class extends BaseService {
12421
13001
  if (!this.adapter.workflowInstances) {
12422
13002
  return { instances: [], total: 0 };
12423
13003
  }
12424
- if (_optionalChain([options, 'optionalAccess', _305 => _305.workflowName])) {
13004
+ if (_optionalChain([options, 'optionalAccess', _304 => _304.workflowName])) {
12425
13005
  const allDbInstances = await this.adapter.workflowInstances.findByWorkflowName(
12426
13006
  options.workflowName,
12427
13007
  { status: options.status }
@@ -12435,11 +13015,11 @@ var WorkflowInstanceService = class extends BaseService {
12435
13015
  return { instances: instances2, total: total2 };
12436
13016
  }
12437
13017
  const { instances: dbInstances, total } = await this.adapter.workflowInstances.list({
12438
- limit: _optionalChain([options, 'optionalAccess', _306 => _306.limit]),
12439
- offset: _optionalChain([options, 'optionalAccess', _307 => _307.offset])
13018
+ limit: _optionalChain([options, 'optionalAccess', _305 => _305.limit]),
13019
+ offset: _optionalChain([options, 'optionalAccess', _306 => _306.offset])
12440
13020
  });
12441
13021
  let instances = dbInstances.map((db) => this.convertDBInstanceToInstance(db));
12442
- if (_optionalChain([options, 'optionalAccess', _308 => _308.status])) {
13022
+ if (_optionalChain([options, 'optionalAccess', _307 => _307.status])) {
12443
13023
  instances = instances.filter((i) => i.status === options.status);
12444
13024
  }
12445
13025
  instances = await this.markExpiredInstances(instances);
@@ -12460,9 +13040,9 @@ var WorkflowInstanceService = class extends BaseService {
12460
13040
  return { instances: [], total: 0 };
12461
13041
  }
12462
13042
  const { instances: dbInstances, total } = await this.adapter.workflowInstances.findByRecordInSlots(objectName, recordId, {
12463
- status: _optionalChain([options, 'optionalAccess', _309 => _309.status]),
12464
- limit: _optionalChain([options, 'optionalAccess', _310 => _310.limit]),
12465
- offset: _optionalChain([options, 'optionalAccess', _311 => _311.offset])
13043
+ status: _optionalChain([options, 'optionalAccess', _308 => _308.status]),
13044
+ limit: _optionalChain([options, 'optionalAccess', _309 => _309.limit]),
13045
+ offset: _optionalChain([options, 'optionalAccess', _310 => _310.offset])
12466
13046
  });
12467
13047
  const instances = dbInstances.map((db) => this.convertDBInstanceToInstance(db));
12468
13048
  return { instances, total };
@@ -12497,7 +13077,7 @@ var WorkflowInstanceService = class extends BaseService {
12497
13077
  updatedAt: /* @__PURE__ */ new Date()
12498
13078
  };
12499
13079
  }
12500
- const executionId = _crypto.randomUUID.call(void 0, );
13080
+ const executionId = generateId();
12501
13081
  let current = {
12502
13082
  ...instance,
12503
13083
  context: {
@@ -12528,13 +13108,13 @@ var WorkflowInstanceService = class extends BaseService {
12528
13108
  try {
12529
13109
  const schemas = await Promise.all(
12530
13110
  current.workflowSnapshot.slots.map(
12531
- (slot) => _optionalChain([this, 'access', _312 => _312.schemaService, 'optionalAccess', _313 => _313.getObjectSchemaByName, 'call', _314 => _314(slot.objectName)])
13111
+ (slot) => _optionalChain([this, 'access', _311 => _311.schemaService, 'optionalAccess', _312 => _312.getObjectSchemaByName, 'call', _313 => _313(slot.objectName)])
12532
13112
  )
12533
13113
  );
12534
13114
  objectDefinitions = schemas.filter(
12535
13115
  (s) => s !== void 0
12536
13116
  );
12537
- } catch (e15) {
13117
+ } catch (e17) {
12538
13118
  }
12539
13119
  }
12540
13120
  const executorContext = {
@@ -12793,9 +13373,9 @@ var WorkflowInstanceService = class extends BaseService {
12793
13373
  */
12794
13374
  async snapshotRecord(recordId) {
12795
13375
  try {
12796
- const record = await _optionalChain([this, 'access', _315 => _315.recordService, 'optionalAccess', _316 => _316.getRecord, 'call', _317 => _317(recordId, { skipPolicyCheck: true })]);
12797
- return _optionalChain([record, 'optionalAccess', _318 => _318.values]);
12798
- } catch (e16) {
13376
+ const record = await _optionalChain([this, 'access', _314 => _314.recordService, 'optionalAccess', _315 => _315.getRecord, 'call', _316 => _316(recordId, { skipPolicyCheck: true })]);
13377
+ return _optionalChain([record, 'optionalAccess', _317 => _317.values]);
13378
+ } catch (e18) {
12799
13379
  return void 0;
12800
13380
  }
12801
13381
  }
@@ -12813,18 +13393,18 @@ var WorkflowInstanceService = class extends BaseService {
12813
13393
  for (const op of [...operations].reverse()) {
12814
13394
  try {
12815
13395
  if (op.operation === "create") {
12816
- await _optionalChain([this, 'access', _319 => _319.recordService, 'optionalAccess', _320 => _320.deleteRecord, 'call', _321 => _321(op.recordId, {
13396
+ await _optionalChain([this, 'access', _318 => _318.recordService, 'optionalAccess', _319 => _319.deleteRecord, 'call', _320 => _320(op.recordId, {
12817
13397
  skipHooks: true,
12818
13398
  skipReferenceCheck: true
12819
13399
  })]);
12820
13400
  rolledBack.push(op.slotId);
12821
13401
  } else if (op.operation === "update" && op.previousData) {
12822
- await _optionalChain([this, 'access', _322 => _322.recordService, 'optionalAccess', _323 => _323.updateRecord, 'call', _324 => _324(op.recordId, op.previousData, {
13402
+ await _optionalChain([this, 'access', _321 => _321.recordService, 'optionalAccess', _322 => _322.updateRecord, 'call', _323 => _323(op.recordId, op.previousData, {
12823
13403
  partial: false
12824
13404
  })]);
12825
13405
  rolledBack.push(op.slotId);
12826
13406
  }
12827
- } catch (e17) {
13407
+ } catch (e19) {
12828
13408
  }
12829
13409
  }
12830
13410
  return rolledBack;
@@ -12943,7 +13523,7 @@ var WorkflowInstanceService = class extends BaseService {
12943
13523
  if (!this.adapter.workflowInstances) {
12944
13524
  return;
12945
13525
  }
12946
- const currentVersion = _nullishCoalesce(_optionalChain([instance, 'access', _325 => _325.context, 'access', _326 => _326.variables, 'optionalAccess', _327 => _327.__version]), () => ( 0));
13526
+ const currentVersion = _nullishCoalesce(_optionalChain([instance, 'access', _324 => _324.context, 'access', _325 => _325.variables, 'optionalAccess', _326 => _326.__version]), () => ( 0));
12947
13527
  const nextVersion = currentVersion + 1;
12948
13528
  const instanceWithVersion = {
12949
13529
  ...instance,
@@ -13224,7 +13804,7 @@ var WorkflowRelationService = class extends BaseService {
13224
13804
  if (attr.type !== "relation") continue;
13225
13805
  for (const slot of slots) {
13226
13806
  const slotData = context.slots[slot.id];
13227
- const slotRecordId = _optionalChain([slotData, 'optionalAccess', _328 => _328.id]);
13807
+ const slotRecordId = _optionalChain([slotData, 'optionalAccess', _327 => _327.id]);
13228
13808
  if (!slotRecordId) continue;
13229
13809
  const targetsSlotObject = attr.targets.some(
13230
13810
  (t) => t.object === slot.objectName
@@ -13292,7 +13872,7 @@ var WorkflowService = class extends BaseService {
13292
13872
  if (Array.isArray(options)) {
13293
13873
  this.systemWorkflows = new Map(options.map((w) => [w.name, w]));
13294
13874
  } else {
13295
- this.systemWorkflows = new Map((_nullishCoalesce(_optionalChain([options, 'optionalAccess', _329 => _329.systemWorkflows]), () => ( []))).map((w) => [w.name, w]));
13875
+ this.systemWorkflows = new Map((_nullishCoalesce(_optionalChain([options, 'optionalAccess', _328 => _328.systemWorkflows]), () => ( []))).map((w) => [w.name, w]));
13296
13876
  }
13297
13877
  }
13298
13878
  // ============================================================================
@@ -13590,7 +14170,7 @@ var WorkflowService = class extends BaseService {
13590
14170
  var UserProfileService = class extends BaseService {
13591
14171
  constructor(adapter, options) {
13592
14172
  super(adapter);
13593
- this.auditService = _optionalChain([options, 'optionalAccess', _330 => _330.auditService]);
14173
+ this.auditService = _optionalChain([options, 'optionalAccess', _329 => _329.auditService]);
13594
14174
  }
13595
14175
  // ============================================================================
13596
14176
  // CACHE MANAGEMENT
@@ -13753,7 +14333,7 @@ var UserProfileService = class extends BaseService {
13753
14333
  */
13754
14334
  async deleteProfile(profileId, options) {
13755
14335
  const profile = await this.getProfileOrThrow(profileId);
13756
- if (_optionalChain([options, 'optionalAccess', _331 => _331.checkAdmin])) {
14336
+ if (_optionalChain([options, 'optionalAccess', _330 => _330.checkAdmin])) {
13757
14337
  if (profile.role === "admin") {
13758
14338
  const adminCount = await this.adapter.userProfiles.countByRole("admin");
13759
14339
  if (adminCount <= 1) {
@@ -13828,7 +14408,7 @@ var UserProfileService = class extends BaseService {
13828
14408
  */
13829
14409
  async hasRole(profileId, role) {
13830
14410
  const profile = await this.getProfile(profileId);
13831
- return _optionalChain([profile, 'optionalAccess', _332 => _332.role]) === role;
14411
+ return _optionalChain([profile, 'optionalAccess', _331 => _331.role]) === role;
13832
14412
  }
13833
14413
  /**
13834
14414
  * Check if user is admin
@@ -14262,7 +14842,7 @@ var DocumentTemplateService = class extends BaseService {
14262
14842
  * Includes both system templates and tenant-specific templates.
14263
14843
  */
14264
14844
  async listTemplates(options) {
14265
- if (_optionalChain([options, 'optionalAccess', _333 => _333.systemOnly])) {
14845
+ if (_optionalChain([options, 'optionalAccess', _332 => _332.systemOnly])) {
14266
14846
  return SYSTEM_TEMPLATES;
14267
14847
  }
14268
14848
  const templates = [...SYSTEM_TEMPLATES];
@@ -14345,8 +14925,8 @@ var DocumentTemplateService = class extends BaseService {
14345
14925
  var DocumentService = class extends BaseService {
14346
14926
  constructor(adapter, options) {
14347
14927
  super(adapter);
14348
- this.templateService = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _334 => _334.templateService]), () => ( new DocumentTemplateService(adapter)));
14349
- this.fileService = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _335 => _335.fileService]), () => ( null));
14928
+ this.templateService = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _333 => _333.templateService]), () => ( new DocumentTemplateService(adapter)));
14929
+ this.fileService = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _334 => _334.fileService]), () => ( null));
14350
14930
  }
14351
14931
  // ============================================================================
14352
14932
  // CREATE
@@ -14597,7 +15177,7 @@ var DocumentService = class extends BaseService {
14597
15177
  */
14598
15178
  async isComplete(documentId) {
14599
15179
  const document2 = await this.getDocument(documentId);
14600
- return _optionalChain([document2, 'optionalAccess', _336 => _336.status]) !== "draft";
15180
+ return _optionalChain([document2, 'optionalAccess', _335 => _335.status]) !== "draft";
14601
15181
  }
14602
15182
  /**
14603
15183
  * Get document with its template and slots.
@@ -14855,7 +15435,7 @@ var DocumentProcessingService = class extends BaseService {
14855
15435
  type: "signature",
14856
15436
  provider: this.config.signatureAdapter.name,
14857
15437
  input: { signers, ...options },
14858
- expiresAt: _optionalChain([options, 'optionalAccess', _337 => _337.expiresAt])
15438
+ expiresAt: _optionalChain([options, 'optionalAccess', _336 => _336.expiresAt])
14859
15439
  });
14860
15440
  return job;
14861
15441
  }
@@ -15012,7 +15592,7 @@ var DocumentProcessingService = class extends BaseService {
15012
15592
  }
15013
15593
  const document2 = await this.documentService.getDocumentOrThrow(documentId);
15014
15594
  const template = await this.templateService.getTemplateOrThrow(document2.templateId);
15015
- if (!_optionalChain([template, 'access', _338 => _338.autoProcessing, 'optionalAccess', _339 => _339.identityVerification, 'optionalAccess', _340 => _340.enabled])) {
15595
+ if (!_optionalChain([template, 'access', _337 => _337.autoProcessing, 'optionalAccess', _338 => _338.identityVerification, 'optionalAccess', _339 => _339.enabled])) {
15016
15596
  throw new Error("Identity verification is not enabled for this document type");
15017
15597
  }
15018
15598
  const job = await this.adapter.documentJobs.create({
@@ -15098,13 +15678,13 @@ var DocumentProcessingService = class extends BaseService {
15098
15678
  const template = await this.templateService.getTemplateOrThrow(document2.templateId);
15099
15679
  const slots = await this.documentService.getSlots(documentId);
15100
15680
  const jobs = [];
15101
- if (_optionalChain([template, 'access', _341 => _341.autoProcessing, 'optionalAccess', _342 => _342.ocr, 'optionalAccess', _343 => _343.enabled]) && this.config.ocrAdapter) {
15681
+ if (_optionalChain([template, 'access', _340 => _340.autoProcessing, 'optionalAccess', _341 => _341.ocr, 'optionalAccess', _342 => _342.enabled]) && this.config.ocrAdapter) {
15102
15682
  for (const slot of slots) {
15103
15683
  const job = await this.processOcr(documentId, slot.slotName);
15104
15684
  jobs.push(job);
15105
15685
  }
15106
15686
  }
15107
- if (_optionalChain([template, 'access', _344 => _344.autoProcessing, 'optionalAccess', _345 => _345.identityVerification, 'optionalAccess', _346 => _346.enabled]) && this.config.identityAdapter) {
15687
+ if (_optionalChain([template, 'access', _343 => _343.autoProcessing, 'optionalAccess', _344 => _344.identityVerification, 'optionalAccess', _345 => _345.enabled]) && this.config.identityAdapter) {
15108
15688
  const job = await this.verifyIdentity(documentId);
15109
15689
  jobs.push(job);
15110
15690
  }
@@ -15175,15 +15755,15 @@ var DocumentProcessingService = class extends BaseService {
15175
15755
  return {
15176
15756
  ocr: {
15177
15757
  available: !!this.config.ocrAdapter,
15178
- provider: _optionalChain([this, 'access', _347 => _347.config, 'access', _348 => _348.ocrAdapter, 'optionalAccess', _349 => _349.name])
15758
+ provider: _optionalChain([this, 'access', _346 => _346.config, 'access', _347 => _347.ocrAdapter, 'optionalAccess', _348 => _348.name])
15179
15759
  },
15180
15760
  signature: {
15181
15761
  available: !!this.config.signatureAdapter,
15182
- provider: _optionalChain([this, 'access', _350 => _350.config, 'access', _351 => _351.signatureAdapter, 'optionalAccess', _352 => _352.name])
15762
+ provider: _optionalChain([this, 'access', _349 => _349.config, 'access', _350 => _350.signatureAdapter, 'optionalAccess', _351 => _351.name])
15183
15763
  },
15184
15764
  identityVerification: {
15185
15765
  available: !!this.config.identityAdapter,
15186
- provider: _optionalChain([this, 'access', _353 => _353.config, 'access', _354 => _354.identityAdapter, 'optionalAccess', _355 => _355.name])
15766
+ provider: _optionalChain([this, 'access', _352 => _352.config, 'access', _353 => _353.identityAdapter, 'optionalAccess', _354 => _354.name])
15187
15767
  }
15188
15768
  };
15189
15769
  }
@@ -15193,7 +15773,7 @@ var DocumentProcessingService = class extends BaseService {
15193
15773
  var FileService = class extends BaseService {
15194
15774
  constructor(adapter, options) {
15195
15775
  super(adapter);
15196
- this.auditService = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _356 => _356.auditService]), () => ( (adapter.audit ? new AuditService(adapter) : void 0)));
15776
+ this.auditService = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _355 => _355.auditService]), () => ( (adapter.audit ? new AuditService(adapter) : void 0)));
15197
15777
  }
15198
15778
  // ============================================================================
15199
15779
  // UPLOAD (requires StorageAdapter)
@@ -15332,7 +15912,7 @@ var FileService = class extends BaseService {
15332
15912
  */
15333
15913
  async getFile(fileId) {
15334
15914
  const file2 = await this.adapter.files.findById(fileId);
15335
- if (_optionalChain([file2, 'optionalAccess', _357 => _357.deletedAt])) {
15915
+ if (_optionalChain([file2, 'optionalAccess', _356 => _356.deletedAt])) {
15336
15916
  return null;
15337
15917
  }
15338
15918
  return file2;
@@ -15394,12 +15974,12 @@ var FileService = class extends BaseService {
15394
15974
  */
15395
15975
  async deleteFile(fileId, options) {
15396
15976
  const file2 = await this.getFileOrThrow(fileId);
15397
- if (_optionalChain([options, 'optionalAccess', _358 => _358.checkOwnership]) && options.userId) {
15977
+ if (_optionalChain([options, 'optionalAccess', _357 => _357.checkOwnership]) && options.userId) {
15398
15978
  if (file2.uploadedBy !== options.userId) {
15399
15979
  throw new Error("You can only delete files you uploaded");
15400
15980
  }
15401
15981
  }
15402
- if (_optionalChain([options, 'optionalAccess', _359 => _359.hard])) {
15982
+ if (_optionalChain([options, 'optionalAccess', _358 => _358.hard])) {
15403
15983
  await this.adapter.files.hardDelete(fileId);
15404
15984
  } else {
15405
15985
  await this.adapter.files.delete(fileId);
@@ -15430,7 +16010,7 @@ var FileService = class extends BaseService {
15430
16010
  }
15431
16011
  const file2 = await this.getFileOrThrow(fileId);
15432
16012
  await this.adapter.storage.delete(file2.storagePath);
15433
- if (_optionalChain([options, 'optionalAccess', _360 => _360.hard])) {
16013
+ if (_optionalChain([options, 'optionalAccess', _359 => _359.hard])) {
15434
16014
  await this.adapter.files.hardDelete(fileId);
15435
16015
  } else {
15436
16016
  await this.adapter.files.delete(fileId);
@@ -15456,15 +16036,15 @@ var FileService = class extends BaseService {
15456
16036
  const fileResults = await Promise.all(fileIds.map((id) => this.getFile(id)));
15457
16037
  const files = fileResults.filter((f) => f !== null);
15458
16038
  if (files.length === 0) return;
15459
- if (_optionalChain([options, 'optionalAccess', _361 => _361.deleteFromStorage]) && this.adapter.storage) {
16039
+ if (_optionalChain([options, 'optionalAccess', _360 => _360.deleteFromStorage]) && this.adapter.storage) {
15460
16040
  const BATCH_SIZE = 10;
15461
16041
  for (let i = 0; i < files.length; i += BATCH_SIZE) {
15462
16042
  const batch = files.slice(i, i + BATCH_SIZE);
15463
- await Promise.all(batch.map((file2) => _optionalChain([this, 'access', _362 => _362.adapter, 'access', _363 => _363.storage, 'optionalAccess', _364 => _364.delete, 'call', _365 => _365(file2.storagePath)])));
16043
+ await Promise.all(batch.map((file2) => _optionalChain([this, 'access', _361 => _361.adapter, 'access', _362 => _362.storage, 'optionalAccess', _363 => _363.delete, 'call', _364 => _364(file2.storagePath)])));
15464
16044
  }
15465
16045
  }
15466
16046
  const idsToDelete = files.map((f) => f.id);
15467
- if (_optionalChain([options, 'optionalAccess', _366 => _366.hard])) {
16047
+ if (_optionalChain([options, 'optionalAccess', _365 => _365.hard])) {
15468
16048
  await Promise.all(idsToDelete.map((id) => this.adapter.files.hardDelete(id)));
15469
16049
  } else {
15470
16050
  await Promise.all(idsToDelete.map((id) => this.adapter.files.delete(id)));
@@ -15472,12 +16052,12 @@ var FileService = class extends BaseService {
15472
16052
  if (this.auditService && this.userId) {
15473
16053
  await Promise.all(
15474
16054
  files.map(
15475
- (file2) => _optionalChain([this, 'access', _367 => _367.auditService, 'optionalAccess', _368 => _368.logFileAction, 'call', _369 => _369({
16055
+ (file2) => _optionalChain([this, 'access', _366 => _366.auditService, 'optionalAccess', _367 => _367.logFileAction, 'call', _368 => _368({
15476
16056
  action: "file.deleted",
15477
16057
  actorId: _nullishCoalesce(this.userId, () => ( "")),
15478
16058
  fileId: file2.id,
15479
16059
  fileName: file2.name,
15480
- metadata: { deletedFromStorage: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _370 => _370.deleteFromStorage]), () => ( false)) }
16060
+ metadata: { deletedFromStorage: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _369 => _369.deleteFromStorage]), () => ( false)) }
15481
16061
  })])
15482
16062
  )
15483
16063
  );
@@ -15555,7 +16135,7 @@ var FileService = class extends BaseService {
15555
16135
  if (!file2) {
15556
16136
  return false;
15557
16137
  }
15558
- if (_optionalChain([options, 'optionalAccess', _371 => _371.isAdmin])) {
16138
+ if (_optionalChain([options, 'optionalAccess', _370 => _370.isAdmin])) {
15559
16139
  return true;
15560
16140
  }
15561
16141
  if (file2.visibility === "public") {
@@ -15565,7 +16145,7 @@ var FileService = class extends BaseService {
15565
16145
  return true;
15566
16146
  }
15567
16147
  if (file2.visibility === "restricted") {
15568
- return _nullishCoalesce(_optionalChain([file2, 'access', _372 => _372.allowedUsers, 'optionalAccess', _373 => _373.includes, 'call', _374 => _374(userId)]), () => ( false));
16148
+ return _nullishCoalesce(_optionalChain([file2, 'access', _371 => _371.allowedUsers, 'optionalAccess', _372 => _372.includes, 'call', _373 => _373(userId)]), () => ( false));
15569
16149
  }
15570
16150
  return false;
15571
16151
  }
@@ -15660,7 +16240,7 @@ function withTimeout(promise, ms, label) {
15660
16240
  var GeocodingService = class {
15661
16241
  constructor(adapter, options) {
15662
16242
  this.adapter = adapter;
15663
- this.timeoutMs = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _375 => _375.timeoutMs]), () => ( GEOCODING_TIMEOUT_MS));
16243
+ this.timeoutMs = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _374 => _374.timeoutMs]), () => ( GEOCODING_TIMEOUT_MS));
15664
16244
  }
15665
16245
  /**
15666
16246
  * Search for address suggestions as the user types
@@ -15744,10 +16324,10 @@ var GlobalSearchService = class extends BaseService {
15744
16324
  */
15745
16325
  async executeSearch(query, options) {
15746
16326
  return await this.adapter.objectRecords.globalSearch(query, {
15747
- limit: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _376 => _376.limit]), () => ( 20)),
15748
- offset: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _377 => _377.offset]), () => ( 0)),
15749
- objectNames: _optionalChain([options, 'optionalAccess', _378 => _378.objectNames]),
15750
- includeObjectInfo: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _379 => _379.includeObjectInfo]), () => ( true))
16327
+ limit: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _375 => _375.limit]), () => ( 20)),
16328
+ offset: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _376 => _376.offset]), () => ( 0)),
16329
+ objectNames: _optionalChain([options, 'optionalAccess', _377 => _377.objectNames]),
16330
+ includeObjectInfo: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _378 => _378.includeObjectInfo]), () => ( true))
15751
16331
  });
15752
16332
  }
15753
16333
  /**
@@ -15758,7 +16338,7 @@ var GlobalSearchService = class extends BaseService {
15758
16338
  * @returns Results grouped by object name
15759
16339
  */
15760
16340
  async searchGrouped(query, options) {
15761
- const limitPerGroup = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _380 => _380.limitPerGroup]), () => ( 5));
16341
+ const limitPerGroup = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _379 => _379.limitPerGroup]), () => ( 5));
15762
16342
  const estimatedGroupCount = 10;
15763
16343
  const fetchLimit = Math.min(limitPerGroup * estimatedGroupCount, 100);
15764
16344
  const { results, total } = await this.search(query, {
@@ -15800,7 +16380,7 @@ var PermissionService = class extends BaseService {
15800
16380
  }
15801
16381
  this.permissionsRepo = adapter.permissions;
15802
16382
  this.permissionCache = _nullishCoalesce(adapter.cache, () => ( new NoopCacheAdapter()));
15803
- this.auditService = _optionalChain([options, 'optionalAccess', _381 => _381.auditService]);
16383
+ this.auditService = _optionalChain([options, 'optionalAccess', _380 => _380.auditService]);
15804
16384
  }
15805
16385
  // ============================================================================
15806
16386
  // PERMISSION CHECKS
@@ -15819,11 +16399,11 @@ var PermissionService = class extends BaseService {
15819
16399
  return true;
15820
16400
  }
15821
16401
  const wildcardPerms = permissions.objectPermissions["*"];
15822
- if (_optionalChain([wildcardPerms, 'optionalAccess', _382 => _382.includes, 'call', _383 => _383(action)])) {
16402
+ if (_optionalChain([wildcardPerms, 'optionalAccess', _381 => _381.includes, 'call', _382 => _382(action)])) {
15823
16403
  return true;
15824
16404
  }
15825
16405
  const objectPerms = permissions.objectPermissions[objectName];
15826
- return _nullishCoalesce(_optionalChain([objectPerms, 'optionalAccess', _384 => _384.includes, 'call', _385 => _385(action)]), () => ( false));
16406
+ return _nullishCoalesce(_optionalChain([objectPerms, 'optionalAccess', _383 => _383.includes, 'call', _384 => _384(action)]), () => ( false));
15827
16407
  }
15828
16408
  /**
15829
16409
  * Check if user can access an object, throw ForbiddenError if not.
@@ -15878,12 +16458,12 @@ var PermissionService = class extends BaseService {
15878
16458
  if (permissions.isAdmin) {
15879
16459
  return true;
15880
16460
  }
15881
- const wildcardPerms = _optionalChain([permissions, 'access', _386 => _386.systemPermissions, 'optionalAccess', _387 => _387["*"]]);
15882
- if (_optionalChain([wildcardPerms, 'optionalAccess', _388 => _388.includes, 'call', _389 => _389(action)])) {
16461
+ const wildcardPerms = _optionalChain([permissions, 'access', _385 => _385.systemPermissions, 'optionalAccess', _386 => _386["*"]]);
16462
+ if (_optionalChain([wildcardPerms, 'optionalAccess', _387 => _387.includes, 'call', _388 => _388(action)])) {
15883
16463
  return true;
15884
16464
  }
15885
- const resourcePerms = _optionalChain([permissions, 'access', _390 => _390.systemPermissions, 'optionalAccess', _391 => _391[resource]]);
15886
- return _nullishCoalesce(_optionalChain([resourcePerms, 'optionalAccess', _392 => _392.includes, 'call', _393 => _393(action)]), () => ( false));
16465
+ const resourcePerms = _optionalChain([permissions, 'access', _389 => _389.systemPermissions, 'optionalAccess', _390 => _390[resource]]);
16466
+ return _nullishCoalesce(_optionalChain([resourcePerms, 'optionalAccess', _391 => _391.includes, 'call', _392 => _392(action)]), () => ( false));
15887
16467
  }
15888
16468
  /**
15889
16469
  * Check if user can access a system resource, throw ForbiddenError if not.
@@ -15912,8 +16492,8 @@ var PermissionService = class extends BaseService {
15912
16492
  if (permissions.isAdmin) {
15913
16493
  return { canRead: true, canCreate: true, canUpdate: true, canDelete: true };
15914
16494
  }
15915
- const wildcardPerms = _nullishCoalesce(_optionalChain([permissions, 'access', _394 => _394.systemPermissions, 'optionalAccess', _395 => _395["*"]]), () => ( []));
15916
- const resourcePerms = _nullishCoalesce(_optionalChain([permissions, 'access', _396 => _396.systemPermissions, 'optionalAccess', _397 => _397[resource]]), () => ( []));
16495
+ const wildcardPerms = _nullishCoalesce(_optionalChain([permissions, 'access', _393 => _393.systemPermissions, 'optionalAccess', _394 => _394["*"]]), () => ( []));
16496
+ const resourcePerms = _nullishCoalesce(_optionalChain([permissions, 'access', _395 => _395.systemPermissions, 'optionalAccess', _396 => _396[resource]]), () => ( []));
15917
16497
  const allPerms = /* @__PURE__ */ new Set([...wildcardPerms, ...resourcePerms]);
15918
16498
  return {
15919
16499
  canRead: allPerms.has("read"),
@@ -16056,7 +16636,7 @@ var PermissionService = class extends BaseService {
16056
16636
  action: "role.updated",
16057
16637
  actorId: this.userId,
16058
16638
  roleId,
16059
- roleLabel: _nullishCoalesce(_optionalChain([role, 'optionalAccess', _398 => _398.label]), () => ( roleId)),
16639
+ roleLabel: _nullishCoalesce(_optionalChain([role, 'optionalAccess', _397 => _397.label]), () => ( roleId)),
16060
16640
  metadata: { permissionsUpdated: true, permissionCount: permissions.length }
16061
16641
  });
16062
16642
  }
@@ -16086,7 +16666,7 @@ var PermissionService = class extends BaseService {
16086
16666
  action: "role.assigned",
16087
16667
  actorId: this.userId,
16088
16668
  roleId,
16089
- roleLabel: _nullishCoalesce(_optionalChain([role, 'optionalAccess', _399 => _399.label]), () => ( roleId)),
16669
+ roleLabel: _nullishCoalesce(_optionalChain([role, 'optionalAccess', _398 => _398.label]), () => ( roleId)),
16090
16670
  targetUserId: userProfileId
16091
16671
  });
16092
16672
  }
@@ -16104,7 +16684,7 @@ var PermissionService = class extends BaseService {
16104
16684
  action: "role.revoked",
16105
16685
  actorId: this.userId,
16106
16686
  roleId,
16107
- roleLabel: _nullishCoalesce(_optionalChain([role, 'optionalAccess', _400 => _400.label]), () => ( roleId)),
16687
+ roleLabel: _nullishCoalesce(_optionalChain([role, 'optionalAccess', _399 => _399.label]), () => ( roleId)),
16108
16688
  targetUserId: userProfileId
16109
16689
  });
16110
16690
  }
@@ -16172,124 +16752,340 @@ var PermissionService = class extends BaseService {
16172
16752
 
16173
16753
  // src/runtime/services/view.service.ts
16174
16754
  var ViewService = class extends BaseService {
16175
- constructor(adapter, nativeViews) {
16755
+ constructor(adapter) {
16176
16756
  super(adapter);
16177
- this.nativeViews = nativeViews;
16178
16757
  }
16179
16758
  // ============================================================================
16180
16759
  // CACHE MANAGEMENT
16181
16760
  // ============================================================================
16182
- /**
16183
- * Invalidate cached views for an object.
16184
- * Called automatically after view mutations.
16185
- */
16186
16761
  async invalidateViewCache(objectName) {
16187
16762
  await this.invalidateCache(cacheKeys.viewsByObject(this.tenantId, objectName));
16188
16763
  }
16764
+ // ============================================================================
16765
+ // READ METHODS
16766
+ // ============================================================================
16189
16767
  /**
16190
- * Get all views for an object (native + custom).
16191
- * Automatically uses tenant context from AsyncLocalStorage.
16768
+ * Get all views for the current tenant.
16769
+ * Optionally filter by view type.
16192
16770
  *
16193
- * Results are cached if a CacheAdapter is configured.
16771
+ * @param type - Optional view type filter
16772
+ * @returns All views for the tenant
16773
+ */
16774
+ async getAllViews(type) {
16775
+ const dbViews = await this.adapter.views.findAllForTenant(type);
16776
+ return dbViews.map((v) => this.convertDBViewToDefinition(v));
16777
+ }
16778
+ /**
16779
+ * Get a specific view by its ID.
16780
+ * Returns null if not found.
16194
16781
  *
16195
- * @param objectName - Object name
16196
- * @returns All views for the object
16782
+ * @param viewId - View ID (UUID)
16783
+ * @returns View definition or null
16197
16784
  */
16198
- async getViewsForObject(objectName) {
16199
- return this.cachedBy("viewsByObject", objectName, () => this.fetchViewsForObject(objectName));
16785
+ async getViewById(viewId) {
16786
+ const dbView = await this.adapter.views.findById(viewId);
16787
+ if (!dbView) {
16788
+ return null;
16789
+ }
16790
+ return this.convertDBViewToDefinition(dbView);
16200
16791
  }
16201
16792
  /**
16202
- * Internal method to fetch views for an object (no caching)
16793
+ * Get all views for an object from the database.
16794
+ * Optionally filter by type and merge with user overlays.
16795
+ *
16796
+ * @param objectName - Object name
16797
+ * @param options - Filter and overlay options
16798
+ * @returns Views from database
16203
16799
  */
16204
- async fetchViewsForObject(objectName) {
16205
- const nativeViewDefs = this.nativeViews.getByObjectName(objectName);
16206
- const dbViews = await this.adapter.views.findByObjectName(objectName);
16207
- const customViews = dbViews.filter((v) => !v.system).map(this.convertDBViewToDefinition);
16208
- return [...nativeViewDefs, ...customViews];
16800
+ async getViews(objectName, options = {}) {
16801
+ const { type, userId } = options;
16802
+ const dbViews = await this.adapter.views.findByObjectName(objectName, type);
16803
+ const views = dbViews.map((v) => this.convertDBViewToDefinition(v));
16804
+ if (!userId) {
16805
+ return views;
16806
+ }
16807
+ const userOverlays = await this.adapter.viewOverlays.findByUser(userId);
16808
+ return views.map((view2) => {
16809
+ const overlay = userOverlays.find((o) => o.viewId === view2.id);
16810
+ return overlay ? this.applyOverlay(view2, overlay) : view2;
16811
+ });
16209
16812
  }
16210
16813
  /**
16211
16814
  * Get a specific view by name.
16212
- * Automatically uses tenant context from AsyncLocalStorage.
16815
+ * Returns null if not found (use getDefaultView for fallback behavior).
16213
16816
  *
16214
16817
  * @param objectName - Object name
16215
16818
  * @param viewName - View name
16216
- * @returns View definition or null
16217
- */
16218
- async getView(objectName, viewName) {
16219
- const nativeView = this.nativeViews.get(objectName, viewName);
16220
- if (nativeView) {
16221
- return nativeView;
16819
+ * @param options - Type filter and overlay options
16820
+ * @returns View or null
16821
+ */
16822
+ async getView(objectName, viewName, options = {}) {
16823
+ const { type, userId } = options;
16824
+ let dbView;
16825
+ if (type) {
16826
+ dbView = await this.adapter.views.findByNameAndType(objectName, viewName, type);
16827
+ } else {
16828
+ dbView = await this.adapter.views.findByName(objectName, viewName);
16222
16829
  }
16223
- const dbView = await this.adapter.views.findByName(objectName, viewName);
16224
- if (dbView) {
16225
- return this.convertDBViewToDefinition(dbView);
16830
+ if (!dbView) {
16831
+ return null;
16226
16832
  }
16227
- return null;
16833
+ const view2 = this.convertDBViewToDefinition(dbView);
16834
+ if (!userId) {
16835
+ return view2;
16836
+ }
16837
+ const overlay = await this.adapter.viewOverlays.findByViewAndUser(dbView.id, userId);
16838
+ return overlay ? this.applyOverlay(view2, overlay) : view2;
16228
16839
  }
16229
16840
  /**
16230
- * Get the default view for an object
16841
+ * Get the default view for an object and type.
16842
+ * If no view exists in DB, auto-creates and persists a default view.
16231
16843
  *
16232
16844
  * Priority:
16233
- * 1. Custom view marked as default (for the specified layout)
16234
- * 2. Native view marked as default (for the specified layout)
16235
- * 3. First available view (for the specified layout)
16845
+ * 1. User's preferred view (from overlay with isUserDefault=true)
16846
+ * 2. View marked as default in DB (with matching layout if specified)
16847
+ * 3. First available view (with matching layout if specified)
16848
+ * 4. Auto-created default view (persisted to DB)
16236
16849
  *
16237
16850
  * @param objectName - Object name
16238
- * @param layout - Optional layout filter ("page" or "modal")
16239
- * @returns Default view or null
16851
+ * @param type - View type
16852
+ * @param objectDefinition - Object definition (for default generation)
16853
+ * @param options - Optional filters (userId, layout for detail views)
16854
+ * @returns View definition (existing or auto-created)
16855
+ */
16856
+ async getDefaultView(objectName, type, objectDefinition, options) {
16857
+ const { userId, layout } = _nullishCoalesce(options, () => ( {}));
16858
+ const matchesLayout = (view2) => {
16859
+ if (!layout || type !== "detail") return true;
16860
+ const detailView2 = view2;
16861
+ return detailView2.config.layout === layout;
16862
+ };
16863
+ const applyUserOverlay = async (view2, viewId) => {
16864
+ if (!userId) return view2;
16865
+ const overlay = await this.adapter.viewOverlays.findByViewAndUser(viewId, userId);
16866
+ return overlay ? this.applyOverlay(view2, overlay) : view2;
16867
+ };
16868
+ if (userId) {
16869
+ const userDefaultOverlay = await this.adapter.viewOverlays.findUserDefault(
16870
+ userId,
16871
+ objectName,
16872
+ type
16873
+ );
16874
+ if (userDefaultOverlay) {
16875
+ const dbView = await this.adapter.views.findById(userDefaultOverlay.viewId);
16876
+ if (dbView && dbView.type === type) {
16877
+ const view2 = this.convertDBViewToDefinition(dbView);
16878
+ if (matchesLayout(view2)) {
16879
+ return this.applyOverlay(view2, userDefaultOverlay);
16880
+ }
16881
+ }
16882
+ }
16883
+ }
16884
+ const defaultDbView = await this.adapter.views.findDefault(objectName, type);
16885
+ if (defaultDbView) {
16886
+ const view2 = this.convertDBViewToDefinition(defaultDbView);
16887
+ if (matchesLayout(view2)) {
16888
+ return await applyUserOverlay(view2, defaultDbView.id);
16889
+ }
16890
+ }
16891
+ const dbViews = await this.adapter.views.findByObjectName(objectName, type);
16892
+ for (const dbView of dbViews) {
16893
+ const view2 = this.convertDBViewToDefinition(dbView);
16894
+ if (matchesLayout(view2)) {
16895
+ return await applyUserOverlay(view2, dbView.id);
16896
+ }
16897
+ }
16898
+ if (dbViews.length > 0) {
16899
+ const firstView = dbViews[0];
16900
+ const view2 = this.convertDBViewToDefinition(firstView);
16901
+ return await applyUserOverlay(view2, firstView.id);
16902
+ }
16903
+ const created = await this.ensureDefaultView(objectName, type, objectDefinition, layout);
16904
+ if (userId) {
16905
+ if (!created.id) {
16906
+ throw new Error("Created view missing ID - this should never happen");
16907
+ }
16908
+ const overlay = await this.adapter.viewOverlays.findByViewAndUser(created.id, userId);
16909
+ return overlay ? this.applyOverlay(created, overlay) : created;
16910
+ }
16911
+ return created;
16912
+ }
16913
+ // ============================================================================
16914
+ // DEFAULT VIEW GENERATION
16915
+ // ============================================================================
16916
+ /**
16917
+ * Ensure a default view exists in DB for the given object and type.
16918
+ * If no view exists, generates and persists one.
16919
+ * Idempotent — safe to call concurrently (uses upsert).
16240
16920
  */
16241
- async getDefaultView(objectName, layout) {
16242
- const views = await this.getViewsForObject(objectName);
16243
- const filtered = layout ? views.filter((v) => (_nullishCoalesce(v.layout, () => ( "page"))) === layout) : views;
16244
- const customDefault = filtered.find((v) => v.default && !v.system);
16245
- if (customDefault) return customDefault;
16246
- const nativeDefault = filtered.find((v) => v.default && v.system);
16247
- if (nativeDefault) return nativeDefault;
16248
- return _nullishCoalesce(filtered[0], () => ( null));
16921
+ async ensureDefaultView(objectName, type, objectDefinition, layout) {
16922
+ const generated = this.generateDefaultViewConfig(objectName, type, objectDefinition, layout);
16923
+ const viewName = type === "detail" && layout === "modal" ? "default-modal" : "default";
16924
+ const dbView = await this.adapter.views.upsert({
16925
+ objectName,
16926
+ type,
16927
+ name: viewName,
16928
+ label: generated.label,
16929
+ config: generated.config,
16930
+ default: true
16931
+ });
16932
+ const legacyFallbackId = `fallback:${objectName}:${type}`;
16933
+ await this.adapter.viewOverlays.migrateViewId(legacyFallbackId, dbView.id);
16934
+ await this.invalidateViewCache(objectName);
16935
+ return this.convertDBViewToDefinition(dbView);
16249
16936
  }
16250
16937
  /**
16251
- * Create a custom view.
16252
- * Automatically uses tenant context from AsyncLocalStorage.
16938
+ * Generate default view config for an object.
16939
+ * Used by ensureDefaultView() and resetViewToDefault().
16940
+ */
16941
+ generateDefaultViewConfig(objectName, type, objectDefinition, layout) {
16942
+ switch (type) {
16943
+ case "detail":
16944
+ return this.generateDefaultDetailConfig(objectName, objectDefinition, layout);
16945
+ case "list":
16946
+ return this.generateDefaultListConfig(objectName, objectDefinition);
16947
+ default:
16948
+ throw new SchemaError(
16949
+ `Default view generation not supported for type: ${type}`,
16950
+ SchemaErrorCode.VALIDATION_FAILED,
16951
+ { type }
16952
+ );
16953
+ }
16954
+ }
16955
+ generateDefaultDetailConfig(objectName, object2, layout = "page") {
16956
+ const visibleAttrs = object2.attributes.filter(
16957
+ (attr) => !(attr.hidden || attr.archived || attr.system)
16958
+ );
16959
+ const fields = visibleAttrs.sort((a, b) => (_nullishCoalesce(a.order, () => ( 999))) - (_nullishCoalesce(b.order, () => ( 999)))).map((attr) => ({
16960
+ attribute: attr.name,
16961
+ span: this.getDefaultFieldSpan(attr.type)
16962
+ }));
16963
+ const formTab = {
16964
+ id: "form",
16965
+ name: "form",
16966
+ label: "Details",
16967
+ type: "form",
16968
+ groups: [
16969
+ {
16970
+ id: "general",
16971
+ label: "General",
16972
+ fields,
16973
+ order: 0
16974
+ }
16975
+ ],
16976
+ order: 0
16977
+ };
16978
+ const tabs = [formTab];
16979
+ tabs.push({
16980
+ id: "activity",
16981
+ name: "activity",
16982
+ label: "Activity",
16983
+ type: "activity",
16984
+ order: 1
16985
+ });
16986
+ tabs.push({
16987
+ id: "notes",
16988
+ name: "notes",
16989
+ label: "Notes",
16990
+ type: "notes",
16991
+ order: 2,
16992
+ allowCreate: true
16993
+ });
16994
+ const hasDocuments = object2.attributes.some((attr) => attr.type === "document");
16995
+ if (hasDocuments) {
16996
+ tabs.push({
16997
+ id: "documents",
16998
+ name: "documents",
16999
+ label: "Documents",
17000
+ type: "documents",
17001
+ order: 3,
17002
+ allowUpload: true,
17003
+ allowRemove: true,
17004
+ showProcessing: true
17005
+ });
17006
+ }
17007
+ const config = {
17008
+ layout,
17009
+ tabs
17010
+ };
17011
+ return {
17012
+ name: "default",
17013
+ label: "Default View",
17014
+ object: objectName,
17015
+ type: "detail",
17016
+ config,
17017
+ default: true
17018
+ };
17019
+ }
17020
+ generateDefaultListConfig(objectName, object2) {
17021
+ const visibleAttrs = object2.attributes.filter(
17022
+ (attr) => !(attr.hidden || attr.archived || attr.system)
17023
+ );
17024
+ const columns = visibleAttrs.sort((a, b) => (_nullishCoalesce(a.order, () => ( 999))) - (_nullishCoalesce(b.order, () => ( 999)))).slice(0, 5).map((attr) => attr.name);
17025
+ const config = {
17026
+ layout: "table",
17027
+ columns
17028
+ };
17029
+ return {
17030
+ name: "default",
17031
+ label: "All Records",
17032
+ object: objectName,
17033
+ type: "list",
17034
+ config,
17035
+ default: true
17036
+ };
17037
+ }
17038
+ getDefaultFieldSpan(type) {
17039
+ switch (type) {
17040
+ case "textarea":
17041
+ case "richtext":
17042
+ case "location":
17043
+ return 12;
17044
+ case "checkbox":
17045
+ return 4;
17046
+ default:
17047
+ return 6;
17048
+ }
17049
+ }
17050
+ // ============================================================================
17051
+ // WRITE METHODS (Architect Mode)
17052
+ // ============================================================================
17053
+ /**
17054
+ * Create a new view (Architect Mode).
16253
17055
  *
16254
17056
  * @param input - View definition
16255
17057
  * @returns Created view
16256
17058
  */
16257
17059
  async createView(input) {
16258
17060
  this.validateViewName(input.name);
16259
- this.validateModalLayout(input.tabs, input.layout);
16260
- const existing = await this.adapter.views.findByName(input.objectName, input.name);
17061
+ const existing = await this.adapter.views.findByNameAndType(
17062
+ input.objectName,
17063
+ input.name,
17064
+ input.type
17065
+ );
16261
17066
  if (existing) {
16262
17067
  throw new SchemaError(
16263
- `View "${input.name}" already exists for object "${input.objectName}"`,
16264
- SchemaErrorCode.DUPLICATE_ATTRIBUTE,
16265
- { viewName: input.name, objectName: input.objectName }
16266
- );
16267
- }
16268
- if (this.nativeViews.has(input.objectName, input.name)) {
16269
- throw new SchemaError(
16270
- `Cannot create view "${input.name}": a system view with this name already exists`,
17068
+ `View "${input.name}" of type "${input.type}" already exists for object "${input.objectName}"`,
16271
17069
  SchemaErrorCode.DUPLICATE_ATTRIBUTE,
16272
- { viewName: input.name, objectName: input.objectName, system: true }
17070
+ { viewName: input.name, type: input.type, objectName: input.objectName }
16273
17071
  );
16274
17072
  }
16275
17073
  const dbView = await this.adapter.views.create({
16276
17074
  objectName: input.objectName,
17075
+ type: input.type,
16277
17076
  name: input.name,
16278
17077
  label: input.label,
16279
17078
  description: input.description,
16280
17079
  icon: input.icon,
16281
- layout: input.layout,
16282
- tabs: _nullishCoalesce(input.tabs, () => ( [])),
16283
- default: _nullishCoalesce(input.default, () => ( false)),
16284
- system: false,
16285
- // Custom views are never system
17080
+ config: input.config,
17081
+ default: input.default,
16286
17082
  metadata: input.metadata
16287
17083
  });
16288
17084
  await this.invalidateViewCache(input.objectName);
16289
17085
  return this.convertDBViewToDefinition(dbView);
16290
17086
  }
16291
17087
  /**
16292
- * Update a custom view
17088
+ * Update an existing view.
16293
17089
  *
16294
17090
  * @param viewId - View ID
16295
17091
  * @param input - Update data
@@ -16300,18 +17096,11 @@ var ViewService = class extends BaseService {
16300
17096
  if (!dbView) {
16301
17097
  throw new NotFoundError("View", viewId);
16302
17098
  }
16303
- if (dbView.system) {
16304
- throw new ProtectedResourceError("view", dbView.name, "modify");
16305
- }
16306
- const effectiveLayout = _nullishCoalesce(input.layout, () => ( dbView.layout));
16307
- const effectiveTabs = _nullishCoalesce(input.tabs, () => ( dbView.tabs));
16308
- this.validateModalLayout(effectiveTabs, effectiveLayout);
16309
17099
  const updated = await this.adapter.views.update(viewId, {
16310
17100
  label: input.label,
16311
17101
  description: input.description,
16312
17102
  icon: input.icon,
16313
- layout: input.layout,
16314
- tabs: input.tabs,
17103
+ config: input.config,
16315
17104
  default: input.default,
16316
17105
  metadata: input.metadata
16317
17106
  });
@@ -16319,7 +17108,8 @@ var ViewService = class extends BaseService {
16319
17108
  return this.convertDBViewToDefinition(updated);
16320
17109
  }
16321
17110
  /**
16322
- * Delete a custom view
17111
+ * Delete a view.
17112
+ * Overlays are automatically deleted (cascade).
16323
17113
  *
16324
17114
  * @param viewId - View ID
16325
17115
  */
@@ -16328,16 +17118,12 @@ var ViewService = class extends BaseService {
16328
17118
  if (!dbView) {
16329
17119
  throw new NotFoundError("View", viewId);
16330
17120
  }
16331
- if (dbView.system) {
16332
- throw new ProtectedResourceError("view", dbView.name, "delete");
16333
- }
17121
+ await this.adapter.viewOverlays.deleteByView(viewId);
16334
17122
  await this.adapter.views.delete(viewId);
16335
17123
  await this.invalidateViewCache(dbView.objectName);
16336
17124
  }
16337
17125
  /**
16338
- * Set a view as default for its object and layout.
16339
- * Only unsets other defaults for the same layout.
16340
- * Automatically uses tenant context from AsyncLocalStorage.
17126
+ * Set a view as default for its object and type.
16341
17127
  *
16342
17128
  * @param viewId - View ID
16343
17129
  * @returns Updated view
@@ -16347,11 +17133,9 @@ var ViewService = class extends BaseService {
16347
17133
  if (!dbView) {
16348
17134
  throw new NotFoundError("View", viewId);
16349
17135
  }
16350
- const viewLayout = _nullishCoalesce(dbView.layout, () => ( "page"));
16351
- const currentViews = await this.adapter.views.findByObjectName(dbView.objectName);
17136
+ const currentViews = await this.adapter.views.findByObjectName(dbView.objectName, dbView.type);
16352
17137
  for (const v of currentViews) {
16353
- const vLayout = _nullishCoalesce(v.layout, () => ( "page"));
16354
- if (v.default && v.id !== viewId && !v.system && vLayout === viewLayout) {
17138
+ if (v.default && v.id !== viewId) {
16355
17139
  await this.adapter.views.update(v.id, { default: false });
16356
17140
  }
16357
17141
  }
@@ -16359,12 +17143,140 @@ var ViewService = class extends BaseService {
16359
17143
  await this.invalidateViewCache(dbView.objectName);
16360
17144
  return this.convertDBViewToDefinition(updated);
16361
17145
  }
17146
+ /**
17147
+ * Reset a view to its default (auto-generated) state.
17148
+ * Regenerates the view config based on the object definition.
17149
+ *
17150
+ * @param viewId - View ID
17151
+ * @param objectDefinition - Object definition for regeneration
17152
+ * @returns Updated view
17153
+ */
17154
+ async resetViewToDefault(viewId, objectDefinition) {
17155
+ const dbView = await this.adapter.views.findById(viewId);
17156
+ if (!dbView) {
17157
+ throw new NotFoundError("View", viewId);
17158
+ }
17159
+ const generated = this.generateDefaultViewConfig(
17160
+ dbView.objectName,
17161
+ dbView.type,
17162
+ objectDefinition,
17163
+ dbView.type === "detail" ? _nullishCoalesce(_optionalChain([dbView, 'access', _400 => _400.config, 'optionalAccess', _401 => _401.layout]), () => ( "page")) : void 0
17164
+ );
17165
+ const newConfig = generated.config;
17166
+ const updated = await this.adapter.views.update(viewId, { config: newConfig });
17167
+ await this.invalidateViewCache(dbView.objectName);
17168
+ return this.convertDBViewToDefinition(updated);
17169
+ }
16362
17170
  // ============================================================================
16363
- // PRIVATE HELPERS
17171
+ // USER CUSTOMIZATION METHODS
16364
17172
  // ============================================================================
16365
17173
  /**
16366
- * Validate view name format (kebab-case)
17174
+ * Reset user customizations for a view.
17175
+ * Deletes the overlay, returning to source/fallback view.
17176
+ *
17177
+ * @param viewId - View ID (can be UUID or fallback ID)
17178
+ * @param userId - User ID
17179
+ */
17180
+ async resetUserCustomizations(viewId, userId) {
17181
+ await this.adapter.viewOverlays.deleteByViewAndUser(viewId, userId);
17182
+ }
17183
+ /**
17184
+ * Set a view as the user's default for an object and type.
17185
+ *
17186
+ * @param viewId - View ID (can be UUID or fallback ID)
17187
+ * @param userId - User ID
17188
+ * @param objectName - Object name
17189
+ * @param type - View type
17190
+ */
17191
+ async setUserDefaultView(viewId, userId, objectName, type) {
17192
+ await this.adapter.viewOverlays.clearUserDefault(userId, objectName, type);
17193
+ const existingOverlay = await this.adapter.viewOverlays.findByViewAndUser(viewId, userId);
17194
+ if (existingOverlay) {
17195
+ await this.adapter.viewOverlays.update(existingOverlay.id, { isUserDefault: true });
17196
+ } else {
17197
+ await this.adapter.viewOverlays.create({
17198
+ viewId,
17199
+ userId,
17200
+ configOverrides: {},
17201
+ isUserDefault: true
17202
+ });
17203
+ }
17204
+ }
17205
+ /**
17206
+ * Check if a user has customized a view.
17207
+ *
17208
+ * @param viewId - View ID
17209
+ * @param userId - User ID
17210
+ * @returns True if overlay exists
17211
+ */
17212
+ async hasUserCustomizations(viewId, userId) {
17213
+ const overlay = await this.adapter.viewOverlays.findByViewAndUser(viewId, userId);
17214
+ return overlay !== null && Object.keys(overlay.configOverrides).length > 0;
17215
+ }
17216
+ // ============================================================================
17217
+ // OVERLAY MERGE LOGIC
17218
+ // ============================================================================
17219
+ /**
17220
+ * Apply an overlay to a view definition.
17221
+ * Implements merge semantics defined in the plan.
17222
+ *
17223
+ * @param view - Source view definition
17224
+ * @param overlay - User overlay
17225
+ * @returns Merged view definition
17226
+ */
17227
+ applyOverlay(view2, overlay) {
17228
+ const overrides = overlay.configOverrides;
17229
+ switch (view2.type) {
17230
+ case "list":
17231
+ return this.applyListViewOverlay(view2, overrides);
17232
+ case "detail":
17233
+ return this.applyDetailViewOverlay(view2, overrides);
17234
+ default:
17235
+ return view2;
17236
+ }
17237
+ }
17238
+ applyListViewOverlay(view2, overrides) {
17239
+ const mergedConfig = {
17240
+ ...view2.config,
17241
+ tabs: this.mergeViewTabs(view2.config.tabs, overrides.tabs, overrides.hiddenTabIds)
17242
+ };
17243
+ return { ...view2, config: mergedConfig };
17244
+ }
17245
+ applyDetailViewOverlay(view2, overrides) {
17246
+ const mergedConfig = {
17247
+ ...view2.config,
17248
+ // Append for tabs (detail tabs)
17249
+ tabs: this.mergeDetailTabs(
17250
+ view2.config.tabs,
17251
+ overrides.detailTabs,
17252
+ overrides.hiddenDetailTabIds
17253
+ )
17254
+ };
17255
+ return {
17256
+ ...view2,
17257
+ config: mergedConfig
17258
+ };
17259
+ }
17260
+ /**
17261
+ * Merge source tabs with overlay tabs.
17262
+ * - Source tabs are visible to all
17263
+ * - Overlay tabs are appended (user-private)
17264
+ * - hiddenTabIds allows hiding source tabs
17265
+ */
17266
+ mergeViewTabs(sourceTabs = [], overlayTabs = [], hiddenTabIds = []) {
17267
+ const visibleSourceTabs = sourceTabs.filter((t) => !hiddenTabIds.includes(t.id));
17268
+ return [...visibleSourceTabs, ...overlayTabs];
17269
+ }
17270
+ /**
17271
+ * Merge detail tabs (form, activity, etc.)
16367
17272
  */
17273
+ mergeDetailTabs(sourceTabs = [], overlayTabs = [], hiddenTabIds = []) {
17274
+ const visibleSourceTabs = sourceTabs.filter((t) => !hiddenTabIds.includes(t.id));
17275
+ return [...visibleSourceTabs, ...overlayTabs];
17276
+ }
17277
+ // ============================================================================
17278
+ // PRIVATE HELPERS
17279
+ // ============================================================================
16368
17280
  validateViewName(name) {
16369
17281
  if (!name || name.length === 0) {
16370
17282
  throw new ValidationError("View name cannot be empty", [
@@ -16386,66 +17298,72 @@ var ViewService = class extends BaseService {
16386
17298
  ]);
16387
17299
  }
16388
17300
  }
16389
- /**
16390
- * Validate modal layout constraints.
16391
- * Modal views must have exactly one form tab.
16392
- */
16393
- validateModalLayout(tabs, layout) {
16394
- if (layout !== "modal") return;
16395
- if (!tabs || tabs.length === 0) {
16396
- throw new ValidationError("Modal views must have exactly one form tab", [
16397
- { path: ["tabs"], message: "Modal views must have exactly one form tab" }
16398
- ]);
16399
- }
16400
- if (tabs.length > 1) {
16401
- throw new ValidationError("Modal views can only have one tab", [
16402
- { path: ["tabs"], message: "Modal views can only have one tab" }
16403
- ]);
16404
- }
16405
- if (tabs[0].type !== "form") {
16406
- throw new ValidationError("Modal views must have a form tab", [
16407
- { path: ["tabs"], message: `Modal views must have a form tab, not a ${tabs[0].type}` }
16408
- ]);
16409
- }
16410
- }
16411
17301
  /**
16412
17302
  * Convert database view to ViewDefinition
16413
17303
  */
16414
17304
  convertDBViewToDefinition(dbView) {
16415
- return {
17305
+ const base = {
16416
17306
  id: dbView.id,
16417
17307
  name: dbView.name,
16418
17308
  label: dbView.label,
16419
17309
  description: dbView.description,
16420
17310
  icon: dbView.icon,
16421
17311
  object: dbView.objectName,
16422
- layout: dbView.layout,
16423
- tabs: dbView.tabs,
16424
17312
  default: dbView.default,
16425
- system: dbView.system,
16426
17313
  metadata: dbView.metadata
16427
17314
  };
17315
+ switch (dbView.type) {
17316
+ case "detail": {
17317
+ const detailView2 = {
17318
+ ...base,
17319
+ type: "detail",
17320
+ config: dbView.config
17321
+ };
17322
+ return detailView2;
17323
+ }
17324
+ case "list": {
17325
+ const listView2 = {
17326
+ ...base,
17327
+ type: "list",
17328
+ config: dbView.config
17329
+ };
17330
+ return listView2;
17331
+ }
17332
+ // TODO: Add proper config types for calendar, timeline, gallery when implemented
17333
+ case "calendar":
17334
+ case "timeline":
17335
+ case "gallery":
17336
+ return { ...base, type: dbView.type, config: dbView.config };
17337
+ default:
17338
+ throw new SchemaError(
17339
+ `Unknown view type: ${dbView.type}`,
17340
+ SchemaErrorCode.VALIDATION_FAILED,
17341
+ { type: dbView.type }
17342
+ );
17343
+ }
16428
17344
  }
16429
17345
  };
16430
17346
 
16431
17347
  // src/runtime/view-sync.ts
16432
- async function syncNativeViews(adapter, nativeViewRegistry, options = {}) {
17348
+ async function seedRegistryViews(adapter, registry2, options = {}) {
16433
17349
  const result = {
16434
17350
  success: true,
16435
17351
  viewsSynced: 0,
16436
17352
  viewsCreated: 0,
16437
- viewsUpdated: 0,
17353
+ viewsSkipped: 0,
16438
17354
  viewsDeleted: 0,
16439
17355
  errors: []
16440
17356
  };
16441
- const nativeViews = nativeViewRegistry.getAll();
17357
+ const registryViews = registry2.getAll();
16442
17358
  if (options.verbose && options.logger) {
16443
- options.logger.info(`[ViewSync] Starting sync for ${nativeViews.length} native views...`);
17359
+ options.logger.info(`[ViewSync] Starting seed for ${registryViews.length} registry views...`);
16444
17360
  }
16445
17361
  try {
16446
17362
  await adapter.transaction(async (tx) => {
16447
- const viewsByObject = await syncAllViews(tx, nativeViews, result, options);
16448
- await cleanupRemovedViews(tx, viewsByObject, result, options);
17363
+ const viewsByObjectAndType = await seedAllViews(tx, registryViews, result, options);
17364
+ if (options.deleteOrphans) {
17365
+ await cleanupOrphanViews(tx, viewsByObjectAndType, result, options);
17366
+ }
16449
17367
  });
16450
17368
  } catch (error2) {
16451
17369
  handleTransactionError(result, error2);
@@ -16453,38 +17371,78 @@ async function syncNativeViews(adapter, nativeViewRegistry, options = {}) {
16453
17371
  logSyncComplete(result, options);
16454
17372
  return result;
16455
17373
  }
16456
- async function syncAllViews(tx, nativeViews, result, options) {
16457
- const viewsByObject = /* @__PURE__ */ new Map();
16458
- for (const nativeView of nativeViews) {
17374
+ var syncNativeViews = seedRegistryViews;
17375
+ async function seedAllViews(tx, registryViews, result, options) {
17376
+ const viewsByObjectAndType = /* @__PURE__ */ new Map();
17377
+ for (const view2 of registryViews) {
16459
17378
  try {
16460
- await syncSingleView(tx, nativeView, result, options);
16461
- trackViewByObject(viewsByObject, nativeView);
17379
+ await seedSingleView(tx, view2, result, options);
17380
+ trackViewByObjectAndType(viewsByObjectAndType, view2);
16462
17381
  } catch (error2) {
16463
- handleViewSyncError(result, nativeView, error2, options);
17382
+ handleViewSyncError(result, view2, error2);
16464
17383
  }
16465
17384
  }
16466
- return viewsByObject;
17385
+ return viewsByObjectAndType;
16467
17386
  }
16468
- function trackViewByObject(viewsByObject, nativeView) {
16469
- const objectViews = _nullishCoalesce(viewsByObject.get(nativeView.object), () => ( []));
16470
- objectViews.push(nativeView.name);
16471
- viewsByObject.set(nativeView.object, objectViews);
17387
+ async function seedSingleView(adapter, view2, result, options) {
17388
+ const exists = await adapter.views.exists(view2.object, view2.name, view2.type);
17389
+ if (exists) {
17390
+ result.viewsSkipped++;
17391
+ result.viewsSynced++;
17392
+ if (options.verbose && options.logger) {
17393
+ options.logger.info(`[ViewSync] Skipped (exists): ${view2.object}:${view2.name}:${view2.type}`);
17394
+ }
17395
+ return;
17396
+ }
17397
+ if (options.dryRun) {
17398
+ result.viewsCreated++;
17399
+ result.viewsSynced++;
17400
+ if (options.verbose && options.logger) {
17401
+ options.logger.info(`[ViewSync] Would create: ${view2.object}:${view2.name}:${view2.type}`);
17402
+ }
17403
+ return;
17404
+ }
17405
+ await adapter.views.upsert({
17406
+ objectName: view2.object,
17407
+ type: view2.type,
17408
+ name: view2.name,
17409
+ label: view2.label,
17410
+ description: view2.description,
17411
+ icon: view2.icon,
17412
+ config: view2.config,
17413
+ default: _nullishCoalesce(view2.default, () => ( false)),
17414
+ metadata: view2.metadata
17415
+ });
17416
+ result.viewsCreated++;
17417
+ result.viewsSynced++;
17418
+ if (options.verbose && options.logger) {
17419
+ options.logger.info(`[ViewSync] \u2713 Created: ${view2.object}:${view2.name}:${view2.type}`);
17420
+ }
17421
+ }
17422
+ function trackViewByObjectAndType(viewsByObjectAndType, view2) {
17423
+ const key = `${view2.object}:${view2.type}`;
17424
+ const viewNames = _nullishCoalesce(viewsByObjectAndType.get(key), () => ( []));
17425
+ viewNames.push(view2.name);
17426
+ viewsByObjectAndType.set(key, viewNames);
16472
17427
  }
16473
- function handleViewSyncError(result, nativeView, error2, _options) {
17428
+ function handleViewSyncError(result, view2, error2) {
16474
17429
  result.success = false;
16475
17430
  result.errors.push({
16476
- viewName: nativeView.name,
16477
- objectName: nativeView.object,
17431
+ viewName: view2.name,
17432
+ objectName: view2.object,
16478
17433
  error: error2 instanceof Error ? error2.message : String(error2)
16479
17434
  });
16480
17435
  }
16481
- async function cleanupRemovedViews(tx, viewsByObject, result, options) {
17436
+ async function cleanupOrphanViews(tx, viewsByObjectAndType, result, options) {
16482
17437
  if (options.dryRun) return;
16483
- for (const [objectName, viewNames] of viewsByObject) {
16484
- const deletedCount = await tx.views.deleteNotIn(objectName, viewNames);
17438
+ for (const [key, viewNames] of viewsByObjectAndType) {
17439
+ const [objectName, type] = key.split(":");
17440
+ const deletedCount = await tx.views.deleteNotIn(objectName, type, viewNames);
16485
17441
  result.viewsDeleted += deletedCount;
16486
17442
  if (options.verbose && deletedCount > 0 && options.logger) {
16487
- options.logger.info(`[ViewSync] Deleted ${deletedCount} obsolete views for ${objectName}`);
17443
+ options.logger.info(
17444
+ `[ViewSync] Deleted ${deletedCount} orphan ${type} views for ${objectName}`
17445
+ );
16488
17446
  }
16489
17447
  }
16490
17448
  }
@@ -16499,63 +17457,27 @@ function handleTransactionError(result, error2) {
16499
17457
  function logSyncComplete(result, options) {
16500
17458
  if (options.verbose && options.logger) {
16501
17459
  options.logger.info(
16502
- `[ViewSync] ${result.success ? "\u2713" : "\u2717"} Sync complete:
16503
- Views: ${result.viewsCreated} created, ${result.viewsUpdated} updated, ${result.viewsDeleted} deleted
17460
+ `[ViewSync] ${result.success ? "\u2713" : "\u2717"} Seed complete:
17461
+ Views: ${result.viewsCreated} created, ${result.viewsSkipped} skipped, ${result.viewsDeleted} deleted
16504
17462
  Errors: ${result.errors.length}`
16505
17463
  );
16506
17464
  }
16507
17465
  }
16508
- async function syncSingleView(adapter, nativeView, result, options) {
16509
- if (!nativeView.system) {
16510
- throw new Error(`View ${nativeView.name} is not marked as system`);
16511
- }
16512
- const existingView = await adapter.views.findSystemByName(nativeView.object, nativeView.name);
16513
- const isNew = !existingView;
16514
- if (isNew) {
16515
- result.viewsCreated++;
16516
- } else {
16517
- result.viewsUpdated++;
16518
- }
16519
- result.viewsSynced++;
16520
- if (options.dryRun) {
16521
- if (options.verbose && options.logger) {
16522
- options.logger.info(
16523
- `[ViewSync] Would ${isNew ? "create" : "update"} view: ${nativeView.object}:${nativeView.name}`
16524
- );
16525
- }
16526
- return;
16527
- }
16528
- await adapter.views.upsert({
16529
- objectName: nativeView.object,
16530
- name: nativeView.name,
16531
- label: nativeView.label,
16532
- description: nativeView.description,
16533
- icon: nativeView.icon,
16534
- tabs: nativeView.tabs,
16535
- default: _nullishCoalesce(nativeView.default, () => ( false)),
16536
- system: true,
16537
- metadata: nativeView.metadata
16538
- });
16539
- if (options.verbose && options.logger) {
16540
- options.logger.info(
16541
- `[ViewSync] \u2713 Synced ${nativeView.object}:${nativeView.name}: ${nativeView.tabs.length} tabs`
16542
- );
16543
- }
16544
- }
16545
- async function verifyNativeViewsSync(adapter, nativeViewRegistry) {
16546
- const nativeViews = nativeViewRegistry.getAll();
16547
- for (const view2 of nativeViews) {
16548
- if (!view2.system) continue;
16549
- const existing = await adapter.views.findSystemByName(view2.object, view2.name);
16550
- if (!existing) {
17466
+ async function verifyRegistryViewsSeeded(adapter, registry2) {
17467
+ const registryViews = registry2.getAll();
17468
+ for (const view2 of registryViews) {
17469
+ const exists = await adapter.views.exists(view2.object, view2.name, view2.type);
17470
+ if (!exists) {
16551
17471
  return false;
16552
17472
  }
16553
17473
  }
16554
17474
  return true;
16555
17475
  }
16556
- async function getViewSyncPreview(adapter, nativeViewRegistry) {
16557
- return await syncNativeViews(adapter, nativeViewRegistry, { dryRun: true });
17476
+ var verifyNativeViewsSync = verifyRegistryViewsSeeded;
17477
+ async function getViewSeedPreview(adapter, registry2) {
17478
+ return await seedRegistryViews(adapter, registry2, { dryRun: true });
16558
17479
  }
17480
+ var getViewSyncPreview = getViewSeedPreview;
16559
17481
 
16560
17482
  // src/runtime/sync.ts
16561
17483
  var BASE_ATTRIBUTE_KEYS = /* @__PURE__ */ new Set([
@@ -16755,7 +17677,7 @@ async function syncAll(adapter, objectRegistry, nativeViewRegistry, options = {}
16755
17677
  console.info(
16756
17678
  `[SyncAll] ${result.success ? "\u2713" : "\u2717"} Full sync complete:
16757
17679
  Objects: ${objectsResult.objectsSynced} synced (${objectsResult.objectsCreated} created, ${objectsResult.objectsUpdated} updated)
16758
- Views: ${viewsResult.viewsSynced} synced (${viewsResult.viewsCreated} created, ${viewsResult.viewsUpdated} updated)
17680
+ Views: ${viewsResult.viewsSynced} synced (${viewsResult.viewsCreated} created, ${viewsResult.viewsSkipped} skipped)
16759
17681
  Errors: ${objectsResult.errors.length + viewsResult.errors.length}`
16760
17682
  );
16761
17683
  }
@@ -17143,4 +18065,28 @@ var NoopGeocodingAdapter = class {
17143
18065
 
17144
18066
 
17145
18067
 
17146
- exports.RELATION_TARGET_ANY = RELATION_TARGET_ANY; exports.isUniversalRelation = isUniversalRelation; exports.RecordReferencedError = RecordReferencedError; exports.AttributeInUseError = AttributeInUseError; exports.ObjectReferencedError = ObjectReferencedError; exports.NoopGeocodingAdapter = NoopGeocodingAdapter; exports.SYSTEM_FIELD_NAMES = SYSTEM_FIELD_NAMES; exports.RESERVED_ATTRIBUTE_NAMES = RESERVED_ATTRIBUTE_NAMES; exports.PolicyViolationError = PolicyViolationError; exports.SYSTEM_ATTRIBUTES = SYSTEM_ATTRIBUTES; exports.getSystemAttributeList = getSystemAttributeList; exports.isSystemAttribute = isSystemAttribute; exports.isSystemAttributeObject = isSystemAttributeObject; exports.isSimpleFormNode = isSimpleFormNode; exports.isAdvancedFormNode = isAdvancedFormNode; exports.isStartNode = isStartNode; exports.isFormNode = isFormNode; exports.isConditionNode = isConditionNode; exports.isDocumentNode = isDocumentNode; exports.isEndNode = isEndNode; exports.getNodeOutputs = getNodeOutputs; exports.isConditionRule = isConditionRule; exports.isConditionGroup = isConditionGroup; exports.eq = eq; exports.neq = neq; exports.and = and; exports.or = or; exports.inValues = inValues; exports.isEmpty = isEmpty; exports.isNotEmpty = isNotEmpty; exports.isWorkflowDefinition = isWorkflowDefinition; exports.isWorkflowPublished = isWorkflowPublished; exports.isSystemWorkflow = isSystemWorkflow; exports.isInstanceTerminal = isInstanceTerminal; exports.isInstanceWaiting = isInstanceWaiting; exports.canResumeInstance = canResumeInstance; exports.createStartTransition = createStartTransition; exports.isInvitationValid = isInvitationValid; exports.isInvitationAccepted = isInvitationAccepted; exports.isInvitationExpired = isInvitationExpired; exports.isGrantValid = isGrantValid; exports.isGrantRevoked = isGrantRevoked; exports.isTokenRevoked = isTokenRevoked; exports.isGrantExpired = isGrantExpired; exports.canAccessNode = canAccessNode; exports.createEmptyContext = createEmptyContext; exports.getContextValue = getContextValue; exports.setContextValue = setContextValue; exports.mergeFormToSlot = mergeFormToSlot; exports.DEFAULT_THEME = DEFAULT_THEME; exports.mergeWithDefaults = mergeWithDefaults; exports.generateCssVariables = generateCssVariables; exports.isInstanceEvent = isInstanceEvent; exports.isNodeEvent = isNodeEvent; exports.isInvitationOrGrantEvent = isInvitationOrGrantEvent; exports.ConditionOperatorSchema = ConditionOperatorSchema; exports.ConditionRuleSchema = ConditionRuleSchema; exports.ConditionGroupSchema = ConditionGroupSchema; exports.StartNodeSchema = StartNodeSchema; exports.FormFieldRefSchema = FormFieldRefSchema; exports.FlowRowFieldSchema = FlowRowFieldSchema; exports.FlowRowSchema = FlowRowSchema; exports.FormNodeSchema = FormNodeSchema; exports.ConditionNodeSchema = ConditionNodeSchema; exports.DocumentNodeSchema = DocumentNodeSchema; exports.EndNodeSchema = EndNodeSchema; exports.WorkflowNodeSchema = WorkflowNodeSchema; exports.SlotModeSchema = SlotModeSchema; exports.WorkflowSlotSchema = WorkflowSlotSchema; exports.AuthMethodSchema = AuthMethodSchema; exports.ShareStatusSchema = ShareStatusSchema; exports.WorkflowShareSchema = WorkflowShareSchema; exports.CreateShareInputSchema = CreateShareInputSchema; exports.NodePositionSchema = NodePositionSchema; exports.ViewportSchema = ViewportSchema; exports.WorkflowLayoutSchema = WorkflowLayoutSchema; exports.ThemeColorsSchema = ThemeColorsSchema; exports.ThemeLogoSchema = ThemeLogoSchema; exports.WorkflowThemeSchema = WorkflowThemeSchema; exports.WorkflowConfigSchema = WorkflowConfigSchema; exports.WorkflowStatusSchema = WorkflowStatusSchema; exports.WorkflowDefinitionSchema = WorkflowDefinitionSchema; exports.asTenantId = asTenantId; exports.asUserId = asUserId; exports.generateId = generateId; exports.generatePrefixedId = generatePrefixedId; exports.slugify = slugify; exports.generateTemplateName = generateTemplateName; exports.EMPTY_VALUE_PLACEHOLDER = EMPTY_VALUE_PLACEHOLDER; exports.formatAttributeValue = formatAttributeValue; exports.SchemaErrorCode = SchemaErrorCode; exports.SchemaError = SchemaError; exports.NotFoundError = NotFoundError; exports.ObjectNotFoundError = ObjectNotFoundError; exports.AttributeNotFoundError = AttributeNotFoundError; exports.RecordNotFoundError = RecordNotFoundError; exports.UserProfileNotFoundError = UserProfileNotFoundError; exports.FileNotFoundError = FileNotFoundError; exports.ValidationError = ValidationError; exports.ProtectedResourceError = ProtectedResourceError; exports.SyncError = SyncError; exports.NotSystemObjectError = NotSystemObjectError; exports.DuplicateError = DuplicateError; exports.isSchemaError = isSchemaError; exports.isNotFoundError = isNotFoundError; exports.isValidationError = isValidationError; exports.isProtectedResourceError = isProtectedResourceError; exports.ForbiddenError = ForbiddenError; exports.ProtectedRoleError = ProtectedRoleError; exports.RoleNotFoundError = RoleNotFoundError; exports.isForbiddenError = isForbiddenError; exports.ConcurrentModificationError = ConcurrentModificationError; exports.isConcurrentModificationError = isConcurrentModificationError; exports.text = text; exports.textarea = textarea; exports.richtext = richtext; exports.number = number; exports.checkbox = checkbox; exports.date = date; exports.phone = phone; exports.currency = currency; exports.status = status; exports.select = select; exports.multiselect = multiselect; exports.location = location; exports.file = file; exports.user = user; exports.relation = relation; exports.rating = rating; exports.formula = formula; exports.rollup = rollup; exports.document = document; exports.ObjectBuilder = ObjectBuilder; exports.object = object; exports.GroupBuilder = GroupBuilder; exports.DirectTableTabConfig = DirectTableTabConfig; exports.InverseTableTabConfig = InverseTableTabConfig; exports.CustomTabConfig = CustomTabConfig; exports.NotesTabConfig = NotesTabConfig; exports.ActivityTabConfig = ActivityTabConfig; exports.FlowsTabConfig = FlowsTabConfig; exports.DocumentsTabConfig = DocumentsTabConfig; exports.TabBuilder = TabBuilder; exports.ViewBuilder = ViewBuilder; exports.view = view; exports.group = group; exports.WorkflowFormRowBuilder = WorkflowFormRowBuilder; exports.WorkflowFormBuilder = WorkflowFormBuilder; exports.WorkflowSimpleFormBuilder = WorkflowSimpleFormBuilder; exports.WorkflowConditionBuilder = WorkflowConditionBuilder; exports.WorkflowEndBuilder = WorkflowEndBuilder; exports.WorkflowStartBuilder = WorkflowStartBuilder; exports.WorkflowBuilder = WorkflowBuilder; exports.workflow = workflow; exports.registry = registry; exports.SYSTEM_TEMPLATE_IDS = SYSTEM_TEMPLATE_IDS; exports.FRENCH_ID_CARD = FRENCH_ID_CARD; exports.PASSPORT = PASSPORT; exports.DRIVING_LICENSE = DRIVING_LICENSE; exports.PROOF_OF_ADDRESS = PROOF_OF_ADDRESS; exports.SIGNABLE_CONTRACT = SIGNABLE_CONTRACT; exports.GENERIC_DOCUMENT = GENERIC_DOCUMENT; exports.SYSTEM_TEMPLATES = SYSTEM_TEMPLATES; exports.getSystemTemplate = getSystemTemplate; exports.isSystemTemplate = isSystemTemplate; exports.DEFAULT_VALIDATION_MESSAGES = DEFAULT_VALIDATION_MESSAGES; exports.textConfigSchema = textConfigSchema; exports.textareaConfigSchema = textareaConfigSchema; exports.richtextConfigSchema = richtextConfigSchema; exports.numberConfigSchema = numberConfigSchema; exports.checkboxConfigSchema = checkboxConfigSchema; exports.dateConfigSchema = dateConfigSchema; exports.phoneConfigSchema = phoneConfigSchema; exports.currencyConfigSchema = currencyConfigSchema; exports.statusConfigSchema = statusConfigSchema; exports.locationConfigSchema = locationConfigSchema; exports.selectConfigSchema = selectConfigSchema; exports.multiselectConfigSchema = multiselectConfigSchema; exports.fileConfigSchema = fileConfigSchema; exports.userConfigSchema = userConfigSchema; exports.relationConfigSchema = relationConfigSchema; exports.ratingConfigSchema = ratingConfigSchema; exports.formulaConfigSchema = formulaConfigSchema; exports.rollupConfigSchema = rollupConfigSchema; exports.documentConfigSchema = documentConfigSchema; exports.attributeConfigSchemas = attributeConfigSchemas; exports.getAttributeConfigSchema = getAttributeConfigSchema; exports.validateAttributeConfig = validateAttributeConfig; exports.parseAttributeConfig = parseAttributeConfig; exports.safeParseAttributeConfig = safeParseAttributeConfig; exports.createTextValidator = createTextValidator; exports.createNumberValidator = createNumberValidator; exports.createCheckboxValidator = createCheckboxValidator; exports.createDateValidator = createDateValidator; exports.createPhoneValidator = createPhoneValidator; exports.createCurrencyValidator = createCurrencyValidator; exports.createStatusValidator = createStatusValidator; exports.createSelectValidator = createSelectValidator; exports.createMultiselectValidator = createMultiselectValidator; exports.createLocationValidator = createLocationValidator; exports.createFileValidator = createFileValidator; exports.createUserValidator = createUserValidator; exports.createSingleRelationValidator = createSingleRelationValidator; exports.createMultiRelationValidator = createMultiRelationValidator; exports.createRelationValidator = createRelationValidator; exports.createRatingValidator = createRatingValidator; exports.createFormulaValidator = createFormulaValidator; exports.createRollupValidator = createRollupValidator; exports.createTextAreaValidator = createTextAreaValidator; exports.createRichtextValidator = createRichtextValidator; exports.createAttributeValidator = createAttributeValidator; exports.createFormAttributeValidator = createFormAttributeValidator; exports.createObjectValidator = createObjectValidator; exports.validateAttribute = validateAttribute; exports.validateObject = validateObject; exports.validateObjectOrThrow = validateObjectOrThrow; exports.createDraftValidator = createDraftValidator; exports.validateDraft = validateDraft; exports.validateDraftOrThrow = validateDraftOrThrow; exports.getMissingRequiredAttributes = getMissingRequiredAttributes; exports.isRecordComplete = isRecordComplete; exports.computeRecordStatus = computeRecordStatus; exports.WorkflowJwtService = WorkflowJwtService; exports.hashOptions = hashOptions; exports.cacheKeys = cacheKeys; exports.cacheTtl = cacheTtl; exports.defaultTtl = defaultTtl; exports.NoopCacheAdapter = NoopCacheAdapter; exports.formatRecord = formatRecord; exports.formatRecords = formatRecords; exports.createDefaultState = createDefaultState; exports.SHORTCUT_TO_FILTER_OPERATOR = SHORTCUT_TO_FILTER_OPERATOR; exports.QueryNoResultError = QueryNoResultError; exports.QueryMultipleResultsError = QueryMultipleResultsError; exports.TenantContextError = TenantContextError; exports.getSchemaFromContext = getSchemaFromContext; exports.getSchemaByNameFromContext = getSchemaByNameFromContext; exports.hasSchemaContext = hasSchemaContext; exports.getSchemaContext = getSchemaContext; exports.addSchemaToContext = addSchemaToContext; exports.runWithSchemaContext = runWithSchemaContext; exports.runWithMergedSchemaContext = runWithMergedSchemaContext; exports.getContext = getContext; exports.getTenantId = getTenantId; exports.getUserId = getUserId; exports.hasContext = hasContext; exports.runWithContext = runWithContext; exports.withTenantContext = withTenantContext; exports.QueryBuilder = QueryBuilder; exports.createQueryBuilder = createQueryBuilder; exports.evaluateCondition = evaluateCondition; exports.evaluate = evaluate; exports.evaluateWithTrace = evaluateWithTrace; exports.ExecutorRegistry = ExecutorRegistry; exports.success = success; exports.wait = wait; exports.complete = complete; exports.error = error; exports.ConditionExecutor = ConditionExecutor; exports.DocumentExecutor = DocumentExecutor; exports.EndExecutor = EndExecutor; exports.FormExecutor = FormExecutor; exports.StartExecutor = StartExecutor; exports.createDefaultExecutorRegistry = createDefaultExecutorRegistry; exports.getDefaultExecutorRegistry = getDefaultExecutorRegistry; exports.evaluateFormula = evaluateFormula; exports.evaluateFormulaWithResult = evaluateFormulaWithResult; exports.formatFormulaResult = formatFormulaResult; exports.evaluateFormulaAttribute = evaluateFormulaAttribute; exports.validateFormulaExpression = validateFormulaExpression; exports.extractFormulaVariables = extractFormulaVariables; exports.extractRelationReferences = extractRelationReferences; exports.extractRelationNames = extractRelationNames; exports.hasRelationReferences = hasRelationReferences; exports.flattenRelationsForEval = flattenRelationsForEval; exports.evaluateFormulaWithRelations = evaluateFormulaWithRelations; exports.evaluateFormulaAttributeWithRelations = evaluateFormulaAttributeWithRelations; exports.InvalidPathError = InvalidPathError; exports.MaxDepthExceededError = MaxDepthExceededError; exports.parsePath = parsePath; exports.validatePath = validatePath; exports.pathHasManyCardinality = pathHasManyCardinality; exports.getPathDepth = getPathDepth; exports.getTargetAttributeName = getTargetAttributeName; exports.getRelationPath = getRelationPath; exports.traversePath = traversePath; exports.resolveSingleValue = resolveSingleValue; exports.resolveMultiplePaths = resolveMultiplePaths; exports.NoopHookRegistry = NoopHookRegistry; exports.DEFAULT_LABEL_FALLBACK = DEFAULT_LABEL_FALLBACK; exports.renderLabelExpression = renderLabelExpression; exports.isLabelExpression = isLabelExpression; exports.extractAttributeNames = extractAttributeNames; exports.enrichValuesForDisplay = enrichValuesForDisplay; exports.enrichValuesWithSelectLabels = enrichValuesWithSelectLabels; exports.extractRelationIds = extractRelationIds; exports.computeLabelWithRelations = computeLabelWithRelations; exports.createMockAdapter = createMockAdapter; exports.PolicyRegistry = PolicyRegistry; exports.defaultPolicyRegistry = defaultPolicyRegistry; exports.notesPolicy = notesPolicy; exports.BaseService = BaseService; exports.BaseRepository = BaseRepository; exports.SchemaContextAwareRepository = SchemaContextAwareRepository; exports.buildAuditChanges = buildAuditChanges; exports.ObjectSchemaService = ObjectSchemaService; exports.AuditService = AuditService; exports.UserService = UserService; exports.applyDefaultValues = applyDefaultValues; exports.checkPermission = checkPermission; exports.getPolicy = getPolicy; exports.buildPolicyContext = buildPolicyContext; exports.checkRecordAccess = checkRecordAccess; exports.checkRecordModifyOrThrow = checkRecordModifyOrThrow; exports.checkRecordDeleteOrThrow = checkRecordDeleteOrThrow; exports.checkSharedObjectWriteAccess = checkSharedObjectWriteAccess; exports.computeLabel = computeLabel; exports.enrichWithFormulas = enrichWithFormulas; exports.enrichRecordsWithFormulas = enrichRecordsWithFormulas; exports.createContextForCreate = createContextForCreate; exports.createContextForUpdate = createContextForUpdate; exports.createContextForDelete = createContextForDelete; exports.createContextForRestore = createContextForRestore; exports.recalculateParentRollups = recalculateParentRollups; exports.RecordQueryService = RecordQueryService; exports.RecordResolverService = RecordResolverService; exports.RelationService = RelationService; exports.RollupService = RollupService; exports.RecordService = RecordService; exports.FormulaResolverService = FormulaResolverService; exports.RollupScheduler = RollupScheduler; exports.DocumentRenderError = DocumentRenderError; exports.StorageDownloadNotSupportedError = StorageDownloadNotSupportedError; exports.DocumentRendererService = DocumentRendererService; exports.DocumentProcessingHook = DocumentProcessingHook; exports.GrantNotFoundError = GrantNotFoundError; exports.GrantExpiredError = GrantExpiredError; exports.GrantRevokedError = GrantRevokedError; exports.TokenRevokedError = TokenRevokedError; exports.WorkflowAccessGrantService = WorkflowAccessGrantService; exports.WorkflowInstanceService = WorkflowInstanceService; exports.InvitationNotFoundError = InvitationNotFoundError; exports.InvitationExpiredError = InvitationExpiredError; exports.InvitationAlreadyAcceptedError = InvitationAlreadyAcceptedError; exports.InvitationRevokedError = InvitationRevokedError; exports.WorkflowInvitationService = WorkflowInvitationService; exports.WorkflowRelationService = WorkflowRelationService; exports.WorkflowService = WorkflowService; exports.UserProfileService = UserProfileService; exports.DocumentGenerationTemplateNotFoundError = DocumentGenerationTemplateNotFoundError; exports.DocumentGenerationNotConfiguredError = DocumentGenerationNotConfiguredError; exports.DocumentGenerationService = DocumentGenerationService; exports.DocumentTemplateService = DocumentTemplateService; exports.DocumentService = DocumentService; exports.DocumentProcessingService = DocumentProcessingService; exports.FileService = FileService; exports.GeocodingService = GeocodingService; exports.GlobalSearchService = GlobalSearchService; exports.PermissionService = PermissionService; exports.ViewService = ViewService; exports.syncNativeViews = syncNativeViews; exports.verifyNativeViewsSync = verifyNativeViewsSync; exports.getViewSyncPreview = getViewSyncPreview; exports.syncNativeObjects = syncNativeObjects; exports.verifyNativeObjectsSync = verifyNativeObjectsSync; exports.getSyncPreview = getSyncPreview; exports.syncAll = syncAll;
18068
+
18069
+
18070
+
18071
+
18072
+
18073
+
18074
+
18075
+
18076
+
18077
+
18078
+
18079
+
18080
+
18081
+
18082
+
18083
+
18084
+
18085
+
18086
+
18087
+
18088
+
18089
+
18090
+
18091
+
18092
+ exports.IDENTITY_PROPERTIES = IDENTITY_PROPERTIES; exports.BEHAVIOR_PROPERTIES = BEHAVIOR_PROPERTIES; exports.PRESENTATION_PROPERTIES = PRESENTATION_PROPERTIES; exports.isIdentityProperty = isIdentityProperty; exports.isBehaviorProperty = isBehaviorProperty; exports.isPresentationProperty = isPresentationProperty; exports.getPropertyProtectionLevel = getPropertyProtectionLevel; exports.filterPropertiesByCategory = filterPropertiesByCategory; exports.RELATION_TARGET_ANY = RELATION_TARGET_ANY; exports.isUniversalRelation = isUniversalRelation; exports.RecordReferencedError = RecordReferencedError; exports.AttributeInUseError = AttributeInUseError; exports.ObjectReferencedError = ObjectReferencedError; exports.NoopGeocodingAdapter = NoopGeocodingAdapter; exports.SYSTEM_FIELD_NAMES = SYSTEM_FIELD_NAMES; exports.RESERVED_ATTRIBUTE_NAMES = RESERVED_ATTRIBUTE_NAMES; exports.PolicyViolationError = PolicyViolationError; exports.SYSTEM_ATTRIBUTES = SYSTEM_ATTRIBUTES; exports.getSystemAttributeList = getSystemAttributeList; exports.isSystemAttribute = isSystemAttribute; exports.isSystemAttributeObject = isSystemAttributeObject; exports.isSimpleFormNode = isSimpleFormNode; exports.isAdvancedFormNode = isAdvancedFormNode; exports.isStartNode = isStartNode; exports.isFormNode = isFormNode; exports.isConditionNode = isConditionNode; exports.isDocumentNode = isDocumentNode; exports.isEndNode = isEndNode; exports.getNodeOutputs = getNodeOutputs; exports.isConditionRule = isConditionRule; exports.isConditionGroup = isConditionGroup; exports.eq = eq; exports.neq = neq; exports.and = and; exports.or = or; exports.inValues = inValues; exports.isEmpty = isEmpty; exports.isNotEmpty = isNotEmpty; exports.isWorkflowDefinition = isWorkflowDefinition; exports.isWorkflowPublished = isWorkflowPublished; exports.isSystemWorkflow = isSystemWorkflow; exports.isInstanceTerminal = isInstanceTerminal; exports.isInstanceWaiting = isInstanceWaiting; exports.canResumeInstance = canResumeInstance; exports.createStartTransition = createStartTransition; exports.isInvitationValid = isInvitationValid; exports.isInvitationAccepted = isInvitationAccepted; exports.isInvitationExpired = isInvitationExpired; exports.isGrantValid = isGrantValid; exports.isGrantRevoked = isGrantRevoked; exports.isTokenRevoked = isTokenRevoked; exports.isGrantExpired = isGrantExpired; exports.canAccessNode = canAccessNode; exports.createEmptyContext = createEmptyContext; exports.getContextValue = getContextValue; exports.setContextValue = setContextValue; exports.mergeFormToSlot = mergeFormToSlot; exports.DEFAULT_THEME = DEFAULT_THEME; exports.mergeWithDefaults = mergeWithDefaults; exports.generateCssVariables = generateCssVariables; exports.isInstanceEvent = isInstanceEvent; exports.isNodeEvent = isNodeEvent; exports.isInvitationOrGrantEvent = isInvitationOrGrantEvent; exports.ConditionOperatorSchema = ConditionOperatorSchema; exports.ConditionRuleSchema = ConditionRuleSchema; exports.ConditionGroupSchema = ConditionGroupSchema; exports.StartNodeSchema = StartNodeSchema; exports.FormFieldRefSchema = FormFieldRefSchema; exports.FlowRowFieldSchema = FlowRowFieldSchema; exports.FlowRowSchema = FlowRowSchema; exports.FormNodeSchema = FormNodeSchema; exports.ConditionNodeSchema = ConditionNodeSchema; exports.DocumentNodeSchema = DocumentNodeSchema; exports.EndNodeSchema = EndNodeSchema; exports.WorkflowNodeSchema = WorkflowNodeSchema; exports.SlotModeSchema = SlotModeSchema; exports.WorkflowSlotSchema = WorkflowSlotSchema; exports.AuthMethodSchema = AuthMethodSchema; exports.ShareStatusSchema = ShareStatusSchema; exports.WorkflowShareSchema = WorkflowShareSchema; exports.CreateShareInputSchema = CreateShareInputSchema; exports.NodePositionSchema = NodePositionSchema; exports.ViewportSchema = ViewportSchema; exports.WorkflowLayoutSchema = WorkflowLayoutSchema; exports.ThemeColorsSchema = ThemeColorsSchema; exports.ThemeLogoSchema = ThemeLogoSchema; exports.WorkflowThemeSchema = WorkflowThemeSchema; exports.WorkflowConfigSchema = WorkflowConfigSchema; exports.WorkflowStatusSchema = WorkflowStatusSchema; exports.WorkflowDefinitionSchema = WorkflowDefinitionSchema; exports.asTenantId = asTenantId; exports.asUserId = asUserId; exports.generateId = generateId; exports.generatePrefixedId = generatePrefixedId; exports.slugify = slugify; exports.generateTemplateName = generateTemplateName; exports.EMPTY_VALUE_PLACEHOLDER = EMPTY_VALUE_PLACEHOLDER; exports.formatAttributeValue = formatAttributeValue; exports.SchemaErrorCode = SchemaErrorCode; exports.SchemaError = SchemaError; exports.NotFoundError = NotFoundError; exports.ObjectNotFoundError = ObjectNotFoundError; exports.AttributeNotFoundError = AttributeNotFoundError; exports.RecordNotFoundError = RecordNotFoundError; exports.UserProfileNotFoundError = UserProfileNotFoundError; exports.FileNotFoundError = FileNotFoundError; exports.ValidationError = ValidationError; exports.ProtectedResourceError = ProtectedResourceError; exports.SyncError = SyncError; exports.NotSystemObjectError = NotSystemObjectError; exports.DuplicateError = DuplicateError; exports.isSchemaError = isSchemaError; exports.isNotFoundError = isNotFoundError; exports.isValidationError = isValidationError; exports.isProtectedResourceError = isProtectedResourceError; exports.ForbiddenError = ForbiddenError; exports.ProtectedRoleError = ProtectedRoleError; exports.RoleNotFoundError = RoleNotFoundError; exports.isForbiddenError = isForbiddenError; exports.ConcurrentModificationError = ConcurrentModificationError; exports.isConcurrentModificationError = isConcurrentModificationError; exports.text = text; exports.textarea = textarea; exports.richtext = richtext; exports.number = number; exports.checkbox = checkbox; exports.date = date; exports.phone = phone; exports.currency = currency; exports.status = status; exports.select = select; exports.multiselect = multiselect; exports.location = location; exports.file = file; exports.user = user; exports.relation = relation; exports.rating = rating; exports.formula = formula; exports.rollup = rollup; exports.document = document; exports.ObjectBuilder = ObjectBuilder; exports.object = object; exports.GroupBuilder = GroupBuilder; exports.DirectTableTabConfig = DirectTableTabConfig; exports.InverseTableTabConfig = InverseTableTabConfig; exports.CustomTabConfig = CustomTabConfig; exports.NotesTabConfig = NotesTabConfig; exports.ActivityTabConfig = ActivityTabConfig; exports.FlowsTabConfig = FlowsTabConfig; exports.DocumentsTabConfig = DocumentsTabConfig; exports.TabBuilder = TabBuilder; exports.DetailViewBuilder = DetailViewBuilder; exports.ViewBuilder = ViewBuilder; exports.detailView = detailView; exports.view = view; exports.ListViewBuilder = ListViewBuilder; exports.ListViewTabConfigBuilder = ListViewTabConfigBuilder; exports.listView = listView; exports.group = group; exports.WorkflowFormRowBuilder = WorkflowFormRowBuilder; exports.WorkflowFormBuilder = WorkflowFormBuilder; exports.WorkflowSimpleFormBuilder = WorkflowSimpleFormBuilder; exports.WorkflowConditionBuilder = WorkflowConditionBuilder; exports.WorkflowEndBuilder = WorkflowEndBuilder; exports.WorkflowStartBuilder = WorkflowStartBuilder; exports.WorkflowBuilder = WorkflowBuilder; exports.workflow = workflow; exports.registry = registry; exports.SYSTEM_TEMPLATE_IDS = SYSTEM_TEMPLATE_IDS; exports.FRENCH_ID_CARD = FRENCH_ID_CARD; exports.PASSPORT = PASSPORT; exports.DRIVING_LICENSE = DRIVING_LICENSE; exports.PROOF_OF_ADDRESS = PROOF_OF_ADDRESS; exports.SIGNABLE_CONTRACT = SIGNABLE_CONTRACT; exports.GENERIC_DOCUMENT = GENERIC_DOCUMENT; exports.SYSTEM_TEMPLATES = SYSTEM_TEMPLATES; exports.getSystemTemplate = getSystemTemplate; exports.isSystemTemplate = isSystemTemplate; exports.DEFAULT_VALIDATION_MESSAGES = DEFAULT_VALIDATION_MESSAGES; exports.textConfigSchema = textConfigSchema; exports.textareaConfigSchema = textareaConfigSchema; exports.richtextConfigSchema = richtextConfigSchema; exports.numberConfigSchema = numberConfigSchema; exports.checkboxConfigSchema = checkboxConfigSchema; exports.dateConfigSchema = dateConfigSchema; exports.phoneConfigSchema = phoneConfigSchema; exports.currencyConfigSchema = currencyConfigSchema; exports.statusConfigSchema = statusConfigSchema; exports.locationConfigSchema = locationConfigSchema; exports.selectConfigSchema = selectConfigSchema; exports.multiselectConfigSchema = multiselectConfigSchema; exports.fileConfigSchema = fileConfigSchema; exports.userConfigSchema = userConfigSchema; exports.relationConfigSchema = relationConfigSchema; exports.ratingConfigSchema = ratingConfigSchema; exports.formulaConfigSchema = formulaConfigSchema; exports.rollupConfigSchema = rollupConfigSchema; exports.documentConfigSchema = documentConfigSchema; exports.attributeConfigSchemas = attributeConfigSchemas; exports.getAttributeConfigSchema = getAttributeConfigSchema; exports.validateAttributeConfig = validateAttributeConfig; exports.parseAttributeConfig = parseAttributeConfig; exports.safeParseAttributeConfig = safeParseAttributeConfig; exports.createTextValidator = createTextValidator; exports.createNumberValidator = createNumberValidator; exports.createCheckboxValidator = createCheckboxValidator; exports.createDateValidator = createDateValidator; exports.createPhoneValidator = createPhoneValidator; exports.createCurrencyValidator = createCurrencyValidator; exports.createStatusValidator = createStatusValidator; exports.createSelectValidator = createSelectValidator; exports.createMultiselectValidator = createMultiselectValidator; exports.createLocationValidator = createLocationValidator; exports.createFileValidator = createFileValidator; exports.createUserValidator = createUserValidator; exports.createSingleRelationValidator = createSingleRelationValidator; exports.createMultiRelationValidator = createMultiRelationValidator; exports.createRelationValidator = createRelationValidator; exports.createRatingValidator = createRatingValidator; exports.createFormulaValidator = createFormulaValidator; exports.createRollupValidator = createRollupValidator; exports.createTextAreaValidator = createTextAreaValidator; exports.createRichtextValidator = createRichtextValidator; exports.createAttributeValidator = createAttributeValidator; exports.createFormAttributeValidator = createFormAttributeValidator; exports.createObjectValidator = createObjectValidator; exports.validateAttribute = validateAttribute; exports.validateObject = validateObject; exports.validateObjectOrThrow = validateObjectOrThrow; exports.createDraftValidator = createDraftValidator; exports.validateDraft = validateDraft; exports.validateDraftOrThrow = validateDraftOrThrow; exports.getMissingRequiredAttributes = getMissingRequiredAttributes; exports.isRecordComplete = isRecordComplete; exports.computeRecordStatus = computeRecordStatus; exports.WorkflowJwtService = WorkflowJwtService; exports.hashOptions = hashOptions; exports.cacheKeys = cacheKeys; exports.cacheTtl = cacheTtl; exports.defaultTtl = defaultTtl; exports.NoopCacheAdapter = NoopCacheAdapter; exports.formatRecord = formatRecord; exports.formatRecords = formatRecords; exports.createDefaultState = createDefaultState; exports.SHORTCUT_TO_FILTER_OPERATOR = SHORTCUT_TO_FILTER_OPERATOR; exports.QueryNoResultError = QueryNoResultError; exports.QueryMultipleResultsError = QueryMultipleResultsError; exports.TenantContextError = TenantContextError; exports.FeatureFlagsContextError = FeatureFlagsContextError; exports.isFeatureEnabled = isFeatureEnabled; exports.getFeatureValue = getFeatureValue; exports.getFeatureFlags = getFeatureFlags; exports.tryGetFeatureValue = tryGetFeatureValue; exports.hasFeatureFlagsContext = hasFeatureFlagsContext; exports.runWithFeatureFlags = runWithFeatureFlags; exports.withFeatureFlags = withFeatureFlags; exports.getSchemaFromContext = getSchemaFromContext; exports.getSchemaByNameFromContext = getSchemaByNameFromContext; exports.hasSchemaContext = hasSchemaContext; exports.getSchemaContext = getSchemaContext; exports.addSchemaToContext = addSchemaToContext; exports.runWithSchemaContext = runWithSchemaContext; exports.runWithMergedSchemaContext = runWithMergedSchemaContext; exports.getContext = getContext2; exports.getTenantId = getTenantId; exports.getUserId = getUserId; exports.hasContext = hasContext; exports.runWithContext = runWithContext; exports.withTenantContext = withTenantContext; exports.QueryBuilder = QueryBuilder; exports.createQueryBuilder = createQueryBuilder; exports.evaluateCondition = evaluateCondition; exports.evaluate = evaluate; exports.evaluateWithTrace = evaluateWithTrace; exports.ExecutorRegistry = ExecutorRegistry; exports.success = success; exports.wait = wait; exports.complete = complete; exports.error = error; exports.ConditionExecutor = ConditionExecutor; exports.DocumentExecutor = DocumentExecutor; exports.EndExecutor = EndExecutor; exports.FormExecutor = FormExecutor; exports.StartExecutor = StartExecutor; exports.createDefaultExecutorRegistry = createDefaultExecutorRegistry; exports.getDefaultExecutorRegistry = getDefaultExecutorRegistry; exports.evaluateFormula = evaluateFormula; exports.evaluateFormulaWithResult = evaluateFormulaWithResult; exports.formatFormulaResult = formatFormulaResult; exports.evaluateFormulaAttribute = evaluateFormulaAttribute; exports.validateFormulaExpression = validateFormulaExpression; exports.extractFormulaVariables = extractFormulaVariables; exports.extractRelationReferences = extractRelationReferences; exports.extractRelationNames = extractRelationNames; exports.hasRelationReferences = hasRelationReferences; exports.flattenRelationsForEval = flattenRelationsForEval; exports.evaluateFormulaWithRelations = evaluateFormulaWithRelations; exports.evaluateFormulaAttributeWithRelations = evaluateFormulaAttributeWithRelations; exports.InvalidPathError = InvalidPathError; exports.MaxDepthExceededError = MaxDepthExceededError; exports.parsePath = parsePath; exports.validatePath = validatePath; exports.pathHasManyCardinality = pathHasManyCardinality; exports.getPathDepth = getPathDepth; exports.getTargetAttributeName = getTargetAttributeName; exports.getRelationPath = getRelationPath; exports.traversePath = traversePath; exports.resolveSingleValue = resolveSingleValue; exports.resolveMultiplePaths = resolveMultiplePaths; exports.NoopHookRegistry = NoopHookRegistry; exports.DEFAULT_LABEL_FALLBACK = DEFAULT_LABEL_FALLBACK; exports.renderLabelExpression = renderLabelExpression; exports.isLabelExpression = isLabelExpression; exports.extractAttributeNames = extractAttributeNames; exports.enrichValuesForDisplay = enrichValuesForDisplay; exports.enrichValuesWithSelectLabels = enrichValuesWithSelectLabels; exports.extractRelationIds = extractRelationIds; exports.computeLabelWithRelations = computeLabelWithRelations; exports.createMockAdapter = createMockAdapter; exports.PolicyRegistry = PolicyRegistry; exports.defaultPolicyRegistry = defaultPolicyRegistry; exports.notesPolicy = notesPolicy; exports.BaseService = BaseService; exports.BaseRepository = BaseRepository; exports.SchemaContextAwareRepository = SchemaContextAwareRepository; exports.buildAuditChanges = buildAuditChanges; exports.ObjectSchemaService = ObjectSchemaService; exports.AuditService = AuditService; exports.UserService = UserService; exports.applyDefaultValues = applyDefaultValues; exports.checkPermission = checkPermission; exports.getPolicy = getPolicy; exports.buildPolicyContext = buildPolicyContext; exports.checkRecordAccess = checkRecordAccess; exports.checkRecordModifyOrThrow = checkRecordModifyOrThrow; exports.checkRecordDeleteOrThrow = checkRecordDeleteOrThrow; exports.checkSharedObjectWriteAccess = checkSharedObjectWriteAccess; exports.computeLabel = computeLabel; exports.enrichWithFormulas = enrichWithFormulas; exports.enrichRecordsWithFormulas = enrichRecordsWithFormulas; exports.createContextForCreate = createContextForCreate; exports.createContextForUpdate = createContextForUpdate; exports.createContextForDelete = createContextForDelete; exports.createContextForRestore = createContextForRestore; exports.recalculateParentRollups = recalculateParentRollups; exports.RecordQueryService = RecordQueryService; exports.RecordResolverService = RecordResolverService; exports.RelationService = RelationService; exports.RollupService = RollupService; exports.RecordService = RecordService; exports.FormulaResolverService = FormulaResolverService; exports.RollupScheduler = RollupScheduler; exports.DocumentRenderError = DocumentRenderError; exports.StorageDownloadNotSupportedError = StorageDownloadNotSupportedError; exports.DocumentRendererService = DocumentRendererService; exports.DocumentProcessingHook = DocumentProcessingHook; exports.GrantNotFoundError = GrantNotFoundError; exports.GrantExpiredError = GrantExpiredError; exports.GrantRevokedError = GrantRevokedError; exports.TokenRevokedError = TokenRevokedError; exports.WorkflowAccessGrantService = WorkflowAccessGrantService; exports.WorkflowInstanceService = WorkflowInstanceService; exports.InvitationNotFoundError = InvitationNotFoundError; exports.InvitationExpiredError = InvitationExpiredError; exports.InvitationAlreadyAcceptedError = InvitationAlreadyAcceptedError; exports.InvitationRevokedError = InvitationRevokedError; exports.WorkflowInvitationService = WorkflowInvitationService; exports.WorkflowRelationService = WorkflowRelationService; exports.WorkflowService = WorkflowService; exports.UserProfileService = UserProfileService; exports.DocumentGenerationTemplateNotFoundError = DocumentGenerationTemplateNotFoundError; exports.DocumentGenerationNotConfiguredError = DocumentGenerationNotConfiguredError; exports.DocumentGenerationService = DocumentGenerationService; exports.DocumentTemplateService = DocumentTemplateService; exports.DocumentService = DocumentService; exports.DocumentProcessingService = DocumentProcessingService; exports.FileService = FileService; exports.GeocodingService = GeocodingService; exports.GlobalSearchService = GlobalSearchService; exports.PermissionService = PermissionService; exports.ViewService = ViewService; exports.seedRegistryViews = seedRegistryViews; exports.syncNativeViews = syncNativeViews; exports.verifyRegistryViewsSeeded = verifyRegistryViewsSeeded; exports.verifyNativeViewsSync = verifyNativeViewsSync; exports.getViewSeedPreview = getViewSeedPreview; exports.getViewSyncPreview = getViewSyncPreview; exports.syncNativeObjects = syncNativeObjects; exports.verifyNativeObjectsSync = verifyNativeObjectsSync; exports.getSyncPreview = getSyncPreview; exports.syncAll = syncAll;