@donotdev/functions 0.0.15 → 0.0.16

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.
@@ -11,59 +11,6 @@ var __export = (target, all) => {
11
11
  __defProp(target, name, { get: all[name], enumerable: true });
12
12
  };
13
13
 
14
- // ../core/utils/src/common/arrayTranslations.ts
15
- var init_arrayTranslations = __esm({
16
- '../core/utils/src/common/arrayTranslations.ts'() {
17
- 'use strict';
18
- },
19
- });
20
-
21
- // ../core/utils/src/common/createMetadata.ts
22
- var init_createMetadata = __esm({
23
- '../core/utils/src/common/createMetadata.ts'() {
24
- 'use strict';
25
- },
26
- });
27
-
28
- // ../core/utils/src/common/dateUtils.ts
29
- var init_dateUtils = __esm({
30
- '../core/utils/src/common/dateUtils.ts'() {
31
- 'use strict';
32
- },
33
- });
34
-
35
- // ../core/types/src/auth/constants.ts
36
- var USER_ROLES, SUBSCRIPTION_TIERS, FEATURES, PERMISSIONS;
37
- var init_constants = __esm({
38
- '../core/types/src/auth/constants.ts'() {
39
- 'use strict';
40
- USER_ROLES = {
41
- GUEST: 'guest',
42
- USER: 'user',
43
- ADMIN: 'admin',
44
- SUPER: 'super',
45
- };
46
- SUBSCRIPTION_TIERS = {
47
- FREE: 'free',
48
- PRO: 'pro',
49
- PREMIUM: 'premium',
50
- };
51
- FEATURES = {
52
- BASIC_ACCESS: 'basic_access',
53
- ADVANCED_FEATURES: 'advanced_features',
54
- API_ACCESS: 'api_access',
55
- PRIORITY_SUPPORT: 'priority_support',
56
- };
57
- PERMISSIONS = {
58
- READ_PUBLIC: 'read_public',
59
- READ_OWN_DATA: 'read_own_data',
60
- WRITE_OWN_DATA: 'write_own_data',
61
- READ_ALL_DATA: 'read_all_data',
62
- MANAGE_USERS: 'manage_users',
63
- };
64
- },
65
- });
66
-
67
14
  // ../../node_modules/.bun/valibot@1.2.0+1fb4c65d43e298b9/node_modules/valibot/dist/index.mjs
68
15
  // @__NO_SIDE_EFFECTS__
69
16
  function getGlobalConfig(config$1) {
@@ -430,6 +377,26 @@ function boolean(message$1) {
430
377
  };
431
378
  }
432
379
  // @__NO_SIDE_EFFECTS__
380
+ function custom(check$1, message$1) {
381
+ return {
382
+ kind: 'schema',
383
+ type: 'custom',
384
+ reference: custom,
385
+ expects: 'unknown',
386
+ async: false,
387
+ check: check$1,
388
+ message: message$1,
389
+ get '~standard'() {
390
+ return /* @__PURE__ */ _getStandardProps(this);
391
+ },
392
+ '~run'(dataset, config$1) {
393
+ if (this.check(dataset.value)) dataset.typed = true;
394
+ else _addIssue(this, 'type', dataset, config$1);
395
+ return dataset;
396
+ },
397
+ };
398
+ }
399
+ // @__NO_SIDE_EFFECTS__
433
400
  function literal(literal_, message$1) {
434
401
  return {
435
402
  kind: 'schema',
@@ -586,6 +553,32 @@ function nullable(wrapped, default_) {
586
553
  };
587
554
  }
588
555
  // @__NO_SIDE_EFFECTS__
556
+ function nullish(wrapped, default_) {
557
+ return {
558
+ kind: 'schema',
559
+ type: 'nullish',
560
+ reference: nullish,
561
+ expects: `(${wrapped.expects} | null | undefined)`,
562
+ async: false,
563
+ wrapped,
564
+ default: default_,
565
+ get '~standard'() {
566
+ return /* @__PURE__ */ _getStandardProps(this);
567
+ },
568
+ '~run'(dataset, config$1) {
569
+ if (dataset.value === null || dataset.value === void 0) {
570
+ if (this.default !== void 0)
571
+ dataset.value = /* @__PURE__ */ getDefault(this, dataset, config$1);
572
+ if (dataset.value === null || dataset.value === void 0) {
573
+ dataset.typed = true;
574
+ return dataset;
575
+ }
576
+ }
577
+ return this.wrapped['~run'](dataset, config$1);
578
+ },
579
+ };
580
+ }
581
+ // @__NO_SIDE_EFFECTS__
589
582
  function number(message$1) {
590
583
  return {
591
584
  kind: 'schema',
@@ -1159,10 +1152,12 @@ var init_dist = __esm({
1159
1152
  __name(any, 'any');
1160
1153
  __name(array, 'array');
1161
1154
  __name(boolean, 'boolean');
1155
+ __name(custom, 'custom');
1162
1156
  __name(literal, 'literal');
1163
1157
  __name(looseObject, 'looseObject');
1164
1158
  __name(never, 'never');
1165
1159
  __name(nullable, 'nullable');
1160
+ __name(nullish, 'nullish');
1166
1161
  __name(number, 'number');
1167
1162
  __name(object, 'object');
1168
1163
  __name(optional, 'optional');
@@ -1180,6 +1175,66 @@ var init_dist = __esm({
1180
1175
  },
1181
1176
  });
1182
1177
 
1178
+ // ../core/utils/src/common/arrayTranslations.ts
1179
+ var init_arrayTranslations = __esm({
1180
+ '../core/utils/src/common/arrayTranslations.ts'() {
1181
+ 'use strict';
1182
+ },
1183
+ });
1184
+
1185
+ // ../core/utils/src/common/createMetadata.ts
1186
+ var init_createMetadata = __esm({
1187
+ '../core/utils/src/common/createMetadata.ts'() {
1188
+ 'use strict';
1189
+ },
1190
+ });
1191
+
1192
+ // ../core/utils/src/common/currencyFormat.ts
1193
+ var init_currencyFormat = __esm({
1194
+ '../core/utils/src/common/currencyFormat.ts'() {
1195
+ 'use strict';
1196
+ },
1197
+ });
1198
+
1199
+ // ../core/utils/src/common/dateUtils.ts
1200
+ var init_dateUtils = __esm({
1201
+ '../core/utils/src/common/dateUtils.ts'() {
1202
+ 'use strict';
1203
+ },
1204
+ });
1205
+
1206
+ // ../core/types/src/auth/constants.ts
1207
+ var USER_ROLES, SUBSCRIPTION_TIERS, FEATURES, PERMISSIONS;
1208
+ var init_constants = __esm({
1209
+ '../core/types/src/auth/constants.ts'() {
1210
+ 'use strict';
1211
+ USER_ROLES = {
1212
+ GUEST: 'guest',
1213
+ USER: 'user',
1214
+ ADMIN: 'admin',
1215
+ SUPER: 'super',
1216
+ };
1217
+ SUBSCRIPTION_TIERS = {
1218
+ FREE: 'free',
1219
+ PRO: 'pro',
1220
+ PREMIUM: 'premium',
1221
+ };
1222
+ FEATURES = {
1223
+ BASIC_ACCESS: 'basic_access',
1224
+ ADVANCED_FEATURES: 'advanced_features',
1225
+ API_ACCESS: 'api_access',
1226
+ PRIORITY_SUPPORT: 'priority_support',
1227
+ };
1228
+ PERMISSIONS = {
1229
+ READ_PUBLIC: 'read_public',
1230
+ READ_OWN_DATA: 'read_own_data',
1231
+ WRITE_OWN_DATA: 'write_own_data',
1232
+ READ_ALL_DATA: 'read_all_data',
1233
+ MANAGE_USERS: 'manage_users',
1234
+ };
1235
+ },
1236
+ });
1237
+
1183
1238
  // ../core/types/src/billing/constants.ts
1184
1239
  var SUBSCRIPTION_STATUS, STRIPE_MODES, DEFAULT_SUBSCRIPTION;
1185
1240
  var init_constants2 = __esm({
@@ -1487,6 +1542,13 @@ var init_aggregate = __esm({
1487
1542
  },
1488
1543
  });
1489
1544
 
1545
+ // ../core/types/src/crud/components.ts
1546
+ var init_components = __esm({
1547
+ '../core/types/src/crud/components.ts'() {
1548
+ 'use strict';
1549
+ },
1550
+ });
1551
+
1490
1552
  // ../core/types/src/crud/constants.ts
1491
1553
  var init_constants3 = __esm({
1492
1554
  '../core/types/src/crud/constants.ts'() {
@@ -1567,6 +1629,7 @@ var init_crud = __esm({
1567
1629
  '../core/types/src/crud/index.ts'() {
1568
1630
  'use strict';
1569
1631
  init_aggregate();
1632
+ init_components();
1570
1633
  init_schemas3();
1571
1634
  init_types3();
1572
1635
  },
@@ -3314,6 +3377,13 @@ var init_errors2 = __esm({
3314
3377
  },
3315
3378
  });
3316
3379
 
3380
+ // ../core/utils/src/common/generateFirestoreRuleCondition.ts
3381
+ var init_generateFirestoreRuleCondition = __esm({
3382
+ '../core/utils/src/common/generateFirestoreRuleCondition.ts'() {
3383
+ 'use strict';
3384
+ },
3385
+ });
3386
+
3317
3387
  // ../core/utils/src/common/maybeTranslate.ts
3318
3388
  var init_maybeTranslate = __esm({
3319
3389
  '../core/utils/src/common/maybeTranslate.ts'() {
@@ -3435,9 +3505,19 @@ function isFieldVisible(visibility, userRole) {
3435
3505
  if (level === 'technical') {
3436
3506
  return hasRoleAccess(userRole, 'admin');
3437
3507
  }
3508
+ if (level === 'owner') {
3509
+ return false;
3510
+ }
3438
3511
  return hasRoleAccess(userRole, level);
3439
3512
  }
3440
- function getVisibleFields(schema, userRole) {
3513
+ function isOwnerVisible(documentData, uid, ownership) {
3514
+ for (const field of ownership.ownerFields) {
3515
+ const value = documentData[field];
3516
+ if (value === uid) return true;
3517
+ }
3518
+ return false;
3519
+ }
3520
+ function getVisibleFields(schema, userRole, options) {
3441
3521
  const schemaAny = schema;
3442
3522
  if (!schemaAny || typeof schemaAny !== 'object' || !schemaAny.entries) {
3443
3523
  console.warn(
@@ -3447,8 +3527,18 @@ function getVisibleFields(schema, userRole) {
3447
3527
  }
3448
3528
  const entries = schemaAny.entries;
3449
3529
  const visibleFieldNames = [];
3530
+ const { documentData, uid, ownership } = options ?? {};
3531
+ const showOwnerFields =
3532
+ ownership &&
3533
+ uid != null &&
3534
+ documentData &&
3535
+ isOwnerVisible(documentData, uid, ownership);
3450
3536
  for (const [key, field] of Object.entries(entries)) {
3451
3537
  const visibility = getFieldVisibility(field);
3538
+ if (visibility === 'owner') {
3539
+ if (showOwnerFields) visibleFieldNames.push(key);
3540
+ continue;
3541
+ }
3452
3542
  if (isFieldVisible(visibility, userRole)) {
3453
3543
  visibleFieldNames.push(key);
3454
3544
  }
@@ -3462,16 +3552,29 @@ var init_getVisibleFields = __esm({
3462
3552
  __name(hasVisibility, 'hasVisibility');
3463
3553
  __name(getFieldVisibility, 'getFieldVisibility');
3464
3554
  __name(isFieldVisible, 'isFieldVisible');
3555
+ __name(isOwnerVisible, 'isOwnerVisible');
3465
3556
  __name(getVisibleFields, 'getVisibleFields');
3466
3557
  },
3467
3558
  });
3468
3559
 
3469
3560
  // ../core/utils/src/common/schema/filterVisibleFields.ts
3470
- function filterVisibleFields(data, schema, userRole) {
3561
+ function filterVisibleFields(data, schema, userRole, options) {
3471
3562
  if (!data) {
3472
3563
  return {};
3473
3564
  }
3474
- const visibleFieldNames = getVisibleFields(schema, userRole);
3565
+ const visibilityOptions =
3566
+ options?.uid != null && options?.ownership != null
3567
+ ? {
3568
+ documentData: options.documentData ?? data,
3569
+ uid: options.uid,
3570
+ ownership: options.ownership,
3571
+ }
3572
+ : void 0;
3573
+ const visibleFieldNames = getVisibleFields(
3574
+ schema,
3575
+ userRole,
3576
+ visibilityOptions
3577
+ );
3475
3578
  const result = {};
3476
3579
  for (const key of visibleFieldNames) {
3477
3580
  if (Object.prototype.hasOwnProperty.call(data, key)) {
@@ -3503,8 +3606,10 @@ var init_common2 = __esm({
3503
3606
  'use strict';
3504
3607
  init_arrayTranslations();
3505
3608
  init_createMetadata();
3609
+ init_currencyFormat();
3506
3610
  init_dateUtils();
3507
3611
  init_errors2();
3612
+ init_generateFirestoreRuleCondition();
3508
3613
  init_maybeTranslate();
3509
3614
  init_pkce();
3510
3615
  init_gracefulInit();
@@ -3548,17 +3653,13 @@ var init_server = __esm({
3548
3653
  },
3549
3654
  });
3550
3655
 
3551
- // ../core/schemas/src/common/validation/enhanceSchema.ts
3552
- var init_enhanceSchema = __esm({
3553
- '../core/schemas/src/common/validation/enhanceSchema.ts'() {
3554
- 'use strict';
3555
- },
3556
- });
3557
-
3558
3656
  // ../core/schemas/src/common/validation/getSchemaType.ts
3559
3657
  function registerSchemaGenerator(type, generator) {
3560
3658
  schemaRegistry.set(type, generator);
3561
3659
  }
3660
+ function applyRequired(schema, required) {
3661
+ return required ? schema : nullish(schema);
3662
+ }
3562
3663
  function registerBuiltinSchemas() {
3563
3664
  registerSchemaGenerator('text', textSchema);
3564
3665
  registerSchemaGenerator('textarea', textSchema);
@@ -3568,10 +3669,17 @@ function registerBuiltinSchemas() {
3568
3669
  registerSchemaGenerator('password', passwordSchema);
3569
3670
  registerSchemaGenerator('url', urlSchema);
3570
3671
  registerSchemaGenerator('tel', telSchema);
3672
+ registerSchemaGenerator('iban', ibanSchema);
3571
3673
  registerSchemaGenerator('number', numberSchema);
3674
+ registerSchemaGenerator('currency', numberSchema);
3675
+ registerSchemaGenerator('price', priceSchema);
3572
3676
  registerSchemaGenerator('range', numberSchema);
3677
+ registerSchemaGenerator('year', numberSchema);
3678
+ registerSchemaGenerator('rating', numberSchema);
3679
+ registerSchemaGenerator('duration', numberSchema);
3573
3680
  registerSchemaGenerator('boolean', booleanSchema);
3574
3681
  registerSchemaGenerator('checkbox', booleanSchema);
3682
+ registerSchemaGenerator('gdprConsent', gdprConsentSchema);
3575
3683
  registerSchemaGenerator('date', dateSchema);
3576
3684
  registerSchemaGenerator('datetime-local', dateSchema);
3577
3685
  registerSchemaGenerator('time', dateSchema);
@@ -3591,6 +3699,8 @@ function registerBuiltinSchemas() {
3591
3699
  registerSchemaGenerator('select', selectSchema);
3592
3700
  registerSchemaGenerator('multiselect', multiselectSchema);
3593
3701
  registerSchemaGenerator('radio', selectSchema);
3702
+ registerSchemaGenerator('combobox', selectSchema);
3703
+ registerSchemaGenerator('switch', switchSchema);
3594
3704
  registerSchemaGenerator('reference', referenceSchema);
3595
3705
  registerSchemaGenerator('hidden', stringSchema);
3596
3706
  registerSchemaGenerator('avatar', stringSchema);
@@ -3599,13 +3709,17 @@ function registerBuiltinSchemas() {
3599
3709
  registerSchemaGenerator('reset', neverSchema);
3600
3710
  }
3601
3711
  function getSchemaType(field) {
3712
+ if (field.validation?.schema) {
3713
+ const customSchema = field.validation.schema;
3714
+ return applyRequired(customSchema, field.validation?.required);
3715
+ }
3602
3716
  const generator = schemaRegistry.get(field.type);
3603
3717
  if (generator) {
3604
3718
  const schema2 = generator(field);
3605
3719
  if (schema2 !== null) return schema2;
3606
3720
  }
3607
3721
  const schema = unknown();
3608
- return field.validation?.required ? schema : optional(schema);
3722
+ return applyRequired(schema, field.validation?.required);
3609
3723
  }
3610
3724
  var schemaRegistry,
3611
3725
  textSchema,
@@ -3630,7 +3744,11 @@ var schemaRegistry,
3630
3744
  referenceSchema,
3631
3745
  stringSchema,
3632
3746
  telSchema,
3633
- neverSchema;
3747
+ ibanSchema,
3748
+ neverSchema,
3749
+ switchSchema,
3750
+ gdprConsentSchema,
3751
+ priceSchema;
3634
3752
  var init_getSchemaType = __esm({
3635
3753
  '../core/schemas/src/common/validation/getSchemaType.ts'() {
3636
3754
  'use strict';
@@ -3638,6 +3756,7 @@ var init_getSchemaType = __esm({
3638
3756
  init_src();
3639
3757
  schemaRegistry = /* @__PURE__ */ new Map();
3640
3758
  __name(registerSchemaGenerator, 'registerSchemaGenerator');
3759
+ __name(applyRequired, 'applyRequired');
3641
3760
  textSchema = /* @__PURE__ */ __name((field) => {
3642
3761
  const validations = [];
3643
3762
  if (field.validation?.minLength !== void 0) {
@@ -3663,11 +3782,11 @@ var init_getSchemaType = __esm({
3663
3782
  }
3664
3783
  const schema =
3665
3784
  validations.length > 0 ? pipe(string(), ...validations) : string();
3666
- return field.validation?.required ? schema : optional(schema);
3785
+ return applyRequired(schema, field.validation?.required);
3667
3786
  }, 'textSchema');
3668
3787
  emailSchema = /* @__PURE__ */ __name((field) => {
3669
3788
  const schema = pipe(string(), email('Invalid email address'));
3670
- return field.validation?.required ? schema : optional(schema);
3789
+ return applyRequired(schema, field.validation?.required);
3671
3790
  }, 'emailSchema');
3672
3791
  passwordSchema = /* @__PURE__ */ __name((field) => {
3673
3792
  const schema =
@@ -3680,11 +3799,11 @@ var init_getSchemaType = __esm({
3680
3799
  )
3681
3800
  )
3682
3801
  : string();
3683
- return field.validation?.required ? schema : optional(schema);
3802
+ return applyRequired(schema, field.validation?.required);
3684
3803
  }, 'passwordSchema');
3685
3804
  urlSchema = /* @__PURE__ */ __name((field) => {
3686
3805
  const schema = pipe(string(), url('Invalid URL'));
3687
- return field.validation?.required ? schema : optional(schema);
3806
+ return applyRequired(schema, field.validation?.required);
3688
3807
  }, 'urlSchema');
3689
3808
  numberSchema = /* @__PURE__ */ __name((field) => {
3690
3809
  const validations = [];
@@ -3706,30 +3825,30 @@ var init_getSchemaType = __esm({
3706
3825
  }
3707
3826
  const schema =
3708
3827
  validations.length > 0 ? pipe(number(), ...validations) : number();
3709
- return field.validation?.required ? schema : optional(schema);
3828
+ return applyRequired(schema, field.validation?.required);
3710
3829
  }, 'numberSchema');
3711
3830
  booleanSchema = /* @__PURE__ */ __name((field) => {
3712
3831
  const schema = boolean();
3713
- return field.validation?.required ? schema : optional(schema);
3832
+ return applyRequired(schema, field.validation?.required);
3714
3833
  }, 'booleanSchema');
3715
3834
  dateSchema = /* @__PURE__ */ __name((field) => {
3716
3835
  const schema = pipe(string(), isoTimestamp('Invalid date format'));
3717
- return field.validation?.required ? schema : optional(schema);
3836
+ return applyRequired(schema, field.validation?.required);
3718
3837
  }, 'dateSchema');
3719
3838
  fileAssetObjectSchema = object({
3720
3839
  url: string(),
3721
3840
  filename: string(),
3722
3841
  size: number(),
3723
- mimeType: optional(string()),
3724
- uploadedAt: optional(string()),
3842
+ mimeType: nullish(string()),
3843
+ uploadedAt: nullish(string()),
3725
3844
  });
3726
3845
  fileSchema = /* @__PURE__ */ __name((field) => {
3727
3846
  const schema = nullable(fileAssetObjectSchema);
3728
- return field.validation?.required ? schema : optional(schema);
3847
+ return applyRequired(schema, field.validation?.required);
3729
3848
  }, 'fileSchema');
3730
3849
  filesSchema = /* @__PURE__ */ __name((field) => {
3731
3850
  const schema = array(fileAssetObjectSchema);
3732
- return field.validation?.required ? schema : optional(schema);
3851
+ return applyRequired(schema, field.validation?.required);
3733
3852
  }, 'filesSchema');
3734
3853
  pictureObjectSchema = object({
3735
3854
  fullUrl: string(),
@@ -3737,126 +3856,149 @@ var init_getSchemaType = __esm({
3737
3856
  });
3738
3857
  pictureSchema = /* @__PURE__ */ __name((field) => {
3739
3858
  const schema = pictureObjectSchema;
3740
- return field.validation?.required ? schema : optional(schema);
3859
+ return applyRequired(schema, field.validation?.required);
3741
3860
  }, 'pictureSchema');
3742
3861
  picturesSchema = /* @__PURE__ */ __name((field) => {
3743
3862
  const schema = array(pictureObjectSchema);
3744
- return field.validation?.required ? schema : optional(schema);
3863
+ return applyRequired(schema, field.validation?.required);
3745
3864
  }, 'picturesSchema');
3746
3865
  geopointSchema = /* @__PURE__ */ __name((field) => {
3747
3866
  const schema = object({ lat: number(), lng: number() });
3748
- return field.validation?.required ? schema : optional(schema);
3867
+ return applyRequired(schema, field.validation?.required);
3749
3868
  }, 'geopointSchema');
3750
3869
  addressSchema = /* @__PURE__ */ __name((field) => {
3751
3870
  const schema = object({
3752
3871
  formatted_address: string(),
3753
3872
  latitude: number(),
3754
3873
  longitude: number(),
3755
- street_number: optional(string()),
3756
- route: optional(string()),
3757
- locality: optional(string()),
3758
- administrative_area_level_1: optional(string()),
3759
- administrative_area_level_2: optional(string()),
3760
- country: optional(string()),
3761
- postal_code: optional(string()),
3874
+ street_number: nullish(string()),
3875
+ route: nullish(string()),
3876
+ locality: nullish(string()),
3877
+ administrative_area_level_1: nullish(string()),
3878
+ administrative_area_level_2: nullish(string()),
3879
+ country: nullish(string()),
3880
+ postal_code: nullish(string()),
3762
3881
  });
3763
- return field.validation?.required ? schema : optional(schema);
3882
+ return applyRequired(schema, field.validation?.required);
3764
3883
  }, 'addressSchema');
3765
3884
  mapSchema = /* @__PURE__ */ __name((field) => {
3766
3885
  const schema = record(string(), unknown());
3767
- return field.validation?.required ? schema : optional(schema);
3886
+ return applyRequired(schema, field.validation?.required);
3768
3887
  }, 'mapSchema');
3769
3888
  arraySchema = /* @__PURE__ */ __name((field) => {
3770
3889
  const schema = array(unknown());
3771
- return field.validation?.required ? schema : optional(schema);
3890
+ return applyRequired(schema, field.validation?.required);
3772
3891
  }, 'arraySchema');
3773
3892
  selectSchema = /* @__PURE__ */ __name((field) => {
3774
3893
  const options = field.validation?.options;
3775
3894
  if (Array.isArray(options) && options.length > 0) {
3776
3895
  const values = options.map((opt) => opt.value);
3777
3896
  const schema2 = picklist(values);
3778
- return field.validation?.required ? schema2 : optional(schema2);
3897
+ return applyRequired(schema2, field.validation?.required);
3779
3898
  }
3780
- const schema = string();
3781
- return field.validation?.required ? schema : optional(schema);
3899
+ const schema = union([string(), number()]);
3900
+ return applyRequired(schema, field.validation?.required);
3782
3901
  }, 'selectSchema');
3783
3902
  multiselectSchema = /* @__PURE__ */ __name((field) => {
3784
3903
  const options = field.validation?.options;
3785
3904
  if (Array.isArray(options) && options.length > 0) {
3786
3905
  const values = options.map((opt) => opt.value);
3787
3906
  const schema2 = array(picklist(values));
3788
- return field.validation?.required ? schema2 : optional(schema2);
3907
+ return applyRequired(schema2, field.validation?.required);
3789
3908
  }
3790
3909
  const schema = array(string());
3791
- return field.validation?.required ? schema : optional(schema);
3910
+ return applyRequired(schema, field.validation?.required);
3792
3911
  }, 'multiselectSchema');
3793
3912
  referenceSchema = /* @__PURE__ */ __name((field) => {
3794
3913
  const schema = pipe(
3795
3914
  string(),
3796
3915
  regex(FIRESTORE_ID_PATTERN, 'Invalid ID format')
3797
3916
  );
3798
- return field.validation?.required ? schema : optional(schema);
3917
+ return applyRequired(schema, field.validation?.required);
3799
3918
  }, 'referenceSchema');
3800
3919
  stringSchema = /* @__PURE__ */ __name((field) => {
3801
3920
  const schema = string();
3802
- return field.validation?.required ? schema : optional(schema);
3921
+ return applyRequired(schema, field.validation?.required);
3803
3922
  }, 'stringSchema');
3804
3923
  telSchema = /* @__PURE__ */ __name((field) => {
3805
3924
  const schema = string();
3806
- return field.validation?.required ? schema : optional(schema);
3925
+ return applyRequired(schema, field.validation?.required);
3807
3926
  }, 'telSchema');
3927
+ ibanSchema = /* @__PURE__ */ __name((field) => {
3928
+ const minLength2 = field.validation?.minLength ?? 15;
3929
+ const maxLength2 = field.validation?.maxLength ?? 34;
3930
+ const pattern =
3931
+ field.validation?.pattern ?? '^[A-Z]{2}[0-9]{2}[A-Z0-9]{4,34}$';
3932
+ const validations = [];
3933
+ if (minLength2 !== void 0) {
3934
+ validations.push(
3935
+ minLength(
3936
+ minLength2,
3937
+ `IBAN must be at least ${minLength2} characters`
3938
+ )
3939
+ );
3940
+ }
3941
+ if (maxLength2 !== void 0) {
3942
+ validations.push(
3943
+ maxLength(maxLength2, `IBAN must not exceed ${maxLength2} characters`)
3944
+ );
3945
+ }
3946
+ if (pattern) {
3947
+ const regex2 =
3948
+ typeof pattern === 'string' ? new RegExp(pattern) : pattern;
3949
+ validations.push(regex(regex2, 'Invalid IBAN format'));
3950
+ }
3951
+ const schema =
3952
+ validations.length > 0 ? pipe(string(), ...validations) : string();
3953
+ return applyRequired(schema, field.validation?.required);
3954
+ }, 'ibanSchema');
3808
3955
  neverSchema = /* @__PURE__ */ __name(() => never(), 'neverSchema');
3956
+ switchSchema = /* @__PURE__ */ __name((field) => {
3957
+ const fieldSpecific = field.options?.fieldSpecific;
3958
+ if (fieldSpecific?.checkedValue && fieldSpecific?.uncheckedValue) {
3959
+ const values = [
3960
+ fieldSpecific.checkedValue,
3961
+ fieldSpecific.uncheckedValue,
3962
+ ];
3963
+ const schema2 = picklist(values);
3964
+ return applyRequired(schema2, field.validation?.required);
3965
+ }
3966
+ const schema = boolean();
3967
+ return applyRequired(schema, field.validation?.required);
3968
+ }, 'switchSchema');
3969
+ gdprConsentSchema = /* @__PURE__ */ __name((field) => {
3970
+ const baseSchema = custom((input) => {
3971
+ if (field.validation?.required) {
3972
+ if (typeof input === 'object' && input !== null) {
3973
+ return input.gdprConsent === true;
3974
+ }
3975
+ return false;
3976
+ }
3977
+ if (input === false || input === null || input === void 0) {
3978
+ return true;
3979
+ }
3980
+ if (typeof input === 'object' && input !== null) {
3981
+ return input.gdprConsent === true;
3982
+ }
3983
+ return false;
3984
+ }, 'GDPR consent must be given');
3985
+ return baseSchema;
3986
+ }, 'gdprConsentSchema');
3987
+ priceSchema = /* @__PURE__ */ __name((field) => {
3988
+ const schema = object({
3989
+ amount: number(),
3990
+ currency: optional(string()),
3991
+ vatIncluded: optional(boolean()),
3992
+ discountPercent: optional(pipe(number(), minValue(0), maxValue(100))),
3993
+ });
3994
+ return applyRequired(schema, field.validation?.required);
3995
+ }, 'priceSchema');
3809
3996
  __name(registerBuiltinSchemas, 'registerBuiltinSchemas');
3810
3997
  registerBuiltinSchemas();
3811
3998
  __name(getSchemaType, 'getSchemaType');
3812
3999
  },
3813
4000
  });
3814
4001
 
3815
- // ../core/schemas/src/common/validation/validateDates.ts
3816
- var init_validateDates = __esm({
3817
- '../core/schemas/src/common/validation/validateDates.ts'() {
3818
- 'use strict';
3819
- init_server();
3820
- },
3821
- });
3822
-
3823
- // ../core/schemas/src/common/validation/validateUniqueFields.ts
3824
- var init_validateUniqueFields = __esm({
3825
- '../core/schemas/src/common/validation/validateUniqueFields.ts'() {
3826
- 'use strict';
3827
- init_server();
3828
- },
3829
- });
3830
-
3831
- // ../core/schemas/src/common/validation/validateDocument.ts
3832
- var init_validateDocument = __esm({
3833
- '../core/schemas/src/common/validation/validateDocument.ts'() {
3834
- 'use strict';
3835
- init_validateDates();
3836
- init_validateUniqueFields();
3837
- },
3838
- });
3839
-
3840
- // ../core/schemas/src/common/validation/index.ts
3841
- var init_validation2 = __esm({
3842
- '../core/schemas/src/common/validation/index.ts'() {
3843
- 'use strict';
3844
- init_enhanceSchema();
3845
- init_getSchemaType();
3846
- init_validateDates();
3847
- init_validateDocument();
3848
- init_validateUniqueFields();
3849
- },
3850
- });
3851
-
3852
- // ../core/schemas/src/common/utils.ts
3853
- var init_utils2 = __esm({
3854
- '../core/schemas/src/common/utils.ts'() {
3855
- 'use strict';
3856
- init_server();
3857
- },
3858
- });
3859
-
3860
4002
  // ../core/schemas/src/common/visibility.ts
3861
4003
  var DEFAULT_STATUS_OPTIONS,
3862
4004
  DEFAULT_STATUS_VALUE,
@@ -3869,9 +4011,9 @@ var init_visibility = __esm({
3869
4011
  'use strict';
3870
4012
  init_src();
3871
4013
  DEFAULT_STATUS_OPTIONS = [
3872
- { value: 'draft', label: 'dndev:status.draft' },
3873
- { value: 'available', label: 'dndev:status.available' },
3874
- { value: 'deleted', label: 'dndev:status.deleted' },
4014
+ { value: 'draft', label: 'crud:status.draft' },
4015
+ { value: 'available', label: 'crud:status.available' },
4016
+ { value: 'deleted', label: 'crud:status.deleted' },
3875
4017
  ];
3876
4018
  DEFAULT_STATUS_VALUE = 'available';
3877
4019
  HIDDEN_STATUSES = ['draft', 'deleted'];
@@ -3893,57 +4035,60 @@ var init_visibility = __esm({
3893
4035
  // Framework-enforced, user-settable (NOT backend-generated)
3894
4036
  ];
3895
4037
  baseFields = {
4038
+ status: {
4039
+ name: 'status',
4040
+ type: 'select',
4041
+ visibility: 'admin',
4042
+ label: 'crud:fields.status',
4043
+ editable: 'admin',
4044
+ // REQUIRED: Status must be editable to be included in forms
4045
+ validation: {
4046
+ required: true,
4047
+ options: [...DEFAULT_STATUS_OPTIONS],
4048
+ },
4049
+ },
3896
4050
  id: {
4051
+ name: 'id',
3897
4052
  type: 'text',
3898
- visibility: 'technical',
4053
+ visibility: 'hidden',
4054
+ label: 'crud:fields.id',
3899
4055
  validation: {
3900
4056
  required: true,
3901
4057
  pattern: FIRESTORE_ID_PATTERN.source,
3902
4058
  },
3903
4059
  },
3904
4060
  createdAt: {
4061
+ name: '_createdAt',
3905
4062
  type: 'timestamp',
3906
4063
  visibility: 'technical',
4064
+ label: 'crud:fields._createdAt',
3907
4065
  validation: { required: true },
3908
4066
  },
3909
4067
  updatedAt: {
4068
+ name: '_updatedAt',
3910
4069
  type: 'timestamp',
3911
4070
  visibility: 'technical',
4071
+ label: 'crud:fields._updatedAt',
3912
4072
  validation: { required: true },
3913
4073
  },
3914
4074
  createdById: {
4075
+ name: '_createdById',
3915
4076
  type: 'reference',
3916
4077
  visibility: 'technical',
4078
+ label: 'crud:fields._createdById',
3917
4079
  validation: { required: true },
3918
4080
  },
3919
4081
  updatedById: {
4082
+ name: '_updatedById',
3920
4083
  type: 'reference',
3921
4084
  visibility: 'technical',
4085
+ label: 'crud:fields._updatedById',
3922
4086
  validation: { required: true },
3923
4087
  },
3924
- status: {
3925
- type: 'select',
3926
- visibility: 'admin',
3927
- editable: 'admin',
3928
- // REQUIRED: Status must be editable to be included in forms
3929
- validation: {
3930
- required: true,
3931
- options: [...DEFAULT_STATUS_OPTIONS],
3932
- },
3933
- },
3934
4088
  };
3935
4089
  },
3936
4090
  });
3937
4091
 
3938
- // ../core/schemas/src/common/defineEntity.ts
3939
- var init_defineEntity = __esm({
3940
- '../core/schemas/src/common/defineEntity.ts'() {
3941
- 'use strict';
3942
- init_server();
3943
- init_visibility();
3944
- },
3945
- });
3946
-
3947
4092
  // ../core/schemas/src/common/createSchema.ts
3948
4093
  function withVisibility(schema, visibility) {
3949
4094
  return Object.assign(schema, { visibility });
@@ -3953,6 +4098,8 @@ function withMetadata(schema, entity) {
3953
4098
  enhanced.metadata = {
3954
4099
  collection: entity.collection,
3955
4100
  entity: entity.name,
4101
+ // Propagate uniqueKeys for backend CRUD functions
4102
+ ...(entity.uniqueKeys && { uniqueKeys: entity.uniqueKeys }),
3956
4103
  };
3957
4104
  return enhanced;
3958
4105
  }
@@ -4008,7 +4155,41 @@ function createSchemas(entity) {
4008
4155
  }
4009
4156
  updateShape['id'] = withVisibility(getSchemaType(baseFields.id), 'technical');
4010
4157
  const updateSchema = withMetadata(object(updateShape), entity);
4011
- const listSchema = withMetadata(array(object(getShape)), entity);
4158
+ let listShape;
4159
+ if (entity.listFields && entity.listFields.length > 0) {
4160
+ const mandatoryFields = ['id', 'status'];
4161
+ const allListFields = [
4162
+ .../* @__PURE__ */ new Set([...mandatoryFields, ...entity.listFields]),
4163
+ ];
4164
+ listShape = {};
4165
+ for (const fieldName of allListFields) {
4166
+ const field = getShape[fieldName];
4167
+ if (field) {
4168
+ listShape[fieldName] = field;
4169
+ }
4170
+ }
4171
+ } else {
4172
+ listShape = getShape;
4173
+ }
4174
+ const listSchema = withMetadata(object(listShape), entity);
4175
+ let listCardShape;
4176
+ const fieldsToUse = entity.listCardFields ?? entity.listFields;
4177
+ if (fieldsToUse && fieldsToUse.length > 0) {
4178
+ const mandatoryFields = ['id', 'status'];
4179
+ const allListCardFields = [
4180
+ .../* @__PURE__ */ new Set([...mandatoryFields, ...fieldsToUse]),
4181
+ ];
4182
+ listCardShape = {};
4183
+ for (const fieldName of allListCardFields) {
4184
+ const field = getShape[fieldName];
4185
+ if (field) {
4186
+ listCardShape[fieldName] = field;
4187
+ }
4188
+ }
4189
+ } else {
4190
+ listCardShape = getShape;
4191
+ }
4192
+ const listCardSchema = withMetadata(object(listCardShape), entity);
4012
4193
  const deleteSchema = withMetadata(
4013
4194
  object({
4014
4195
  id: withVisibility(getSchemaType(baseFields.id), 'technical'),
@@ -4021,6 +4202,7 @@ function createSchemas(entity) {
4021
4202
  update: updateSchema,
4022
4203
  get: getSchema,
4023
4204
  list: listSchema,
4205
+ listCard: listCardSchema,
4024
4206
  delete: deleteSchema,
4025
4207
  };
4026
4208
  }
@@ -4039,6 +4221,90 @@ var init_createSchema = __esm({
4039
4221
  },
4040
4222
  });
4041
4223
 
4224
+ // ../core/schemas/src/client/index.ts
4225
+ var init_client = __esm({
4226
+ '../core/schemas/src/client/index.ts'() {
4227
+ 'use strict';
4228
+ init_createSchema();
4229
+ },
4230
+ });
4231
+
4232
+ // ../core/schemas/src/common/validation/enhanceSchema.ts
4233
+ var init_enhanceSchema = __esm({
4234
+ '../core/schemas/src/common/validation/enhanceSchema.ts'() {
4235
+ 'use strict';
4236
+ },
4237
+ });
4238
+
4239
+ // ../core/schemas/src/common/validation/validateDates.ts
4240
+ var init_validateDates = __esm({
4241
+ '../core/schemas/src/common/validation/validateDates.ts'() {
4242
+ 'use strict';
4243
+ init_server();
4244
+ },
4245
+ });
4246
+
4247
+ // ../core/schemas/src/common/validation/validateUniqueFields.ts
4248
+ var init_validateUniqueFields = __esm({
4249
+ '../core/schemas/src/common/validation/validateUniqueFields.ts'() {
4250
+ 'use strict';
4251
+ init_server();
4252
+ },
4253
+ });
4254
+
4255
+ // ../core/schemas/src/common/validation/validateDocument.ts
4256
+ var init_validateDocument = __esm({
4257
+ '../core/schemas/src/common/validation/validateDocument.ts'() {
4258
+ 'use strict';
4259
+ init_validateDates();
4260
+ init_validateUniqueFields();
4261
+ },
4262
+ });
4263
+
4264
+ // ../core/schemas/src/common/validation/index.ts
4265
+ var init_validation2 = __esm({
4266
+ '../core/schemas/src/common/validation/index.ts'() {
4267
+ 'use strict';
4268
+ init_enhanceSchema();
4269
+ init_getSchemaType();
4270
+ init_validateDates();
4271
+ init_validateDocument();
4272
+ init_validateUniqueFields();
4273
+ },
4274
+ });
4275
+
4276
+ // ../core/schemas/src/common/utils.ts
4277
+ var init_utils2 = __esm({
4278
+ '../core/schemas/src/common/utils.ts'() {
4279
+ 'use strict';
4280
+ init_server();
4281
+ },
4282
+ });
4283
+
4284
+ // ../core/schemas/src/common/defineEntity.ts
4285
+ var init_defineEntity = __esm({
4286
+ '../core/schemas/src/common/defineEntity.ts'() {
4287
+ 'use strict';
4288
+ init_src();
4289
+ init_server();
4290
+ init_visibility();
4291
+ },
4292
+ });
4293
+
4294
+ // ../core/schemas/src/common/optionHelpers.ts
4295
+ var init_optionHelpers = __esm({
4296
+ '../core/schemas/src/common/optionHelpers.ts'() {
4297
+ 'use strict';
4298
+ },
4299
+ });
4300
+
4301
+ // ../core/schemas/src/common/scopeProvider.ts
4302
+ var init_scopeProvider = __esm({
4303
+ '../core/schemas/src/common/scopeProvider.ts'() {
4304
+ 'use strict';
4305
+ },
4306
+ });
4307
+
4042
4308
  // ../core/schemas/src/common/index.ts
4043
4309
  var init_common3 = __esm({
4044
4310
  '../core/schemas/src/common/index.ts'() {
@@ -4048,22 +4314,26 @@ var init_common3 = __esm({
4048
4314
  init_visibility();
4049
4315
  init_defineEntity();
4050
4316
  init_createSchema();
4317
+ init_optionHelpers();
4318
+ init_scopeProvider();
4051
4319
  },
4052
4320
  });
4053
4321
 
4054
- // ../core/schemas/src/server/index.ts
4055
- var init_server2 = __esm({
4056
- '../core/schemas/src/server/index.ts'() {
4322
+ // ../core/schemas/src/index.ts
4323
+ var init_src2 = __esm({
4324
+ '../core/schemas/src/index.ts'() {
4325
+ 'use strict';
4326
+ init_client();
4057
4327
  init_common3();
4058
4328
  },
4059
4329
  });
4060
4330
 
4061
4331
  // ../core/server.ts
4062
- var init_server3 = __esm({
4332
+ var init_server2 = __esm({
4063
4333
  '../core/server.ts'() {
4064
4334
  init_server();
4065
4335
  init_src();
4066
- init_server2();
4336
+ init_src2();
4067
4337
  init_server();
4068
4338
  },
4069
4339
  });
@@ -4152,7 +4422,7 @@ var getFirebaseAdminServices;
4152
4422
  var init_init = __esm({
4153
4423
  '../providers/firebase/src/server/init.ts'() {
4154
4424
  'use strict';
4155
- init_server3();
4425
+ init_server2();
4156
4426
  __name(initializeFirebaseAdminServices, 'initializeFirebaseAdminServices');
4157
4427
  getFirebaseAdminServices = createSingleton(initializeFirebaseAdminServices);
4158
4428
  __name(initFirebaseAdmin, 'initFirebaseAdmin');
@@ -4168,7 +4438,7 @@ var serverImplementations, getServerAdmin, getServerFirestore, generateServerId;
4168
4438
  var init_utils3 = __esm({
4169
4439
  '../providers/firebase/src/server/utils.ts'() {
4170
4440
  'use strict';
4171
- init_server3();
4441
+ init_server2();
4172
4442
  serverImplementations = {
4173
4443
  async getServerAdmin() {
4174
4444
  try {
@@ -4349,22 +4619,8 @@ function prepareForFirestore(data, removeFields = []) {
4349
4619
  if (Array.isArray(data)) {
4350
4620
  return data.map((item) => prepareForFirestore(item, removeFields));
4351
4621
  }
4352
- if (
4353
- typeof data === 'string' &&
4354
- /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/.test(data)
4355
- ) {
4356
- try {
4357
- return toTimestamp(data);
4358
- } catch (error) {
4359
- return data;
4360
- }
4361
- }
4362
4622
  if (data instanceof Date) {
4363
- try {
4364
- return toTimestamp(data);
4365
- } catch (error) {
4366
- return data;
4367
- }
4623
+ return data.toISOString();
4368
4624
  }
4369
4625
  if (typeof data === 'object' && data !== null) {
4370
4626
  const prepared = {};
@@ -4400,7 +4656,7 @@ function createFirestorePartialUpdate(original, updated) {
4400
4656
  var init_transform = __esm({
4401
4657
  '../providers/firebase/src/shared/transform.ts'() {
4402
4658
  'use strict';
4403
- init_server3();
4659
+ init_server2();
4404
4660
  __name(createTimestamp, 'createTimestamp');
4405
4661
  __name(toTimestamp, 'toTimestamp');
4406
4662
  __name(firestoreToISOString, 'firestoreToISOString');
@@ -4427,7 +4683,7 @@ var init_batch = __esm({
4427
4683
  '../providers/firebase/src/server/batch.ts'() {
4428
4684
  'use strict';
4429
4685
  init_dist();
4430
- init_server3();
4686
+ init_server2();
4431
4687
  init_utils3();
4432
4688
  init_transform();
4433
4689
  isClient = typeof window !== 'undefined';
@@ -4706,7 +4962,7 @@ var isClient2, notAvailableInBrowser2, admin, getAdminFirestore, generateId;
4706
4962
  var init_utils4 = __esm({
4707
4963
  '../providers/firebase/src/shared/utils.ts'() {
4708
4964
  'use strict';
4709
- init_server3();
4965
+ init_server2();
4710
4966
  isClient2 = typeof window !== 'undefined';
4711
4967
  notAvailableInBrowser2 = /* @__PURE__ */ __name(
4712
4968
  (fnName) => () => {
@@ -4889,7 +5145,7 @@ async function saveSubscriptionFromStripeEvent(
4889
5145
  var init_subscription = __esm({
4890
5146
  '../providers/firebase/src/server/subscription.ts'() {
4891
5147
  'use strict';
4892
- init_server3();
5148
+ init_server2();
4893
5149
  init_utils3();
4894
5150
  init_transform();
4895
5151
  init_utils4();
@@ -5049,7 +5305,7 @@ var validatorRegistry;
5049
5305
  var init_uniqueness = __esm({
5050
5306
  '../providers/firebase/src/server/uniqueness.ts'() {
5051
5307
  'use strict';
5052
- init_server3();
5308
+ init_server2();
5053
5309
  init_utils3();
5054
5310
  validatorRegistry = {};
5055
5311
  __name(
@@ -5113,7 +5369,7 @@ var init_validation3 = __esm({
5113
5369
  '../providers/firebase/src/server/validation.ts'() {
5114
5370
  'use strict';
5115
5371
  init_dist();
5116
- init_server3();
5372
+ init_server2();
5117
5373
  init_uniqueness();
5118
5374
  init_uniqueness();
5119
5375
  __name(validateFirestoreDocument, 'validateFirestoreDocument');
@@ -5165,7 +5421,7 @@ __export(server_exports2, {
5165
5421
  validateUniqueness: () => validateUniqueness,
5166
5422
  });
5167
5423
  import { FieldValue, Query, Timestamp } from 'firebase-admin/firestore';
5168
- var init_server4 = __esm({
5424
+ var init_server3 = __esm({
5169
5425
  '../providers/firebase/src/server/index.ts'() {
5170
5426
  'use strict';
5171
5427
  init_init();
@@ -5178,18 +5434,504 @@ var init_server4 = __esm({
5178
5434
  },
5179
5435
  });
5180
5436
 
5437
+ // src/shared/utils/internal/rateLimiter.ts
5438
+ var rateLimiter_exports = {};
5439
+ __export(rateLimiter_exports, {
5440
+ DEFAULT_RATE_LIMITS: () => DEFAULT_RATE_LIMITS,
5441
+ checkRateLimit: () => checkRateLimit,
5442
+ checkRateLimitWithFirestore: () => checkRateLimitWithFirestore,
5443
+ getRateLimitStatus: () => getRateLimitStatus,
5444
+ resetRateLimit: () => resetRateLimit,
5445
+ resetRateLimitInFirestore: () => resetRateLimitInFirestore,
5446
+ });
5447
+ import { logger } from 'firebase-functions/v2';
5448
+ async function checkRateLimit(key, config) {
5449
+ const now = Date.now();
5450
+ const entry = rateLimitStore.get(key);
5451
+ if (entry?.blockUntil && now < entry.blockUntil) {
5452
+ return {
5453
+ allowed: false,
5454
+ remaining: 0,
5455
+ resetAt: new Date(entry.blockUntil),
5456
+ blockRemainingSeconds: Math.ceil((entry.blockUntil - now) / 1e3),
5457
+ };
5458
+ }
5459
+ if (entry && now >= entry.windowStart + config.windowMs) {
5460
+ rateLimitStore.delete(key);
5461
+ }
5462
+ const currentEntry = rateLimitStore.get(key) || {
5463
+ attempts: 0,
5464
+ windowStart: now,
5465
+ blockUntil: null,
5466
+ };
5467
+ if (currentEntry.attempts >= config.maxAttempts) {
5468
+ currentEntry.blockUntil = now + config.blockDurationMs;
5469
+ rateLimitStore.set(key, currentEntry);
5470
+ logger.warn('Rate limit exceeded', {
5471
+ key,
5472
+ attempts: currentEntry.attempts,
5473
+ blockUntil: new Date(currentEntry.blockUntil),
5474
+ });
5475
+ return {
5476
+ allowed: false,
5477
+ remaining: 0,
5478
+ resetAt: new Date(currentEntry.blockUntil),
5479
+ blockRemainingSeconds: Math.ceil(config.blockDurationMs / 1e3),
5480
+ };
5481
+ }
5482
+ currentEntry.attempts += 1;
5483
+ rateLimitStore.set(key, currentEntry);
5484
+ return {
5485
+ allowed: true,
5486
+ remaining: config.maxAttempts - currentEntry.attempts,
5487
+ resetAt: new Date(currentEntry.windowStart + config.windowMs),
5488
+ blockRemainingSeconds: null,
5489
+ };
5490
+ }
5491
+ async function checkRateLimitWithFirestore(key, config) {
5492
+ const db = getFirebaseAdminFirestore();
5493
+ const rateLimitRef = db.collection('rateLimits').doc(key);
5494
+ try {
5495
+ const now = Date.now();
5496
+ const doc = await rateLimitRef.get();
5497
+ if (!doc.exists) {
5498
+ await rateLimitRef.set({
5499
+ attempts: 1,
5500
+ windowStart: now,
5501
+ blockUntil: null,
5502
+ lastUpdated: now,
5503
+ });
5504
+ return {
5505
+ allowed: true,
5506
+ remaining: config.maxAttempts - 1,
5507
+ resetAt: new Date(now + config.windowMs),
5508
+ blockRemainingSeconds: null,
5509
+ };
5510
+ }
5511
+ const data = doc.data();
5512
+ if (data.blockUntil && now < data.blockUntil) {
5513
+ return {
5514
+ allowed: false,
5515
+ remaining: 0,
5516
+ resetAt: new Date(data.blockUntil),
5517
+ blockRemainingSeconds: Math.ceil((data.blockUntil - now) / 1e3),
5518
+ };
5519
+ }
5520
+ if (now >= data.windowStart + config.windowMs) {
5521
+ await rateLimitRef.set({
5522
+ attempts: 1,
5523
+ windowStart: now,
5524
+ blockUntil: null,
5525
+ lastUpdated: now,
5526
+ });
5527
+ return {
5528
+ allowed: true,
5529
+ remaining: config.maxAttempts - 1,
5530
+ resetAt: new Date(now + config.windowMs),
5531
+ blockRemainingSeconds: null,
5532
+ };
5533
+ }
5534
+ if (data.attempts >= config.maxAttempts) {
5535
+ const blockUntil = now + config.blockDurationMs;
5536
+ await rateLimitRef.update({
5537
+ blockUntil,
5538
+ lastUpdated: now,
5539
+ });
5540
+ logger.warn('Rate limit exceeded (Firestore)', {
5541
+ key,
5542
+ attempts: data.attempts,
5543
+ blockUntil: new Date(blockUntil),
5544
+ });
5545
+ return {
5546
+ allowed: false,
5547
+ remaining: 0,
5548
+ resetAt: new Date(blockUntil),
5549
+ blockRemainingSeconds: Math.ceil(config.blockDurationMs / 1e3),
5550
+ };
5551
+ }
5552
+ await rateLimitRef.update({
5553
+ attempts: data.attempts + 1,
5554
+ lastUpdated: now,
5555
+ });
5556
+ return {
5557
+ allowed: true,
5558
+ remaining: config.maxAttempts - (data.attempts + 1),
5559
+ resetAt: new Date(data.windowStart + config.windowMs),
5560
+ blockRemainingSeconds: null,
5561
+ };
5562
+ } catch (error) {
5563
+ logger.error('Rate limit check failed', {
5564
+ key,
5565
+ error: error instanceof Error ? error.message : String(error),
5566
+ });
5567
+ return {
5568
+ allowed: true,
5569
+ remaining: config.maxAttempts,
5570
+ resetAt: null,
5571
+ blockRemainingSeconds: null,
5572
+ };
5573
+ }
5574
+ }
5575
+ function resetRateLimit(key) {
5576
+ rateLimitStore.delete(key);
5577
+ logger.info('Rate limit reset', { key });
5578
+ }
5579
+ async function resetRateLimitInFirestore(key) {
5580
+ const db = getFirebaseAdminFirestore();
5581
+ const rateLimitRef = db.collection('rateLimits').doc(key);
5582
+ try {
5583
+ await rateLimitRef.delete();
5584
+ logger.info('Rate limit reset (Firestore)', { key });
5585
+ } catch (error) {
5586
+ logger.error('Failed to reset rate limit', {
5587
+ key,
5588
+ error: error instanceof Error ? error.message : String(error),
5589
+ });
5590
+ }
5591
+ }
5592
+ function getRateLimitStatus(key, config) {
5593
+ const now = Date.now();
5594
+ const entry = rateLimitStore.get(key);
5595
+ if (!entry) {
5596
+ return {
5597
+ allowed: true,
5598
+ remaining: config.maxAttempts,
5599
+ resetAt: null,
5600
+ blockRemainingSeconds: null,
5601
+ };
5602
+ }
5603
+ if (entry.blockUntil && now < entry.blockUntil) {
5604
+ return {
5605
+ allowed: false,
5606
+ remaining: 0,
5607
+ resetAt: new Date(entry.blockUntil),
5608
+ blockRemainingSeconds: Math.ceil((entry.blockUntil - now) / 1e3),
5609
+ };
5610
+ }
5611
+ if (now >= entry.windowStart + config.windowMs) {
5612
+ return {
5613
+ allowed: true,
5614
+ remaining: config.maxAttempts,
5615
+ resetAt: null,
5616
+ blockRemainingSeconds: null,
5617
+ };
5618
+ }
5619
+ return {
5620
+ allowed: entry.attempts < config.maxAttempts,
5621
+ remaining: Math.max(0, config.maxAttempts - entry.attempts),
5622
+ resetAt: new Date(entry.windowStart + config.windowMs),
5623
+ blockRemainingSeconds: null,
5624
+ };
5625
+ }
5626
+ var rateLimitStore, DEFAULT_RATE_LIMITS;
5627
+ var init_rateLimiter2 = __esm({
5628
+ 'src/shared/utils/internal/rateLimiter.ts'() {
5629
+ 'use strict';
5630
+ init_server3();
5631
+ rateLimitStore = /* @__PURE__ */ new Map();
5632
+ __name(checkRateLimit, 'checkRateLimit');
5633
+ __name(checkRateLimitWithFirestore, 'checkRateLimitWithFirestore');
5634
+ __name(resetRateLimit, 'resetRateLimit');
5635
+ __name(resetRateLimitInFirestore, 'resetRateLimitInFirestore');
5636
+ __name(getRateLimitStatus, 'getRateLimitStatus');
5637
+ DEFAULT_RATE_LIMITS = {
5638
+ checkout: {
5639
+ maxAttempts: 5,
5640
+ windowMs: 60 * 1e3,
5641
+ // 1 minute
5642
+ blockDurationMs: 5 * 60 * 1e3,
5643
+ // 5 minutes
5644
+ },
5645
+ webhook: {
5646
+ maxAttempts: 100,
5647
+ windowMs: 60 * 1e3,
5648
+ // 1 minute
5649
+ blockDurationMs: 60 * 1e3,
5650
+ // 1 minute
5651
+ },
5652
+ auth: {
5653
+ maxAttempts: 10,
5654
+ windowMs: 60 * 1e3,
5655
+ // 1 minute
5656
+ blockDurationMs: 5 * 60 * 1e3,
5657
+ // 5 minutes
5658
+ },
5659
+ api: {
5660
+ maxAttempts: 100,
5661
+ windowMs: 60 * 1e3,
5662
+ // 1 minute
5663
+ blockDurationMs: 60 * 1e3,
5664
+ // 1 minute
5665
+ },
5666
+ };
5667
+ },
5668
+ });
5669
+
5670
+ // src/shared/utils/internal/monitoring.ts
5671
+ var monitoring_exports = {};
5672
+ __export(monitoring_exports, {
5673
+ checkPaymentFailureRate: () => checkPaymentFailureRate,
5674
+ checkPaymentVolume: () => checkPaymentVolume,
5675
+ cleanupOldMetrics: () => cleanupOldMetrics,
5676
+ getPaymentMetricsSummary: () => getPaymentMetricsSummary,
5677
+ recordPaymentMetrics: () => recordPaymentMetrics,
5678
+ });
5679
+ import { logger as logger2 } from 'firebase-functions/v2';
5680
+ async function recordPaymentMetrics(metrics) {
5681
+ try {
5682
+ const db = getFirebaseAdminFirestore();
5683
+ const metricsRef = db.collection('payment_metrics').doc();
5684
+ await metricsRef.set({
5685
+ ...metrics,
5686
+ recordedAt: /* @__PURE__ */ new Date().toISOString(),
5687
+ });
5688
+ logger2.info('Payment metrics recorded', {
5689
+ operation: metrics.operation,
5690
+ status: metrics.status,
5691
+ userId: metrics.userId,
5692
+ });
5693
+ } catch (error) {
5694
+ logger2.error('Failed to record payment metrics', {
5695
+ error: error instanceof Error ? error.message : String(error),
5696
+ metrics,
5697
+ });
5698
+ }
5699
+ }
5700
+ async function checkPaymentFailureRate(timeWindowHours = 24) {
5701
+ try {
5702
+ const db = getFirebaseAdminFirestore();
5703
+ const cutoffTime = /* @__PURE__ */ new Date();
5704
+ cutoffTime.setHours(cutoffTime.getHours() - timeWindowHours);
5705
+ const metricsRef = db.collection('payment_metrics');
5706
+ const recentMetrics = await metricsRef
5707
+ .where('timestamp', '>=', cutoffTime.toISOString())
5708
+ .get();
5709
+ if (recentMetrics.empty) {
5710
+ return { failureRate: 0, shouldAlert: false };
5711
+ }
5712
+ const totalPayments = recentMetrics.size;
5713
+ const failedPayments = recentMetrics.docs.filter(
5714
+ (doc) => doc.data().status === 'failed'
5715
+ ).length;
5716
+ const failureRate = (failedPayments / totalPayments) * 100;
5717
+ const shouldAlert = failureRate > 10;
5718
+ if (shouldAlert) {
5719
+ await triggerPaymentFailureAlert(
5720
+ failureRate,
5721
+ totalPayments,
5722
+ failedPayments
5723
+ );
5724
+ }
5725
+ return { failureRate, shouldAlert };
5726
+ } catch (error) {
5727
+ logger2.error('Failed to check payment failure rate', {
5728
+ error: error instanceof Error ? error.message : String(error),
5729
+ });
5730
+ return { failureRate: 0, shouldAlert: false };
5731
+ }
5732
+ }
5733
+ async function checkPaymentVolume(volumeThreshold = 1e4) {
5734
+ try {
5735
+ const db = getFirebaseAdminFirestore();
5736
+ const today = /* @__PURE__ */ new Date();
5737
+ today.setHours(0, 0, 0, 0);
5738
+ const tomorrow = new Date(today);
5739
+ tomorrow.setDate(tomorrow.getDate() + 1);
5740
+ const metricsRef = db.collection('payment_metrics');
5741
+ const todayMetrics = await metricsRef
5742
+ .where('timestamp', '>=', today.toISOString())
5743
+ .where('timestamp', '<', tomorrow.toISOString())
5744
+ .where('status', '==', 'success')
5745
+ .get();
5746
+ let totalVolume = 0;
5747
+ todayMetrics.docs.forEach((doc) => {
5748
+ const data = doc.data();
5749
+ if (data.amount && data.currency === 'usd') {
5750
+ totalVolume += data.amount / 100;
5751
+ }
5752
+ });
5753
+ const shouldAlert = totalVolume > volumeThreshold;
5754
+ if (shouldAlert) {
5755
+ await triggerHighVolumeAlert(totalVolume, volumeThreshold);
5756
+ }
5757
+ return { totalVolume, shouldAlert };
5758
+ } catch (error) {
5759
+ logger2.error('Failed to check payment volume', {
5760
+ error: error instanceof Error ? error.message : String(error),
5761
+ });
5762
+ return { totalVolume: 0, shouldAlert: false };
5763
+ }
5764
+ }
5765
+ async function triggerPaymentFailureAlert(
5766
+ failureRate,
5767
+ totalPayments,
5768
+ failedPayments
5769
+ ) {
5770
+ try {
5771
+ const db = getFirebaseAdminFirestore();
5772
+ const alertRef = db.collection('payment_alerts').doc();
5773
+ await alertRef.set({
5774
+ type: 'payment_failure_rate',
5775
+ severity: 'high',
5776
+ message: `Payment failure rate is ${failureRate.toFixed(2)}% (${failedPayments}/${totalPayments} payments failed)`,
5777
+ data: {
5778
+ failureRate,
5779
+ totalPayments,
5780
+ failedPayments,
5781
+ },
5782
+ triggeredAt: /* @__PURE__ */ new Date().toISOString(),
5783
+ status: 'active',
5784
+ });
5785
+ logger2.error('PAYMENT FAILURE ALERT TRIGGERED', {
5786
+ failureRate,
5787
+ totalPayments,
5788
+ failedPayments,
5789
+ });
5790
+ } catch (error) {
5791
+ logger2.error('Failed to trigger payment failure alert', {
5792
+ error: error instanceof Error ? error.message : String(error),
5793
+ });
5794
+ }
5795
+ }
5796
+ async function triggerHighVolumeAlert(totalVolume, threshold) {
5797
+ try {
5798
+ const db = getFirebaseAdminFirestore();
5799
+ const alertRef = db.collection('payment_alerts').doc();
5800
+ await alertRef.set({
5801
+ type: 'high_payment_volume',
5802
+ severity: 'medium',
5803
+ message: `Daily payment volume exceeded threshold: $${totalVolume.toFixed(2)} (threshold: $${threshold})`,
5804
+ data: {
5805
+ totalVolume,
5806
+ threshold,
5807
+ },
5808
+ triggeredAt: /* @__PURE__ */ new Date().toISOString(),
5809
+ status: 'active',
5810
+ });
5811
+ logger2.warn('HIGH PAYMENT VOLUME ALERT TRIGGERED', {
5812
+ totalVolume,
5813
+ threshold,
5814
+ });
5815
+ } catch (error) {
5816
+ logger2.error('Failed to trigger high volume alert', {
5817
+ error: error instanceof Error ? error.message : String(error),
5818
+ });
5819
+ }
5820
+ }
5821
+ async function getPaymentMetricsSummary(startDate, endDate) {
5822
+ try {
5823
+ const db = getFirebaseAdminFirestore();
5824
+ const metricsRef = db.collection('payment_metrics');
5825
+ const metrics = await metricsRef
5826
+ .where('timestamp', '>=', startDate.toISOString())
5827
+ .where('timestamp', '<=', endDate.toISOString())
5828
+ .get();
5829
+ let totalPayments = 0;
5830
+ let successfulPayments = 0;
5831
+ let failedPayments = 0;
5832
+ let totalVolume = 0;
5833
+ metrics.docs.forEach((doc) => {
5834
+ const data = doc.data();
5835
+ totalPayments++;
5836
+ if (data.status === 'success') {
5837
+ successfulPayments++;
5838
+ if (data.amount && data.currency === 'usd') {
5839
+ totalVolume += data.amount / 100;
5840
+ }
5841
+ } else if (data.status === 'failed') {
5842
+ failedPayments++;
5843
+ }
5844
+ });
5845
+ const averageAmount =
5846
+ successfulPayments > 0 ? totalVolume / successfulPayments : 0;
5847
+ return {
5848
+ totalPayments,
5849
+ successfulPayments,
5850
+ failedPayments,
5851
+ totalVolume,
5852
+ averageAmount,
5853
+ };
5854
+ } catch (error) {
5855
+ logger2.error('Failed to get payment metrics summary', {
5856
+ error: error instanceof Error ? error.message : String(error),
5857
+ });
5858
+ return {
5859
+ totalPayments: 0,
5860
+ successfulPayments: 0,
5861
+ failedPayments: 0,
5862
+ totalVolume: 0,
5863
+ averageAmount: 0,
5864
+ };
5865
+ }
5866
+ }
5867
+ async function cleanupOldMetrics(
5868
+ metricsRetentionDays = 90,
5869
+ alertsRetentionDays = 30
5870
+ ) {
5871
+ try {
5872
+ const db = getFirebaseAdminFirestore();
5873
+ const now = /* @__PURE__ */ new Date();
5874
+ const metricsCutoff = new Date(now);
5875
+ metricsCutoff.setDate(metricsCutoff.getDate() - metricsRetentionDays);
5876
+ const oldMetrics = await db
5877
+ .collection('payment_metrics')
5878
+ .where('recordedAt', '<', metricsCutoff.toISOString())
5879
+ .limit(500)
5880
+ .get();
5881
+ if (!oldMetrics.empty) {
5882
+ const batch = db.batch();
5883
+ oldMetrics.docs.forEach((doc) => batch.delete(doc.ref));
5884
+ await batch.commit();
5885
+ }
5886
+ const alertsCutoff = new Date(now);
5887
+ alertsCutoff.setDate(alertsCutoff.getDate() - alertsRetentionDays);
5888
+ const oldAlerts = await db
5889
+ .collection('payment_alerts')
5890
+ .where('triggeredAt', '<', alertsCutoff.toISOString())
5891
+ .limit(500)
5892
+ .get();
5893
+ if (!oldAlerts.empty) {
5894
+ const batch = db.batch();
5895
+ oldAlerts.docs.forEach((doc) => batch.delete(doc.ref));
5896
+ await batch.commit();
5897
+ }
5898
+ logger2.info('Payment metrics cleanup completed', {
5899
+ deletedMetrics: oldMetrics.size,
5900
+ deletedAlerts: oldAlerts.size,
5901
+ });
5902
+ } catch (error) {
5903
+ logger2.error('Payment metrics cleanup failed', {
5904
+ error: error instanceof Error ? error.message : String(error),
5905
+ });
5906
+ }
5907
+ }
5908
+ var init_monitoring = __esm({
5909
+ 'src/shared/utils/internal/monitoring.ts'() {
5910
+ 'use strict';
5911
+ init_server3();
5912
+ __name(recordPaymentMetrics, 'recordPaymentMetrics');
5913
+ __name(checkPaymentFailureRate, 'checkPaymentFailureRate');
5914
+ __name(checkPaymentVolume, 'checkPaymentVolume');
5915
+ __name(triggerPaymentFailureAlert, 'triggerPaymentFailureAlert');
5916
+ __name(triggerHighVolumeAlert, 'triggerHighVolumeAlert');
5917
+ __name(getPaymentMetricsSummary, 'getPaymentMetricsSummary');
5918
+ __name(cleanupOldMetrics, 'cleanupOldMetrics');
5919
+ },
5920
+ });
5921
+
5181
5922
  // src/firebase/auth/getCustomClaims.ts
5182
- init_server4();
5183
5923
  init_dist();
5924
+ init_server3();
5184
5925
 
5185
5926
  // src/firebase/baseFunction.ts
5186
5927
  init_dist();
5928
+ init_server2();
5187
5929
  import { logger as logger3 } from 'firebase-functions/v2';
5188
5930
  import { onCall } from 'firebase-functions/v2/https';
5189
5931
 
5190
5932
  // src/shared/errorHandling.ts
5191
- init_server3();
5192
5933
  import { HttpsError } from 'firebase-functions/v2/https';
5934
+ init_server2();
5193
5935
  var DoNotDevError3 = class _DoNotDevError extends Error {
5194
5936
  static {
5195
5937
  __name(this, 'DoNotDevError');
@@ -5294,177 +6036,33 @@ function isFirebaseEnvironment() {
5294
6036
  return (
5295
6037
  typeof process !== 'undefined' &&
5296
6038
  (process.env.FUNCTIONS_EMULATOR === 'true' ||
5297
- process.env.FIREBASE_CONFIG !== void 0 ||
5298
- process.env.GCLOUD_PROJECT !== void 0)
5299
- );
5300
- }
5301
- __name(isFirebaseEnvironment, 'isFirebaseEnvironment');
5302
- function isVercelEnvironment() {
5303
- return (
5304
- typeof process !== 'undefined' &&
5305
- (process.env.VERCEL === '1' || process.env.VERCEL_ENV !== void 0)
5306
- );
5307
- }
5308
- __name(isVercelEnvironment, 'isVercelEnvironment');
5309
- function throwFirebaseError(code, message, details) {
5310
- throw new HttpsError(code, message, details);
5311
- }
5312
- __name(throwFirebaseError, 'throwFirebaseError');
5313
- function throwVercelError(code, message, details) {
5314
- const error = new Error(message);
5315
- error.code = code;
5316
- error.details = details;
5317
- throw error;
5318
- }
5319
- __name(throwVercelError, 'throwVercelError');
5320
-
5321
- // src/shared/utils/internal/monitoring.ts
5322
- init_server4();
5323
- import { logger } from 'firebase-functions/v2';
5324
- async function recordPaymentMetrics(metrics) {
5325
- try {
5326
- const db = getFirebaseAdminFirestore();
5327
- const metricsRef = db.collection('payment_metrics').doc();
5328
- await metricsRef.set({
5329
- ...metrics,
5330
- recordedAt: /* @__PURE__ */ new Date().toISOString(),
5331
- });
5332
- logger.info('Payment metrics recorded', {
5333
- operation: metrics.operation,
5334
- status: metrics.status,
5335
- userId: metrics.userId,
5336
- });
5337
- } catch (error) {
5338
- logger.error('Failed to record payment metrics', {
5339
- error: error instanceof Error ? error.message : String(error),
5340
- metrics,
5341
- });
5342
- }
5343
- }
5344
- __name(recordPaymentMetrics, 'recordPaymentMetrics');
5345
-
5346
- // src/shared/utils/internal/rateLimiter.ts
5347
- init_server4();
5348
- import { logger as logger2 } from 'firebase-functions/v2';
5349
- async function checkRateLimitWithFirestore(key, config) {
5350
- const db = getFirebaseAdminFirestore();
5351
- const rateLimitRef = db.collection('rateLimits').doc(key);
5352
- try {
5353
- const now = Date.now();
5354
- const doc = await rateLimitRef.get();
5355
- if (!doc.exists) {
5356
- await rateLimitRef.set({
5357
- attempts: 1,
5358
- windowStart: now,
5359
- blockUntil: null,
5360
- lastUpdated: now,
5361
- });
5362
- return {
5363
- allowed: true,
5364
- remaining: config.maxAttempts - 1,
5365
- resetAt: new Date(now + config.windowMs),
5366
- blockRemainingSeconds: null,
5367
- };
5368
- }
5369
- const data = doc.data();
5370
- if (data.blockUntil && now < data.blockUntil) {
5371
- return {
5372
- allowed: false,
5373
- remaining: 0,
5374
- resetAt: new Date(data.blockUntil),
5375
- blockRemainingSeconds: Math.ceil((data.blockUntil - now) / 1e3),
5376
- };
5377
- }
5378
- if (now >= data.windowStart + config.windowMs) {
5379
- await rateLimitRef.set({
5380
- attempts: 1,
5381
- windowStart: now,
5382
- blockUntil: null,
5383
- lastUpdated: now,
5384
- });
5385
- return {
5386
- allowed: true,
5387
- remaining: config.maxAttempts - 1,
5388
- resetAt: new Date(now + config.windowMs),
5389
- blockRemainingSeconds: null,
5390
- };
5391
- }
5392
- if (data.attempts >= config.maxAttempts) {
5393
- const blockUntil = now + config.blockDurationMs;
5394
- await rateLimitRef.update({
5395
- blockUntil,
5396
- lastUpdated: now,
5397
- });
5398
- logger2.warn('Rate limit exceeded (Firestore)', {
5399
- key,
5400
- attempts: data.attempts,
5401
- blockUntil: new Date(blockUntil),
5402
- });
5403
- return {
5404
- allowed: false,
5405
- remaining: 0,
5406
- resetAt: new Date(blockUntil),
5407
- blockRemainingSeconds: Math.ceil(config.blockDurationMs / 1e3),
5408
- };
5409
- }
5410
- await rateLimitRef.update({
5411
- attempts: data.attempts + 1,
5412
- lastUpdated: now,
5413
- });
5414
- return {
5415
- allowed: true,
5416
- remaining: config.maxAttempts - (data.attempts + 1),
5417
- resetAt: new Date(data.windowStart + config.windowMs),
5418
- blockRemainingSeconds: null,
5419
- };
5420
- } catch (error) {
5421
- logger2.error('Rate limit check failed', {
5422
- key,
5423
- error: error instanceof Error ? error.message : String(error),
5424
- });
5425
- return {
5426
- allowed: true,
5427
- remaining: config.maxAttempts,
5428
- resetAt: null,
5429
- blockRemainingSeconds: null,
5430
- };
5431
- }
6039
+ process.env.FIREBASE_CONFIG !== void 0 ||
6040
+ process.env.GCLOUD_PROJECT !== void 0)
6041
+ );
5432
6042
  }
5433
- __name(checkRateLimitWithFirestore, 'checkRateLimitWithFirestore');
5434
- var DEFAULT_RATE_LIMITS = {
5435
- checkout: {
5436
- maxAttempts: 5,
5437
- windowMs: 60 * 1e3,
5438
- // 1 minute
5439
- blockDurationMs: 5 * 60 * 1e3,
5440
- // 5 minutes
5441
- },
5442
- webhook: {
5443
- maxAttempts: 100,
5444
- windowMs: 60 * 1e3,
5445
- // 1 minute
5446
- blockDurationMs: 60 * 1e3,
5447
- // 1 minute
5448
- },
5449
- auth: {
5450
- maxAttempts: 10,
5451
- windowMs: 60 * 1e3,
5452
- // 1 minute
5453
- blockDurationMs: 5 * 60 * 1e3,
5454
- // 5 minutes
5455
- },
5456
- api: {
5457
- maxAttempts: 100,
5458
- windowMs: 60 * 1e3,
5459
- // 1 minute
5460
- blockDurationMs: 60 * 1e3,
5461
- // 1 minute
5462
- },
5463
- };
6043
+ __name(isFirebaseEnvironment, 'isFirebaseEnvironment');
6044
+ function isVercelEnvironment() {
6045
+ return (
6046
+ typeof process !== 'undefined' &&
6047
+ (process.env.VERCEL === '1' || process.env.VERCEL_ENV !== void 0)
6048
+ );
6049
+ }
6050
+ __name(isVercelEnvironment, 'isVercelEnvironment');
6051
+ function throwFirebaseError(code, message, details) {
6052
+ throw new HttpsError(code, message, details);
6053
+ }
6054
+ __name(throwFirebaseError, 'throwFirebaseError');
6055
+ function throwVercelError(code, message, details) {
6056
+ const error = new Error(message);
6057
+ error.code = code;
6058
+ error.details = details;
6059
+ throw error;
6060
+ }
6061
+ __name(throwVercelError, 'throwVercelError');
5464
6062
 
5465
6063
  // src/shared/utils.ts
6064
+ init_server2();
5466
6065
  init_server3();
5467
- init_server4();
5468
6066
  import Stripe from 'stripe';
5469
6067
  var _stripe = null;
5470
6068
  function initStripe(apiKey) {
@@ -5507,6 +6105,9 @@ function assertAuthenticated(auth) {
5507
6105
  __name(assertAuthenticated, 'assertAuthenticated');
5508
6106
  function getUserRole(auth) {
5509
6107
  if (!auth?.uid) return 'guest';
6108
+ const role = auth.token?.role;
6109
+ if (role === 'super') return 'super';
6110
+ if (role === 'admin') return 'admin';
5510
6111
  if (auth.token?.isSuper) return 'super';
5511
6112
  if (auth.token?.isAdmin) return 'admin';
5512
6113
  return 'user';
@@ -5519,13 +6120,6 @@ function validateStripeEnvironment() {
5519
6120
  }
5520
6121
  }
5521
6122
  __name(validateStripeEnvironment, 'validateStripeEnvironment');
5522
- function assertAdmin(uid) {
5523
- if (!uid) {
5524
- throw new Error('Authentication required');
5525
- }
5526
- return uid;
5527
- }
5528
- __name(assertAdmin, 'assertAdmin');
5529
6123
  function validateDocument(data, schema) {
5530
6124
  if (!data || typeof data !== 'object') {
5531
6125
  throw new Error('Invalid document data');
@@ -5541,7 +6135,59 @@ function findReferences(collection, docId) {
5541
6135
  __name(findReferences, 'findReferences');
5542
6136
 
5543
6137
  // src/firebase/baseFunction.ts
5544
- function createBaseFunction(config, schema, operation, businessLogic) {
6138
+ var checkRateLimitWithFirestore2 = null;
6139
+ var DEFAULT_RATE_LIMITS2 = null;
6140
+ var recordPaymentMetrics2 = null;
6141
+ async function loadRateLimiter() {
6142
+ if (!checkRateLimitWithFirestore2) {
6143
+ const mod = await Promise.resolve().then(
6144
+ () => (init_rateLimiter2(), rateLimiter_exports)
6145
+ );
6146
+ checkRateLimitWithFirestore2 = mod.checkRateLimitWithFirestore;
6147
+ DEFAULT_RATE_LIMITS2 = mod.DEFAULT_RATE_LIMITS;
6148
+ }
6149
+ return {
6150
+ checkRateLimitWithFirestore: checkRateLimitWithFirestore2,
6151
+ DEFAULT_RATE_LIMITS: DEFAULT_RATE_LIMITS2,
6152
+ };
6153
+ }
6154
+ __name(loadRateLimiter, 'loadRateLimiter');
6155
+ async function loadMonitoring() {
6156
+ if (!recordPaymentMetrics2) {
6157
+ const mod = await Promise.resolve().then(
6158
+ () => (init_monitoring(), monitoring_exports)
6159
+ );
6160
+ recordPaymentMetrics2 = mod.recordPaymentMetrics;
6161
+ }
6162
+ return recordPaymentMetrics2;
6163
+ }
6164
+ __name(loadMonitoring, 'loadMonitoring');
6165
+ function getClientIp(request) {
6166
+ const forwardedFor = request.rawRequest.headers['x-forwarded-for'];
6167
+ if (forwardedFor) {
6168
+ let ips;
6169
+ if (Array.isArray(forwardedFor)) {
6170
+ ips = forwardedFor.length > 0 ? forwardedFor[0] : void 0;
6171
+ } else {
6172
+ ips = forwardedFor;
6173
+ }
6174
+ if (ips && typeof ips === 'string') {
6175
+ const firstIp = ips.split(',')[0];
6176
+ return firstIp ? firstIp.trim() : 'unknown';
6177
+ }
6178
+ }
6179
+ const rawIp =
6180
+ request.rawRequest.ip || request.rawRequest.socket?.remoteAddress;
6181
+ return rawIp || 'unknown';
6182
+ }
6183
+ __name(getClientIp, 'getClientIp');
6184
+ function createBaseFunction(
6185
+ config,
6186
+ schema,
6187
+ operation,
6188
+ businessLogic,
6189
+ requiredRole = 'user'
6190
+ ) {
5545
6191
  if (!schema) {
5546
6192
  const error = new Error(
5547
6193
  `Schema is undefined for ${operation}. Ensure the schema is properly imported and exported.`
@@ -5612,69 +6258,95 @@ function createBaseFunction(config, schema, operation, businessLogic) {
5612
6258
  });
5613
6259
  throw parseError;
5614
6260
  }
5615
- const uid = assertAuthenticated(request.auth);
5616
- const rateLimitKey = `${operation}_${uid}`;
5617
- const rateLimitConfig =
5618
- DEFAULT_RATE_LIMITS[operation] || DEFAULT_RATE_LIMITS.checkout;
5619
- const rateLimitResult = await checkRateLimitWithFirestore(
5620
- rateLimitKey,
5621
- rateLimitConfig
5622
- );
5623
- if (!rateLimitResult.allowed) {
5624
- logger3.warn(`Rate limit exceeded for ${operation}`, {
6261
+ const userRole = getUserRole(request.auth);
6262
+ let uid;
6263
+ if (requiredRole === 'guest') {
6264
+ uid = request.auth?.uid || 'guest';
6265
+ } else {
6266
+ uid = assertAuthenticated(request.auth);
6267
+ if (!hasRoleAccess(userRole, requiredRole)) {
6268
+ logger3.warn(`Insufficient role for ${operation}`, {
6269
+ userId: uid,
6270
+ userRole,
6271
+ requiredRole,
6272
+ });
6273
+ throw new Error(
6274
+ `Access denied. Required role: ${requiredRole}, your role: ${userRole}`
6275
+ );
6276
+ }
6277
+ }
6278
+ if (process.env.ENABLE_RATE_LIMITING === 'true') {
6279
+ const {
6280
+ checkRateLimitWithFirestore: checkLimit,
6281
+ DEFAULT_RATE_LIMITS: limits,
6282
+ } = await loadRateLimiter();
6283
+ const rateLimitIdentifier =
6284
+ requiredRole === 'guest' && uid === 'guest'
6285
+ ? `ip_${getClientIp(request)}`
6286
+ : `uid_${uid}`;
6287
+ const rateLimitKey = `${operation}_${rateLimitIdentifier}`;
6288
+ const rateLimitConfig = limits[operation] || limits.api;
6289
+ const rateLimitResult = await checkLimit(rateLimitKey, rateLimitConfig);
6290
+ if (!rateLimitResult.allowed) {
6291
+ logger3.warn(`Rate limit exceeded for ${operation}`, {
6292
+ identifier: rateLimitIdentifier,
6293
+ remaining: rateLimitResult.remaining,
6294
+ resetAt: rateLimitResult.resetAt,
6295
+ });
6296
+ throw new Error(
6297
+ `Rate limit exceeded. Try again in ${rateLimitResult.blockRemainingSeconds} seconds.`
6298
+ );
6299
+ }
6300
+ }
6301
+ const result = await businessLogic(validatedData, {
6302
+ uid,
6303
+ userRole,
6304
+ request,
6305
+ });
6306
+ if (process.env.ENABLE_METRICS === 'true') {
6307
+ const recordMetrics = await loadMonitoring();
6308
+ await recordMetrics({
6309
+ operation,
5625
6310
  userId: uid,
5626
- remaining: rateLimitResult.remaining,
5627
- resetAt: rateLimitResult.resetAt,
6311
+ status: 'success',
6312
+ timestamp: /* @__PURE__ */ new Date().toISOString(),
6313
+ metadata: {
6314
+ requestId: request.rawRequest.headers['x-request-id'] || 'unknown',
6315
+ },
5628
6316
  });
5629
- throw new Error(
5630
- `Rate limit exceeded. Try again in ${rateLimitResult.blockRemainingSeconds} seconds.`
5631
- );
5632
6317
  }
5633
- const result = await businessLogic(validatedData, { uid, request });
5634
- await recordPaymentMetrics({
5635
- operation,
5636
- userId: uid,
5637
- status: 'success',
5638
- timestamp: /* @__PURE__ */ new Date().toISOString(),
5639
- metadata: {
5640
- requestId: request.rawRequest.headers['x-request-id'] || 'unknown',
5641
- },
5642
- });
5643
6318
  return result;
5644
6319
  } catch (error) {
5645
- await recordPaymentMetrics({
5646
- operation,
5647
- userId: request.auth?.uid || 'anonymous',
5648
- status: 'failed',
5649
- timestamp: /* @__PURE__ */ new Date().toISOString(),
5650
- metadata: {
5651
- error: error instanceof Error ? error.message : 'Unknown error',
5652
- requestId: request.rawRequest.headers['x-request-id'] || 'unknown',
5653
- },
5654
- });
6320
+ if (process.env.ENABLE_METRICS === 'true') {
6321
+ const recordMetrics = await loadMonitoring();
6322
+ await recordMetrics({
6323
+ operation,
6324
+ userId: request.auth?.uid || 'anonymous',
6325
+ status: 'failed',
6326
+ timestamp: /* @__PURE__ */ new Date().toISOString(),
6327
+ metadata: {
6328
+ error: error instanceof Error ? error.message : 'Unknown error',
6329
+ requestId: request.rawRequest.headers['x-request-id'] || 'unknown',
6330
+ },
6331
+ });
6332
+ }
5655
6333
  throw handleError2(error);
5656
6334
  }
5657
6335
  });
5658
6336
  }
5659
6337
  __name(createBaseFunction, 'createBaseFunction');
5660
6338
 
5661
- // src/firebase/config/secrets.ts
5662
- import { defineSecret } from 'firebase-functions/params';
5663
- var stripeSecretKey = defineSecret('STRIPE_SECRET_KEY');
5664
- var stripeWebhookSecret = defineSecret('STRIPE_WEBHOOK_SECRET');
5665
- var githubPersonalAccessToken = defineSecret('GITHUB_PERSONAL_ACCESS_TOKEN');
5666
-
5667
6339
  // src/firebase/config/constants.ts
5668
6340
  var FIREBASE_REGION = process.env.FIREBASE_REGION || 'europe-west1';
5669
6341
  var ENFORCE_APP_CHECK = process.env.ENFORCE_APP_CHECK === 'true';
5670
6342
  var BASE_CONFIG = {
5671
6343
  region: FIREBASE_REGION,
5672
- invoker: 'public',
5673
- // Cloud Run allows HTTP, onCall validates Firebase Auth
5674
6344
  ...(ENFORCE_APP_CHECK && { enforceAppCheck: true }),
5675
6345
  };
5676
6346
  var FUNCTION_CONFIG = {
5677
6347
  ...BASE_CONFIG,
6348
+ invoker: 'public',
6349
+ // Cloud Run allows HTTP, onCall validates Firebase Auth
5678
6350
  memory: '1GiB',
5679
6351
  timeoutSeconds: 60,
5680
6352
  cors: true,
@@ -5685,7 +6357,6 @@ var STRIPE_CONFIG = {
5685
6357
  memory: '512MiB',
5686
6358
  timeoutSeconds: 30,
5687
6359
  cors: true,
5688
- secrets: [stripeSecretKey, stripeWebhookSecret],
5689
6360
  };
5690
6361
  var AUTH_CONFIG = {
5691
6362
  ...BASE_CONFIG,
@@ -5694,6 +6365,17 @@ var AUTH_CONFIG = {
5694
6365
  };
5695
6366
  var CRUD_CONFIG = {
5696
6367
  ...BASE_CONFIG,
6368
+ invoker: 'public',
6369
+ // Cloud Run allows HTTP, onCall validates Firebase Auth + role-based access
6370
+ memory: '256MiB',
6371
+ timeoutSeconds: 15,
6372
+ cors: true,
6373
+ // Enable CORS for cross-origin requests (required for web apps)
6374
+ };
6375
+ var CRUD_READ_CONFIG = {
6376
+ ...BASE_CONFIG,
6377
+ invoker: 'public',
6378
+ // Cloud Run allows HTTP, onCall validates Firebase Auth
5697
6379
  memory: '256MiB',
5698
6380
  timeoutSeconds: 15,
5699
6381
  cors: true,
@@ -5747,8 +6429,8 @@ var getCustomClaims = /* @__PURE__ */ __name((customSchema) => {
5747
6429
  }, 'getCustomClaims');
5748
6430
 
5749
6431
  // src/firebase/auth/getUserAuthStatus.ts
5750
- init_server4();
5751
6432
  init_dist();
6433
+ init_server3();
5752
6434
  var getUserAuthStatusSchema = object({});
5753
6435
  async function getUserAuthStatusLogic(data, context) {
5754
6436
  const user = await getFirebaseAdminAuth().getUser(context.uid);
@@ -5772,8 +6454,8 @@ var getUserAuthStatus = /* @__PURE__ */ __name((customSchema) => {
5772
6454
  }, 'getUserAuthStatus');
5773
6455
 
5774
6456
  // src/firebase/auth/removeCustomClaims.ts
5775
- init_server4();
5776
6457
  init_dist();
6458
+ init_server3();
5777
6459
  var removeCustomClaimsSchema = object({
5778
6460
  claimsToRemove: pipe(
5779
6461
  array(string()),
@@ -5803,8 +6485,8 @@ var removeCustomClaims = /* @__PURE__ */ __name((customSchema) => {
5803
6485
  }, 'removeCustomClaims');
5804
6486
 
5805
6487
  // src/firebase/auth/setCustomClaims.ts
5806
- init_server4();
5807
6488
  init_dist();
6489
+ init_server3();
5808
6490
  var setCustomClaimsSchema = object({
5809
6491
  customClaims: record(string(), any()),
5810
6492
  idempotencyKey: optional(string()),
@@ -5854,8 +6536,8 @@ var setCustomClaims = /* @__PURE__ */ __name((customSchema) => {
5854
6536
  }, 'setCustomClaims');
5855
6537
 
5856
6538
  // src/firebase/billing/createCheckoutSession.ts
5857
- init_server4();
5858
- init_server3();
6539
+ init_server2();
6540
+ init_server2();
5859
6541
  init_server3();
5860
6542
  import { logger as logger5 } from 'firebase-functions/v2';
5861
6543
 
@@ -5930,6 +6612,12 @@ function validateMetadata(metadata) {
5930
6612
  }
5931
6613
  __name(validateMetadata, 'validateMetadata');
5932
6614
 
6615
+ // src/firebase/config/secrets.ts
6616
+ import { defineSecret } from 'firebase-functions/params';
6617
+ var stripeSecretKey = defineSecret('STRIPE_SECRET_KEY');
6618
+ var stripeWebhookSecret = defineSecret('STRIPE_WEBHOOK_SECRET');
6619
+ var githubPersonalAccessToken = defineSecret('GITHUB_PERSONAL_ACCESS_TOKEN');
6620
+
5933
6621
  // src/firebase/billing/createCheckoutSession.ts
5934
6622
  async function createCheckoutSessionLogic(data, context, billingConfig) {
5935
6623
  initStripe(stripeSecretKey.value());
@@ -6123,7 +6811,7 @@ async function updateUserSubscription(userId, subscriptionData, authProvider) {
6123
6811
  __name(updateUserSubscription, 'updateUserSubscription');
6124
6812
 
6125
6813
  // src/shared/billing/webhookHandler.ts
6126
- init_server3();
6814
+ init_server2();
6127
6815
  import 'stripe';
6128
6816
 
6129
6817
  // src/shared/logger.ts
@@ -6332,7 +7020,7 @@ async function isFirestoreAvailable() {
6332
7020
  }
6333
7021
  try {
6334
7022
  const { getFirebaseAdminFirestore: getFirebaseAdminFirestore2 } =
6335
- await Promise.resolve().then(() => (init_server4(), server_exports2));
7023
+ await Promise.resolve().then(() => (init_server3(), server_exports2));
6336
7024
  const db = getFirebaseAdminFirestore2();
6337
7025
  await db.collection('_health_check').limit(1).get();
6338
7026
  return true;
@@ -6380,7 +7068,7 @@ var FirestoreIdempotency = class {
6380
7068
  async init() {
6381
7069
  if (this.initialized) return;
6382
7070
  const { getFirebaseAdminFirestore: getFirebaseAdminFirestore2 } =
6383
- await Promise.resolve().then(() => (init_server4(), server_exports2));
7071
+ await Promise.resolve().then(() => (init_server3(), server_exports2));
6384
7072
  this.db = getFirebaseAdminFirestore2();
6385
7073
  this.initialized = true;
6386
7074
  }
@@ -6443,7 +7131,7 @@ function resetIdempotencyStore() {
6443
7131
  __name(resetIdempotencyStore, 'resetIdempotencyStore');
6444
7132
 
6445
7133
  // src/shared/utils/external/date.ts
6446
- init_server4();
7134
+ init_server3();
6447
7135
  function addMonths(date, months) {
6448
7136
  const result = new Date(date);
6449
7137
  const originalDate = result.getDate();
@@ -6924,8 +7612,8 @@ var billingHealth = onRequest2(STRIPE_CONFIG, async (req, res) => {
6924
7612
  });
6925
7613
 
6926
7614
  // src/firebase/billing/refreshSubscriptionStatus.ts
6927
- init_server4();
6928
7615
  init_dist();
7616
+ init_server3();
6929
7617
  import 'stripe';
6930
7618
  var refreshSubscriptionStatusSchema = object({
6931
7619
  userId: pipe(string(), minLength(1, 'User ID is required')),
@@ -6977,11 +7665,11 @@ var refreshSubscriptionStatus = /* @__PURE__ */ __name((customSchema) => {
6977
7665
  }, 'refreshSubscriptionStatus');
6978
7666
 
6979
7667
  // src/firebase/billing/cancelSubscription.ts
6980
- init_server4();
6981
7668
  init_dist();
7669
+ init_server3();
6982
7670
 
6983
7671
  // src/shared/billing/helpers/subscriptionManagement.ts
6984
- init_server3();
7672
+ init_server2();
6985
7673
  import 'stripe';
6986
7674
  async function cancelUserSubscription(userId, authProvider) {
6987
7675
  validateStripeEnvironment();
@@ -7059,8 +7747,8 @@ function cancelSubscription() {
7059
7747
  __name(cancelSubscription, 'cancelSubscription');
7060
7748
 
7061
7749
  // src/firebase/billing/changePlan.ts
7062
- init_server4();
7063
7750
  init_dist();
7751
+ init_server3();
7064
7752
  import 'stripe';
7065
7753
  var changePlanSchema = object({
7066
7754
  userId: string(),
@@ -7146,8 +7834,8 @@ function changePlan(billingConfig) {
7146
7834
  __name(changePlan, 'changePlan');
7147
7835
 
7148
7836
  // src/firebase/billing/createCustomerPortal.ts
7149
- init_server4();
7150
7837
  init_dist();
7838
+ init_server3();
7151
7839
  var customerPortalSchema = object({
7152
7840
  userId: string(),
7153
7841
  returnUrl: optional(pipe(string(), url())),
@@ -7190,7 +7878,7 @@ __name(createCustomerPortal, 'createCustomerPortal');
7190
7878
 
7191
7879
  // src/firebase/crud/aggregate.ts
7192
7880
  init_dist();
7193
- init_server4();
7881
+ init_server3();
7194
7882
 
7195
7883
  // src/shared/schema.ts
7196
7884
  function isFieldVisible2(key, visibility, isAdmin, isAuthenticated = true) {
@@ -7206,6 +7894,9 @@ function isFieldVisible2(key, visibility, isAdmin, isAuthenticated = true) {
7206
7894
  if (visibility === 'technical') {
7207
7895
  return isAdmin;
7208
7896
  }
7897
+ if (visibility === 'owner') {
7898
+ return false;
7899
+ }
7209
7900
  if (visibility === 'user' || visibility === void 0) {
7210
7901
  return isAuthenticated;
7211
7902
  }
@@ -7226,24 +7917,49 @@ function canAggregateField(fieldName, schema, isAdmin) {
7226
7917
  return isFieldVisible2(fieldName, visibility, isAdmin);
7227
7918
  }
7228
7919
  __name(canAggregateField, 'canAggregateField');
7920
+ function getPriceOrNumberValue(raw) {
7921
+ if (raw != null && typeof raw === 'object' && 'amount' in raw) {
7922
+ const obj = raw;
7923
+ const amount = Number(obj.amount);
7924
+ if (!Number.isFinite(amount)) return NaN;
7925
+ const discountPercent = Number(obj.discountPercent);
7926
+ const pct = Number.isFinite(discountPercent)
7927
+ ? Math.min(100, Math.max(0, discountPercent))
7928
+ : 0;
7929
+ return pct > 0 ? amount * (1 - pct / 100) : amount;
7930
+ }
7931
+ const n = Number(raw);
7932
+ return Number.isFinite(n) ? n : NaN;
7933
+ }
7934
+ __name(getPriceOrNumberValue, 'getPriceOrNumberValue');
7935
+ function getNumericValue(doc, field) {
7936
+ return getPriceOrNumberValue(doc[field]);
7937
+ }
7938
+ __name(getNumericValue, 'getNumericValue');
7229
7939
  function computeMetric(docs, metric) {
7230
7940
  let filtered = docs;
7231
7941
  if (metric.filter) {
7232
7942
  filtered = docs.filter((doc) => {
7233
7943
  const value = doc[metric.filter.field];
7944
+ const comparable =
7945
+ value != null && typeof value === 'object' && 'amount' in value
7946
+ ? getPriceOrNumberValue(value)
7947
+ : typeof value === 'number' || value == null
7948
+ ? value
7949
+ : Number(value);
7234
7950
  switch (metric.filter.operator) {
7235
7951
  case '==':
7236
7952
  return value === metric.filter.value;
7237
7953
  case '!=':
7238
7954
  return value !== metric.filter.value;
7239
7955
  case '>':
7240
- return value > metric.filter.value;
7956
+ return comparable > metric.filter.value;
7241
7957
  case '<':
7242
- return value < metric.filter.value;
7958
+ return comparable < metric.filter.value;
7243
7959
  case '>=':
7244
- return value >= metric.filter.value;
7960
+ return comparable >= metric.filter.value;
7245
7961
  case '<=':
7246
- return value <= metric.filter.value;
7962
+ return comparable <= metric.filter.value;
7247
7963
  default:
7248
7964
  return true;
7249
7965
  }
@@ -7254,31 +7970,31 @@ function computeMetric(docs, metric) {
7254
7970
  return filtered.length;
7255
7971
  case 'sum': {
7256
7972
  return filtered.reduce((sum, doc) => {
7257
- const val = Number(doc[metric.field]) || 0;
7258
- return sum + val;
7973
+ const val = getNumericValue(doc, metric.field);
7974
+ return sum + (Number.isFinite(val) ? val : 0);
7259
7975
  }, 0);
7260
7976
  }
7261
7977
  case 'avg': {
7262
7978
  if (filtered.length === 0) return null;
7263
7979
  const sum = filtered.reduce((s, doc) => {
7264
- const val = Number(doc[metric.field]) || 0;
7265
- return s + val;
7980
+ const val = getNumericValue(doc, metric.field);
7981
+ return s + (Number.isFinite(val) ? val : 0);
7266
7982
  }, 0);
7267
7983
  return sum / filtered.length;
7268
7984
  }
7269
7985
  case 'min': {
7270
7986
  if (filtered.length === 0) return null;
7271
7987
  return filtered.reduce((min, doc) => {
7272
- const val = Number(doc[metric.field]);
7273
- if (isNaN(val)) return min;
7988
+ const val = getNumericValue(doc, metric.field);
7989
+ if (!Number.isFinite(val)) return min;
7274
7990
  return min === null ? val : Math.min(min, val);
7275
7991
  }, null);
7276
7992
  }
7277
7993
  case 'max': {
7278
7994
  if (filtered.length === 0) return null;
7279
7995
  return filtered.reduce((max, doc) => {
7280
- const val = Number(doc[metric.field]);
7281
- if (isNaN(val)) return max;
7996
+ const val = getNumericValue(doc, metric.field);
7997
+ if (!Number.isFinite(val)) return max;
7282
7998
  return max === null ? val : Math.max(max, val);
7283
7999
  }, null);
7284
8000
  }
@@ -7394,7 +8110,7 @@ var aggregateEntities = /* @__PURE__ */ __name(
7394
8110
 
7395
8111
  // src/firebase/crud/create.ts
7396
8112
  init_dist();
7397
- init_server4();
8113
+ init_server2();
7398
8114
  init_server3();
7399
8115
 
7400
8116
  // src/shared/github.ts
@@ -7617,49 +8333,6 @@ function updateMetadata(userId) {
7617
8333
  __name(updateMetadata, 'updateMetadata');
7618
8334
 
7619
8335
  // src/shared/firebase.ts
7620
- function createTimestamp2(date) {
7621
- return {
7622
- seconds: Math.floor(date.getTime() / 1e3),
7623
- nanoseconds: (date.getTime() % 1e3) * 1e6,
7624
- toDate: /* @__PURE__ */ __name(() => new Date(date), 'toDate'),
7625
- toMillis: /* @__PURE__ */ __name(() => date.getTime(), 'toMillis'),
7626
- isEqual: /* @__PURE__ */ __name(
7627
- (other) =>
7628
- other.seconds === Math.floor(date.getTime() / 1e3) &&
7629
- other.nanoseconds === (date.getTime() % 1e3) * 1e6,
7630
- 'isEqual'
7631
- ),
7632
- valueOf: /* @__PURE__ */ __name(
7633
- () =>
7634
- `Timestamp(seconds=${Math.floor(date.getTime() / 1e3)}, nanoseconds=${(date.getTime() % 1e3) * 1e6})`,
7635
- 'valueOf'
7636
- ),
7637
- };
7638
- }
7639
- __name(createTimestamp2, 'createTimestamp');
7640
- function toTimestamp2(date) {
7641
- try {
7642
- if (typeof date === 'string') {
7643
- const parsed = new Date(date);
7644
- if (isNaN(parsed.getTime())) {
7645
- throw new Error(`Invalid date string format: ${date}`);
7646
- }
7647
- return createTimestamp2(parsed);
7648
- }
7649
- if (date instanceof Date) {
7650
- if (isNaN(date.getTime())) {
7651
- throw new Error('Invalid Date object');
7652
- }
7653
- return createTimestamp2(date);
7654
- }
7655
- throw new Error('Date must be a string or Date object');
7656
- } catch (error) {
7657
- throw new Error(
7658
- `Failed to convert to timestamp: ${error instanceof Error ? error.message : 'Unknown error'}`
7659
- );
7660
- }
7661
- }
7662
- __name(toTimestamp2, 'toTimestamp');
7663
8336
  function toISOString(timestamp) {
7664
8337
  return timestamp.toDate().toISOString();
7665
8338
  }
@@ -7721,9 +8394,7 @@ function prepareForFirestore2(data, removeFields = []) {
7721
8394
  continue;
7722
8395
  }
7723
8396
  if (value instanceof Date) {
7724
- prepared[key] = toTimestamp2(value);
7725
- } else if (typeof value === 'string' && isISODateString2(value)) {
7726
- prepared[key] = toTimestamp2(value);
8397
+ prepared[key] = value.toISOString();
7727
8398
  } else {
7728
8399
  prepared[key] = prepareForFirestore2(value, removeFields);
7729
8400
  }
@@ -7731,34 +8402,78 @@ function prepareForFirestore2(data, removeFields = []) {
7731
8402
  return prepared;
7732
8403
  }
7733
8404
  if (data instanceof Date) {
7734
- return toTimestamp2(data);
7735
- }
7736
- if (typeof data === 'string' && isISODateString2(data)) {
7737
- return toTimestamp2(data);
8405
+ return data.toISOString();
7738
8406
  }
7739
8407
  return data;
7740
8408
  }
7741
8409
  __name(prepareForFirestore2, 'prepareForFirestore');
7742
- function isISODateString2(str) {
7743
- if (typeof str !== 'string') return false;
7744
- const isoDatePattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z?$/;
7745
- if (!isoDatePattern.test(str)) return false;
7746
- const date = new Date(str);
7747
- return (
7748
- !isNaN(date.getTime()) &&
7749
- date.toISOString().startsWith(str.substring(0, 19))
7750
- );
7751
- }
7752
- __name(isISODateString2, 'isISODateString');
7753
8410
 
7754
8411
  // src/firebase/crud/create.ts
8412
+ function normalizeValue(value) {
8413
+ if (typeof value === 'string') {
8414
+ return value.toLowerCase();
8415
+ }
8416
+ return value;
8417
+ }
8418
+ __name(normalizeValue, 'normalizeValue');
8419
+ function normalizePayloadForUniqueKeys(payload, uniqueKeys) {
8420
+ const normalized = { ...payload };
8421
+ for (const uniqueKey of uniqueKeys) {
8422
+ for (const field of uniqueKey.fields) {
8423
+ if (typeof normalized[field] === 'string') {
8424
+ normalized[field] = normalized[field].toLowerCase();
8425
+ }
8426
+ }
8427
+ }
8428
+ return normalized;
8429
+ }
8430
+ __name(normalizePayloadForUniqueKeys, 'normalizePayloadForUniqueKeys');
8431
+ async function checkUniqueKeys(collection, payload, uniqueKeys, isDraft) {
8432
+ const db = getFirebaseAdminFirestore();
8433
+ for (const uniqueKey of uniqueKeys) {
8434
+ const skipForDrafts = uniqueKey.skipForDrafts !== false;
8435
+ if (isDraft && skipForDrafts) continue;
8436
+ const allFieldsHaveValues = uniqueKey.fields.every(
8437
+ (field) => payload[field] != null && payload[field] !== ''
8438
+ );
8439
+ if (!allFieldsHaveValues) continue;
8440
+ let query = db.collection(collection);
8441
+ for (const field of uniqueKey.fields) {
8442
+ query = query.where(field, '==', normalizeValue(payload[field]));
8443
+ }
8444
+ const existing = await query.limit(1).get();
8445
+ if (!existing.empty) {
8446
+ const firstDoc = existing.docs[0];
8447
+ const existingDoc = transformFirestoreData2({
8448
+ id: firstDoc.id,
8449
+ ...firstDoc.data(),
8450
+ });
8451
+ if (uniqueKey.findOrCreate) {
8452
+ return { found: true, existingDoc, findOrCreate: true };
8453
+ }
8454
+ const fieldNames = uniqueKey.fields.join(' + ');
8455
+ throw new DoNotDevError(
8456
+ uniqueKey.errorMessage || `Duplicate ${fieldNames}`,
8457
+ 'already-exists',
8458
+ {
8459
+ details: {
8460
+ fields: uniqueKey.fields,
8461
+ existingId: firstDoc.id,
8462
+ },
8463
+ }
8464
+ );
8465
+ }
8466
+ }
8467
+ return { found: false };
8468
+ }
8469
+ __name(checkUniqueKeys, 'checkUniqueKeys');
7755
8470
  function createEntityLogicFactory(collection, documentSchema) {
7756
8471
  return /* @__PURE__ */ __name(async function createEntityLogic(
7757
8472
  data,
7758
8473
  context
7759
8474
  ) {
7760
8475
  const { payload, idempotencyKey } = data;
7761
- const uid = await assertAdmin(context.uid);
8476
+ const { uid } = context;
7762
8477
  if (idempotencyKey) {
7763
8478
  const db2 = getFirebaseAdminFirestore();
7764
8479
  const idempotencyRef = db2
@@ -7771,11 +8486,28 @@ function createEntityLogicFactory(collection, documentSchema) {
7771
8486
  }
7772
8487
  const status = payload.status ?? DEFAULT_STATUS_VALUE;
7773
8488
  const isDraft = status === 'draft';
8489
+ const schemaWithMeta = documentSchema;
8490
+ const uniqueKeys = schemaWithMeta.metadata?.uniqueKeys;
8491
+ if (uniqueKeys && uniqueKeys.length > 0) {
8492
+ const checkResult = await checkUniqueKeys(
8493
+ collection,
8494
+ payload,
8495
+ uniqueKeys,
8496
+ isDraft
8497
+ );
8498
+ if (checkResult.found && checkResult.findOrCreate) {
8499
+ return checkResult.existingDoc;
8500
+ }
8501
+ }
8502
+ const normalizedPayload =
8503
+ uniqueKeys && uniqueKeys.length > 0
8504
+ ? normalizePayloadForUniqueKeys(payload, uniqueKeys)
8505
+ : payload;
7774
8506
  if (!isDraft) {
7775
- validateDocument(payload, documentSchema);
8507
+ validateDocument(normalizedPayload, documentSchema);
7776
8508
  }
7777
8509
  const documentData = {
7778
- ...prepareForFirestore2(payload),
8510
+ ...prepareForFirestore2(normalizedPayload),
7779
8511
  status,
7780
8512
  // Ensure status is always present
7781
8513
  ...createMetadata(uid),
@@ -7802,7 +8534,7 @@ function createEntityLogicFactory(collection, documentSchema) {
7802
8534
  }
7803
8535
  __name(createEntityLogicFactory, 'createEntityLogicFactory');
7804
8536
  var createEntity = /* @__PURE__ */ __name(
7805
- (collection, documentSchema, customSchema) => {
8537
+ (collection, documentSchema, requiredRole, customSchema) => {
7806
8538
  const requestSchema =
7807
8539
  customSchema ||
7808
8540
  object({
@@ -7813,22 +8545,22 @@ var createEntity = /* @__PURE__ */ __name(
7813
8545
  CRUD_CONFIG,
7814
8546
  requestSchema,
7815
8547
  'create_entity',
7816
- createEntityLogicFactory(collection, documentSchema)
8548
+ createEntityLogicFactory(collection, documentSchema),
8549
+ requiredRole
7817
8550
  );
7818
8551
  },
7819
8552
  'createEntity'
7820
8553
  );
7821
8554
 
7822
8555
  // src/firebase/crud/delete.ts
7823
- init_server4();
7824
8556
  init_dist();
8557
+ init_server3();
7825
8558
  function deleteEntityLogicFactory(collection) {
7826
8559
  return /* @__PURE__ */ __name(async function deleteEntityLogic(
7827
8560
  data,
7828
8561
  context
7829
8562
  ) {
7830
8563
  const { id } = data;
7831
- await assertAdmin(context.uid);
7832
8564
  const references = await findReferences(collection, id);
7833
8565
  if (references.length > 0) {
7834
8566
  throw new DoNotDevError(
@@ -7843,44 +8575,51 @@ function deleteEntityLogicFactory(collection) {
7843
8575
  }, 'deleteEntityLogic');
7844
8576
  }
7845
8577
  __name(deleteEntityLogicFactory, 'deleteEntityLogicFactory');
7846
- var deleteEntity = /* @__PURE__ */ __name((collection, customSchema) => {
7847
- const requestSchema =
7848
- customSchema ||
7849
- object({
7850
- id: pipe(string(), minLength(1)),
7851
- });
7852
- return createBaseFunction(
7853
- CRUD_CONFIG,
7854
- requestSchema,
7855
- 'delete_entity',
7856
- deleteEntityLogicFactory(collection)
7857
- );
7858
- }, 'deleteEntity');
8578
+ var deleteEntity = /* @__PURE__ */ __name(
8579
+ (collection, requiredRole, customSchema) => {
8580
+ const requestSchema =
8581
+ customSchema ||
8582
+ object({
8583
+ id: pipe(string(), minLength(1)),
8584
+ });
8585
+ return createBaseFunction(
8586
+ CRUD_CONFIG,
8587
+ requestSchema,
8588
+ 'delete_entity',
8589
+ deleteEntityLogicFactory(collection),
8590
+ requiredRole
8591
+ );
8592
+ },
8593
+ 'deleteEntity'
8594
+ );
7859
8595
 
7860
8596
  // src/firebase/crud/get.ts
7861
8597
  init_dist();
8598
+ init_server2();
7862
8599
  init_server3();
7863
- init_server3();
7864
- init_server4();
7865
- function getEntityLogicFactory(collection, documentSchema) {
8600
+ function getEntityLogicFactory(collection, documentSchema, ownership) {
7866
8601
  return /* @__PURE__ */ __name(async function getEntityLogic(data, context) {
7867
8602
  const { id } = data;
8603
+ const { userRole, uid } = context;
7868
8604
  const db = getFirebaseAdminFirestore();
7869
8605
  const docRef = db.collection(collection).doc(id);
7870
8606
  const doc = await docRef.get();
7871
8607
  if (!doc.exists) {
7872
8608
  throw new DoNotDevError('Entity not found', 'not-found');
7873
8609
  }
7874
- const userRole = getUserRole(context.request.auth);
7875
- const isAdmin = userRole === 'admin' || userRole === 'super';
8610
+ const isAdmin = hasRoleAccess(userRole, 'admin');
7876
8611
  const docData = doc.data();
7877
8612
  if (!isAdmin && HIDDEN_STATUSES.includes(docData?.status)) {
7878
8613
  throw new DoNotDevError('Entity not found', 'not-found');
7879
8614
  }
8615
+ const rawData = docData || {};
8616
+ const visibilityOptions =
8617
+ ownership && uid ? { documentData: rawData, uid, ownership } : void 0;
7880
8618
  const filteredData = filterVisibleFields(
7881
- docData || {},
8619
+ rawData,
7882
8620
  documentSchema,
7883
- userRole
8621
+ userRole,
8622
+ visibilityOptions
7884
8623
  );
7885
8624
  return transformFirestoreData2({
7886
8625
  id: doc.id,
@@ -7890,41 +8629,68 @@ function getEntityLogicFactory(collection, documentSchema) {
7890
8629
  }
7891
8630
  __name(getEntityLogicFactory, 'getEntityLogicFactory');
7892
8631
  var getEntity = /* @__PURE__ */ __name(
7893
- (collection, documentSchema, customSchema) => {
8632
+ (collection, documentSchema, requiredRole, customSchema, ownership) => {
7894
8633
  const requestSchema =
7895
8634
  customSchema ||
7896
8635
  object({
7897
8636
  id: pipe(string(), minLength(1)),
7898
8637
  });
7899
8638
  return createBaseFunction(
7900
- CRUD_CONFIG,
8639
+ CRUD_READ_CONFIG,
7901
8640
  requestSchema,
7902
8641
  'get_entity',
7903
- getEntityLogicFactory(collection, documentSchema)
8642
+ getEntityLogicFactory(collection, documentSchema, ownership),
8643
+ requiredRole
7904
8644
  );
7905
8645
  },
7906
8646
  'getEntity'
7907
8647
  );
7908
8648
 
7909
8649
  // src/firebase/crud/list.ts
7910
- init_server4();
7911
- init_server3();
7912
8650
  init_dist();
7913
- init_server4();
8651
+ init_server2();
7914
8652
  init_server3();
7915
- function listEntitiesLogicFactory(collection, documentSchema) {
8653
+ function applyPublicCondition(query, publicCondition) {
8654
+ let q = query;
8655
+ for (const c of publicCondition) {
8656
+ q = q.where(c.field, c.op, c.value);
8657
+ }
8658
+ return q;
8659
+ }
8660
+ __name(applyPublicCondition, 'applyPublicCondition');
8661
+ function listEntitiesLogicFactory(
8662
+ collection,
8663
+ documentSchema,
8664
+ listFields,
8665
+ ownership,
8666
+ isListCard
8667
+ ) {
7916
8668
  return /* @__PURE__ */ __name(async function listEntitiesLogic(
7917
8669
  data,
7918
8670
  context
7919
8671
  ) {
7920
- const { where = [], orderBy = [], limit = 50, startAfterId, search } = data;
7921
- const userRole = getUserRole(context.request.auth);
7922
- const isAdmin = userRole === 'admin' || userRole === 'super';
8672
+ const { where = [], orderBy = [], limit, startAfterId, search } = data;
8673
+ const { userRole, uid } = context;
8674
+ const isAdmin = hasRoleAccess(userRole, 'admin');
7923
8675
  const db = getFirebaseAdminFirestore();
7924
8676
  let query = db.collection(collection);
7925
8677
  if (!isAdmin) {
7926
8678
  query = query.where('status', 'not-in', [...HIDDEN_STATUSES]);
7927
8679
  }
8680
+ if (ownership && !isAdmin) {
8681
+ if (
8682
+ isListCard &&
8683
+ ownership.publicCondition &&
8684
+ ownership.publicCondition.length > 0
8685
+ ) {
8686
+ query = applyPublicCondition(query, ownership.publicCondition);
8687
+ } else if (!isListCard && ownership.ownerFields.length > 0) {
8688
+ const firstOwnerField = ownership.ownerFields[0];
8689
+ query = query.where(firstOwnerField, '==', uid);
8690
+ if (ownership.ownerFields.length > 1) {
8691
+ }
8692
+ }
8693
+ }
7928
8694
  if (search) {
7929
8695
  const { field, query: searchQuery } = search;
7930
8696
  query = query
@@ -7947,12 +8713,70 @@ function listEntitiesLogicFactory(collection, documentSchema) {
7947
8713
  }
7948
8714
  query = query.startAfter(startAfterDoc);
7949
8715
  }
7950
- query = query.limit(limit);
8716
+ if (limit !== void 0 && limit > 0) {
8717
+ query = query.limit(limit);
8718
+ }
8719
+ console.log(
8720
+ `[listEntities] Collection: ${collection}, UserRole: ${userRole}, IsAdmin: ${isAdmin}`
8721
+ );
8722
+ console.log(
8723
+ `[listEntities] Filters - where: ${JSON.stringify(where)}, orderBy: ${JSON.stringify(orderBy)}, limit: ${limit}`
8724
+ );
7951
8725
  const snapshot = await query.get();
7952
- const docs = snapshot.docs.map((doc) => ({
7953
- id: doc.id,
7954
- ...filterVisibleFields(doc.data() || {}, documentSchema, userRole),
7955
- }));
8726
+ console.log(
8727
+ `[listEntities] Query returned ${snapshot.docs.length} documents`
8728
+ );
8729
+ const schemaHasEntries = !!documentSchema?.entries;
8730
+ console.log(`[listEntities] Schema has entries: ${schemaHasEntries}`);
8731
+ const isPictureObject = /* @__PURE__ */ __name((value) => {
8732
+ return (
8733
+ typeof value === 'object' &&
8734
+ value !== null &&
8735
+ 'thumbUrl' in value &&
8736
+ 'fullUrl' in value
8737
+ );
8738
+ }, 'isPictureObject');
8739
+ const optimizePictureField = /* @__PURE__ */ __name((value) => {
8740
+ if (Array.isArray(value) && value.length > 0) {
8741
+ const firstPicture = value[0];
8742
+ if (isPictureObject(firstPicture)) {
8743
+ return firstPicture.thumbUrl || firstPicture.fullUrl || null;
8744
+ }
8745
+ if (typeof firstPicture === 'string') {
8746
+ return firstPicture;
8747
+ }
8748
+ } else if (isPictureObject(value)) {
8749
+ return value.thumbUrl || value.fullUrl || null;
8750
+ }
8751
+ return value;
8752
+ }, 'optimizePictureField');
8753
+ const visibilityOptions = ownership && uid ? { uid, ownership } : void 0;
8754
+ const docs = snapshot.docs.map((doc) => {
8755
+ const rawData = doc.data() || {};
8756
+ const visibleData = filterVisibleFields(
8757
+ rawData,
8758
+ documentSchema,
8759
+ userRole,
8760
+ visibilityOptions
8761
+ ? { ...visibilityOptions, documentData: rawData }
8762
+ : void 0
8763
+ );
8764
+ if (listFields && listFields.length > 0) {
8765
+ const filtered = { id: doc.id };
8766
+ for (const field of listFields) {
8767
+ if (field in visibleData) {
8768
+ const value = visibleData[field];
8769
+ filtered[field] = optimizePictureField(value);
8770
+ }
8771
+ }
8772
+ return filtered;
8773
+ }
8774
+ const optimizedData = { id: doc.id };
8775
+ for (const [key, value] of Object.entries(visibleData)) {
8776
+ optimizedData[key] = optimizePictureField(value);
8777
+ }
8778
+ return optimizedData;
8779
+ });
7956
8780
  return {
7957
8781
  items: transformFirestoreData2(docs),
7958
8782
  lastVisible: snapshot.docs[snapshot.docs.length - 1]?.id || null,
@@ -7963,13 +8787,21 @@ function listEntitiesLogicFactory(collection, documentSchema) {
7963
8787
  }
7964
8788
  __name(listEntitiesLogicFactory, 'listEntitiesLogicFactory');
7965
8789
  var listEntities = /* @__PURE__ */ __name(
7966
- (collection, documentSchema, customSchema) => {
8790
+ (
8791
+ collection,
8792
+ documentSchema,
8793
+ requiredRole,
8794
+ customSchema,
8795
+ listFields,
8796
+ ownership,
8797
+ isListCard
8798
+ ) => {
7967
8799
  const requestSchema =
7968
8800
  customSchema ||
7969
8801
  object({
7970
8802
  where: optional(array(tuple([string(), any(), any()]))),
7971
8803
  orderBy: optional(array(tuple([string(), picklist(['asc', 'desc'])]))),
7972
- limit: optional(pipe(number(), minValue(1), maxValue(100))),
8804
+ limit: optional(pipe(number(), minValue(1))),
7973
8805
  startAfterId: optional(string()),
7974
8806
  search: optional(
7975
8807
  object({
@@ -7979,10 +8811,17 @@ var listEntities = /* @__PURE__ */ __name(
7979
8811
  ),
7980
8812
  });
7981
8813
  return createBaseFunction(
7982
- CRUD_CONFIG,
8814
+ CRUD_READ_CONFIG,
7983
8815
  requestSchema,
7984
8816
  'list_entities',
7985
- listEntitiesLogicFactory(collection, documentSchema)
8817
+ listEntitiesLogicFactory(
8818
+ collection,
8819
+ documentSchema,
8820
+ listFields,
8821
+ ownership,
8822
+ isListCard
8823
+ ),
8824
+ requiredRole
7986
8825
  );
7987
8826
  },
7988
8827
  'listEntities'
@@ -7990,15 +8829,76 @@ var listEntities = /* @__PURE__ */ __name(
7990
8829
 
7991
8830
  // src/firebase/crud/update.ts
7992
8831
  init_dist();
7993
- init_server4();
8832
+ init_server2();
7994
8833
  init_server3();
8834
+ function normalizeValue2(value) {
8835
+ if (typeof value === 'string') {
8836
+ return value.toLowerCase();
8837
+ }
8838
+ return value;
8839
+ }
8840
+ __name(normalizeValue2, 'normalizeValue');
8841
+ function normalizePayloadForUniqueKeys2(payload, uniqueKeys) {
8842
+ const normalized = { ...payload };
8843
+ for (const uniqueKey of uniqueKeys) {
8844
+ for (const field of uniqueKey.fields) {
8845
+ if (typeof normalized[field] === 'string') {
8846
+ normalized[field] = normalized[field].toLowerCase();
8847
+ }
8848
+ }
8849
+ }
8850
+ return normalized;
8851
+ }
8852
+ __name(normalizePayloadForUniqueKeys2, 'normalizePayloadForUniqueKeys');
8853
+ async function checkUniqueKeysForUpdate(
8854
+ collection,
8855
+ currentDocId,
8856
+ mergedData,
8857
+ payload,
8858
+ uniqueKeys,
8859
+ isDraft
8860
+ ) {
8861
+ const db = getFirebaseAdminFirestore();
8862
+ for (const uniqueKey of uniqueKeys) {
8863
+ const skipForDrafts = uniqueKey.skipForDrafts !== false;
8864
+ if (isDraft && skipForDrafts) continue;
8865
+ const isUpdatingUniqueKeyField = uniqueKey.fields.some(
8866
+ (field) => field in payload
8867
+ );
8868
+ if (!isUpdatingUniqueKeyField) continue;
8869
+ const allFieldsHaveValues = uniqueKey.fields.every(
8870
+ (field) => mergedData[field] != null && mergedData[field] !== ''
8871
+ );
8872
+ if (!allFieldsHaveValues) continue;
8873
+ let query = db.collection(collection);
8874
+ for (const field of uniqueKey.fields) {
8875
+ query = query.where(field, '==', normalizeValue2(mergedData[field]));
8876
+ }
8877
+ const existing = await query.limit(2).get();
8878
+ const conflictingDoc = existing.docs.find((doc) => doc.id !== currentDocId);
8879
+ if (conflictingDoc) {
8880
+ const fieldNames = uniqueKey.fields.join(' + ');
8881
+ throw new DoNotDevError(
8882
+ uniqueKey.errorMessage || `Duplicate ${fieldNames}`,
8883
+ 'already-exists',
8884
+ {
8885
+ details: {
8886
+ fields: uniqueKey.fields,
8887
+ existingId: conflictingDoc.id,
8888
+ },
8889
+ }
8890
+ );
8891
+ }
8892
+ }
8893
+ }
8894
+ __name(checkUniqueKeysForUpdate, 'checkUniqueKeysForUpdate');
7995
8895
  function updateEntityLogicFactory(collection, documentSchema) {
7996
8896
  return /* @__PURE__ */ __name(async function updateEntityLogic(
7997
8897
  data,
7998
8898
  context
7999
8899
  ) {
8000
8900
  const { id, payload, idempotencyKey } = data;
8001
- const uid = await assertAdmin(context.uid);
8901
+ const { uid } = context;
8002
8902
  if (idempotencyKey) {
8003
8903
  const db2 = getFirebaseAdminFirestore();
8004
8904
  const idempotencyRef = db2
@@ -8019,11 +8919,27 @@ function updateEntityLogicFactory(collection, documentSchema) {
8019
8919
  const mergedData = { ...currentData, ...payload };
8020
8920
  const resultingStatus = mergedData.status ?? DEFAULT_STATUS_VALUE;
8021
8921
  const isDraft = resultingStatus === 'draft';
8922
+ const schemaWithMeta = documentSchema;
8923
+ const uniqueKeys = schemaWithMeta.metadata?.uniqueKeys;
8924
+ if (uniqueKeys && uniqueKeys.length > 0) {
8925
+ await checkUniqueKeysForUpdate(
8926
+ collection,
8927
+ id,
8928
+ mergedData,
8929
+ payload,
8930
+ uniqueKeys,
8931
+ isDraft
8932
+ );
8933
+ }
8022
8934
  if (!isDraft) {
8023
8935
  validateDocument(mergedData, documentSchema);
8024
8936
  }
8937
+ const normalizedPayload =
8938
+ uniqueKeys && uniqueKeys.length > 0
8939
+ ? normalizePayloadForUniqueKeys2(payload, uniqueKeys)
8940
+ : payload;
8025
8941
  const updateData = {
8026
- ...prepareForFirestore2(payload),
8942
+ ...prepareForFirestore2(normalizedPayload),
8027
8943
  ...updateMetadata(uid),
8028
8944
  };
8029
8945
  await docRef.update(updateData);
@@ -8047,7 +8963,7 @@ function updateEntityLogicFactory(collection, documentSchema) {
8047
8963
  }
8048
8964
  __name(updateEntityLogicFactory, 'updateEntityLogicFactory');
8049
8965
  var updateEntity = /* @__PURE__ */ __name(
8050
- (collection, documentSchema, customSchema) => {
8966
+ (collection, documentSchema, requiredRole, customSchema) => {
8051
8967
  const requestSchema =
8052
8968
  customSchema ||
8053
8969
  object({
@@ -8059,14 +8975,15 @@ var updateEntity = /* @__PURE__ */ __name(
8059
8975
  CRUD_CONFIG,
8060
8976
  requestSchema,
8061
8977
  'update_entity',
8062
- updateEntityLogicFactory(collection, documentSchema)
8978
+ updateEntityLogicFactory(collection, documentSchema),
8979
+ requiredRole
8063
8980
  );
8064
8981
  },
8065
8982
  'updateEntity'
8066
8983
  );
8067
8984
 
8068
8985
  // src/firebase/helpers/githubAccessHelper.ts
8069
- init_server4();
8986
+ init_server3();
8070
8987
  import { logger as logger8 } from 'firebase-functions/v2';
8071
8988
  async function grantGitHubAccessHelper(
8072
8989
  userId,
@@ -8178,7 +9095,7 @@ async function setCustomClaimsHelper(userId, claims, merge = true) {
8178
9095
  __name(setCustomClaimsHelper, 'setCustomClaimsHelper');
8179
9096
 
8180
9097
  // src/firebase/helpers/githubTeamAccessHelper.ts
8181
- init_server4();
9098
+ init_server3();
8182
9099
  import { logger as logger9 } from 'firebase-functions/v2';
8183
9100
  async function grantGitHubTeamAccessHelper(
8184
9101
  userId,
@@ -8337,7 +9254,7 @@ async function checkGitHubTeamAccessHelper(userId, githubUsername, teamConfig) {
8337
9254
  __name(checkGitHubTeamAccessHelper, 'checkGitHubTeamAccessHelper');
8338
9255
 
8339
9256
  // src/firebase/oauth/disconnect.ts
8340
- init_server4();
9257
+ init_server2();
8341
9258
  init_server3();
8342
9259
  import {
8343
9260
  onCall as onCall2,
@@ -8404,7 +9321,7 @@ async function revokeToken(provider, accessToken) {
8404
9321
  __name(revokeToken, 'revokeToken');
8405
9322
 
8406
9323
  // src/firebase/oauth/exchangeToken.ts
8407
- init_server4();
9324
+ init_server2();
8408
9325
  init_server3();
8409
9326
  import {
8410
9327
  onCall as onCall3,
@@ -8578,7 +9495,7 @@ async function saveOAuthConnection(data) {
8578
9495
  __name(saveOAuthConnection, 'saveOAuthConnection');
8579
9496
 
8580
9497
  // src/firebase/oauth/getConnections.ts
8581
- init_server4();
9498
+ init_server3();
8582
9499
  import {
8583
9500
  onCall as onCall4,
8584
9501
  HttpsError as HttpsError4,
@@ -8629,8 +9546,8 @@ var getConnections = onCall4(async (request) => {
8629
9546
  });
8630
9547
 
8631
9548
  // src/firebase/oauth/githubAccess.ts
8632
- init_server4();
8633
9549
  init_dist();
9550
+ init_server2();
8634
9551
  init_server3();
8635
9552
  import { logger as logger10 } from 'firebase-functions/v2';
8636
9553
  import { onCall as onCall5 } from 'firebase-functions/v2/https';
@@ -8835,7 +9752,7 @@ async function checkGitHubAccessWithSchema(request, customSchema) {
8835
9752
  __name(checkGitHubAccessWithSchema, 'checkGitHubAccessWithSchema');
8836
9753
 
8837
9754
  // src/firebase/oauth/refreshToken.ts
8838
- init_server4();
9755
+ init_server2();
8839
9756
  init_server3();
8840
9757
  import {
8841
9758
  onCall as onCall6,
@@ -8941,7 +9858,7 @@ var refreshToken = onCall6(async (request) => {
8941
9858
  });
8942
9859
 
8943
9860
  // src/firebase/scheduled/checkExpiredSubscriptions.ts
8944
- init_server4();
9861
+ init_server3();
8945
9862
  import { logger as logger11 } from 'firebase-functions/v2';
8946
9863
  import { onSchedule } from 'firebase-functions/v2/scheduler';
8947
9864
  var checkExpiredSubscriptions = onSchedule(
@@ -9029,24 +9946,62 @@ async function revokeExpiredSubscription(userId, subscription) {
9029
9946
  __name(revokeExpiredSubscription, 'revokeExpiredSubscription');
9030
9947
 
9031
9948
  // src/firebase/registerCrudFunctions.ts
9032
- init_server3();
9033
- function registerCrudFunctions(
9034
- entities,
9035
- target = module.exports,
9036
- options = {}
9037
- ) {
9949
+ init_server2();
9950
+ function createCrudFunctions(entities, options = {}) {
9038
9951
  const { prefix = '' } = options;
9952
+ const functions = {};
9039
9953
  for (const [key, value] of Object.entries(entities)) {
9040
9954
  if (!isEntity(value)) continue;
9041
9955
  const entity = value;
9042
9956
  const col = entity.collection;
9043
9957
  const schemas = createSchemas(entity);
9044
- target[`${prefix}create_${col}`] = createEntity(col, schemas.create);
9045
- target[`${prefix}get_${col}`] = getEntity(col, schemas.get);
9046
- target[`${prefix}list_${col}`] = listEntities(col, schemas.list);
9047
- target[`${prefix}update_${col}`] = updateEntity(col, schemas.update);
9048
- target[`${prefix}delete_${col}`] = deleteEntity(col, schemas.delete);
9958
+ const access = entity.access;
9959
+ functions[`${prefix}create_${col}`] = createEntity(
9960
+ col,
9961
+ schemas.create,
9962
+ access.create
9963
+ );
9964
+ functions[`${prefix}get_${col}`] = getEntity(
9965
+ col,
9966
+ schemas.get,
9967
+ access.read,
9968
+ void 0,
9969
+ entity.ownership
9970
+ );
9971
+ functions[`${prefix}list_${col}`] = listEntities(
9972
+ col,
9973
+ schemas.get,
9974
+ access.read,
9975
+ void 0,
9976
+ entity.listFields,
9977
+ entity.ownership,
9978
+ false
9979
+ );
9980
+ functions[`${prefix}listCard_${col}`] = listEntities(
9981
+ col,
9982
+ schemas.get,
9983
+ access.read,
9984
+ void 0,
9985
+ entity.listCardFields ?? entity.listFields ?? void 0,
9986
+ entity.ownership,
9987
+ true
9988
+ );
9989
+ functions[`${prefix}update_${col}`] = updateEntity(
9990
+ col,
9991
+ schemas.update,
9992
+ access.update
9993
+ );
9994
+ functions[`${prefix}delete_${col}`] = deleteEntity(col, access.delete);
9995
+ }
9996
+ return functions;
9997
+ }
9998
+ __name(createCrudFunctions, 'createCrudFunctions');
9999
+ function registerCrudFunctions(entities, target, options = {}) {
10000
+ const functions = createCrudFunctions(entities, options);
10001
+ if (target) {
10002
+ Object.assign(target, functions);
9049
10003
  }
10004
+ return functions;
9050
10005
  }
9051
10006
  __name(registerCrudFunctions, 'registerCrudFunctions');
9052
10007
  function isEntity(value) {
@@ -9062,6 +10017,7 @@ export {
9062
10017
  AUTH_CONFIG,
9063
10018
  AVAILABLE_REGIONS,
9064
10019
  CRUD_CONFIG,
10020
+ CRUD_READ_CONFIG,
9065
10021
  FIREBASE_REGION,
9066
10022
  FUNCTION_CONFIG,
9067
10023
  STRIPE_CONFIG,
@@ -9075,6 +10031,7 @@ export {
9075
10031
  checkGitHubTeamAccessHelper,
9076
10032
  createBaseFunction,
9077
10033
  createCheckoutSession,
10034
+ createCrudFunctions,
9078
10035
  createCustomerPortal,
9079
10036
  createEntity,
9080
10037
  createIdempotencyStore,