@buka/nestjs-kit 4.1.8 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -336,114 +336,181 @@ function IsScalarDictionary(ctor, validationOptions) {
336
336
  //#endregion
337
337
  //#region src/modules/core/models/urn.ts
338
338
  const URN_PREFIX = "urn:buka:";
339
- const URN_PATTERN = /^urn:buka:([a-z][a-z0-9-]*)(?::([a-z][a-z0-9-]*)(?::(.+))?)?$/;
340
339
  /**
341
340
  * 统一资源名称(URN)
342
341
  *
343
- * 格式: urn:buka:<namespace>[:<resource>[:<identifier>]]
342
+ * 格式: urn:buka:<domain>:<resource-type>[:<resource-id>]
344
343
  *
345
344
  * 支持三种粒度:
346
- * - namespace 级: urn:buka:galaxy
345
+ * - 概念域级: urn:buka:galaxy
347
346
  * - 资源类型级: urn:buka:galaxy:principal
348
347
  * - 实例级: urn:buka:galaxy:principal:550e8400-e29b-41d4-a716-446655440000
349
348
  *
350
- * namespace 划分原则:按资源类型的定义权归属划分,非按部署单元。
349
+ * domain 划分原则:按资源类型的定义权归属划分,非按部署单元。
350
+ * resource-type 第一级推荐用于 env(环境),这是一个语义约定,不强制。
351
351
  *
352
352
  * 推荐通过静态工厂方法或派生方法构建层级 URN:
353
353
  * ```ts
354
- * Urn.of('galaxy') // → NamespaceUrn
355
- * Urn.of('galaxy', 'principal') // → ResourceUrn
356
- * Urn.of('galaxy', 'principal', '550e8400-...') // → IdentifierUrn
354
+ * Urn.of('galaxy') // → DomainUrn
355
+ * Urn.of('galaxy', 'principal') // → ResourceTypeUrn
356
+ * Urn.of('galaxy', 'principal', '550e8400-...') // → ResourceIdUrn
357
357
  *
358
358
  * // 或通过派生方法逐层构建
359
359
  * Urn.of('galaxy')
360
- * .withResource('principal') // → ResourceUrn
361
- * .withIdentifier('550e8400-...') // → IdentifierUrn
360
+ * .withResourceType('principal') // → ResourceTypeUrn
361
+ * .withResourceId('550e8400-...') // → ResourceIdUrn
362
362
  * ```
363
363
  */
364
364
  var Urn = class Urn {
365
- constructor(namespace, resource, identifier) {
366
- this.namespace = namespace;
367
- this.resource = resource;
368
- this.identifier = identifier;
365
+ constructor(domain, resourceType, resourceId) {
366
+ this.domain = domain;
367
+ this.resourceType = resourceType;
368
+ this.resourceId = resourceId;
369
+ if (!/^(?:\*|[a-z][a-z0-9-]*)$/.test(domain)) throw new Error(`Invalid domain: ${domain}`);
370
+ if (resourceType !== void 0) {
371
+ for (const seg of resourceType.split(":")) if (!/^(?:\*|[a-z][a-z0-9-]*)$/.test(seg)) throw new Error(`Invalid resourceType segment: '${seg}' in '${resourceType}'`);
372
+ }
373
+ if (resourceId !== void 0 && !/^(?:\*{1,2}|[a-z0-9][a-z0-9-]*)$/.test(resourceId)) throw new Error(`Invalid resourceId: ${resourceId}`);
369
374
  }
370
375
  /**
371
376
  * 序列化为 URN 字符串
372
377
  */
373
378
  toString() {
374
- let urn = `${URN_PREFIX}${this.namespace}`;
375
- if (this.resource) urn += `:${this.resource}`;
376
- if (this.identifier) urn += `:${this.identifier}`;
379
+ let urn = `${URN_PREFIX}${this.domain}`;
380
+ if (this.resourceType) urn += `:${this.resourceType}`;
381
+ if (this.resourceId) urn += `:${this.resourceId}`;
377
382
  return urn;
378
383
  }
379
384
  /**
385
+ * 返回 resourceType 按 `:` 拆分后的层级数组
386
+ */
387
+ get resourceTypeSegments() {
388
+ return this.resourceType ? this.resourceType.split(":") : [];
389
+ }
390
+ toSegments() {
391
+ const segments = [this.domain];
392
+ if (this.resourceType) segments.push(...this.resourceType.split(":"));
393
+ if (this.resourceId) segments.push(this.resourceId);
394
+ return segments;
395
+ }
396
+ /**
380
397
  * 衍生出资源类型级 URN
381
398
  *
382
- * @throws Error 当前 URN 已有 resource 时抛出
399
+ * @throws Error 当前 URN 已有 resourceType 时抛出
383
400
  */
384
- withResource(resource) {
385
- if (this.resource !== void 0) throw new Error(`Cannot derive ResourceUrn from a URN that already has a resource: ${this.toString()}`);
386
- return new Urn(this.namespace, resource);
401
+ withResourceType(resourceType) {
402
+ if (this.resourceType !== void 0) throw new Error(`Cannot derive ResourceTypeUrn from a URN that already has a resourceType: ${this.toString()}`);
403
+ return new Urn(this.domain, resourceType);
387
404
  }
388
405
  /**
389
406
  * 衍生出实例级 URN
390
407
  *
391
- * @throws Error 当前 URN 无 resource 或已有 identifier 时抛出
408
+ * @throws Error 当前 URN 无 resourceType 或已有 resourceId 时抛出
392
409
  */
393
- withIdentifier(identifier) {
394
- if (this.resource === void 0) throw new Error(`Cannot derive IdentifierUrn from a URN without a resource: ${this.toString()}`);
395
- if (this.identifier !== void 0) throw new Error(`Cannot derive IdentifierUrn from a URN that already has an identifier: ${this.toString()}`);
396
- return new Urn(this.namespace, this.resource, identifier);
410
+ withResourceId(resourceId) {
411
+ if (this.resourceType === void 0) throw new Error(`Cannot derive ResourceIdUrn from a URN without a resourceType: ${this.toString()}`);
412
+ if (this.resourceId !== void 0) throw new Error(`Cannot derive ResourceIdUrn from a URN that already has a resourceId: ${this.toString()}`);
413
+ return new Urn(this.domain, this.resourceType, resourceId);
397
414
  }
398
415
  /**
399
- * 类型守卫:判断是否为 namespace 级 URN
416
+ * 类型守卫:判断是否为概念域级 URN
400
417
  */
401
- isNamespaceUrn() {
402
- return this.resource === void 0;
418
+ isDomainUrn() {
419
+ return this.resourceType === void 0;
403
420
  }
404
421
  /**
405
422
  * 类型守卫:判断是否为资源类型级 URN
406
423
  */
407
- isResourceUrn() {
408
- return this.resource !== void 0 && this.identifier === void 0;
424
+ isResourceTypeUrn() {
425
+ return this.resourceType !== void 0 && this.resourceId === void 0;
409
426
  }
410
427
  /**
411
428
  * 类型守卫:判断是否为实例级 URN
412
429
  */
413
- isIdentifierUrn() {
414
- return this.resource !== void 0 && this.identifier !== void 0;
430
+ isResourceIdUrn() {
431
+ return this.resourceType !== void 0 && this.resourceId !== void 0;
415
432
  }
416
- static of(namespace, resource, identifier) {
417
- return new Urn(namespace, resource, identifier);
433
+ static of(domain, resourceType, resourceId) {
434
+ return new Urn(domain, resourceType, resourceId);
418
435
  }
419
436
  /**
420
- * 从 URN 字符串解析
437
+ * 从 URN 字符串解析,支持通配符 `*` 和 `**`
438
+ *
439
+ * - `*` 匹配恰好一个段
440
+ * - `**` 匹配零个或多个尾部段(仅允许出现在末尾)
421
441
  *
422
442
  * @throws Error URN 格式不合法时抛出
423
443
  */
424
444
  static parse(urn) {
425
- const match = urn.match(URN_PATTERN);
426
- if (!match) throw new Error(`Invalid URN: ${urn}`);
427
- return new Urn(match[1], match[2], match[3]);
445
+ if (!urn.startsWith(URN_PREFIX)) throw new Error(`Invalid URN: ${urn}`);
446
+ const parts = urn.slice(9).split(":");
447
+ if (parts.length === 0 || parts[0] === "") throw new Error(`Invalid URN: ${urn}`);
448
+ const segments = [];
449
+ for (let i = 0; i < parts.length; i++) {
450
+ const part = parts[i];
451
+ if (part === "**") {
452
+ if (i !== parts.length - 1) throw new Error(`Invalid URN: '**' is only allowed at the end: ${urn}`);
453
+ segments.push(part);
454
+ break;
455
+ }
456
+ if (part === "*" || /^[a-z0-9][a-z0-9-]*$/.test(part)) segments.push(part);
457
+ else throw new Error(`Invalid URN segment: '${part}' in ${urn}`);
458
+ }
459
+ if (segments.length === 0) throw new Error(`Invalid URN: ${urn}`);
460
+ const domain = segments[0];
461
+ let resourceType;
462
+ let resourceId;
463
+ if (segments[segments.length - 1] === "**") {
464
+ if (segments.length === 1) {} else if (segments.length === 2) resourceType = segments[1] !== "**" ? segments[1] : void 0;
465
+ else resourceType = segments.slice(1, -1).join(":");
466
+ resourceId = "**";
467
+ } else if (segments.length === 2) resourceType = segments[1];
468
+ else if (segments.length >= 3) {
469
+ resourceType = segments.slice(1, -1).join(":");
470
+ resourceId = segments[segments.length - 1];
471
+ }
472
+ return new Urn(domain, resourceType, resourceId);
428
473
  }
429
474
  /**
430
- * 判断是否匹配指定的 namespace、resource 和 identifier
475
+ * 判断是否匹配指定的 domain、resourceType 和 resourceId
431
476
  *
432
477
  * 仅比较传入的参数,未传入的参数不参与比较。
433
478
  */
434
- is(namespace, resource, identifier) {
435
- if (this.namespace !== namespace) return false;
436
- if (resource !== void 0 && this.resource !== resource) return false;
437
- if (identifier !== void 0 && this.identifier !== identifier) return false;
479
+ is(domain, resourceType, resourceId) {
480
+ if (this.domain !== domain) return false;
481
+ if (resourceType !== void 0 && this.resourceType !== resourceType) return false;
482
+ if (resourceId !== void 0 && this.resourceId !== resourceId) return false;
483
+ return true;
484
+ }
485
+ /**
486
+ * 判断当前 URN 是否包含另一个 URN
487
+ *
488
+ * 当前 URN 含通配符(`*` 或 `**`)时,作为集合模式判断:
489
+ * - `*` 匹配恰好一个段
490
+ * - `**` 匹配零个或多个尾部段(仅末尾有效)
491
+ *
492
+ * 当前 URN 为具体 URN(无通配符)时,仅包含自身(严格相等)。
493
+ */
494
+ contains(other) {
495
+ const thisSegs = this.toSegments();
496
+ const otherSegs = other.toSegments();
497
+ if (thisSegs.length > 0 && thisSegs[thisSegs.length - 1] === "**") {
498
+ const fixedSegs = thisSegs.slice(0, -1);
499
+ if (otherSegs.length < fixedSegs.length) return false;
500
+ for (let i = 0; i < fixedSegs.length; i++) if (fixedSegs[i] !== "*" && fixedSegs[i] !== otherSegs[i]) return false;
501
+ return true;
502
+ }
503
+ if (thisSegs.length !== otherSegs.length) return false;
504
+ for (let i = 0; i < thisSegs.length; i++) if (thisSegs[i] !== "*" && thisSegs[i] !== otherSegs[i]) return false;
438
505
  return true;
439
506
  }
440
507
  };
441
508
  //#endregion
442
509
  //#region src/modules/core/decorators/class-validator/is-urn.ts
443
510
  const IS_URN = "isUrn";
444
- const IS_NAMESPACE_URN = "isNamespaceUrn";
445
- const IS_RESOURCE_URN = "isResourceUrn";
446
- const IS_IDENTIFIER_URN = "isIdentifierUrn";
511
+ const IS_DOMAIN_URN = "isDomainUrn";
512
+ const IS_RESOURCE_TYPE_URN = "isResourceTypeUrn";
513
+ const IS_RESOURCE_ID_URN = "isResourceIdUrn";
447
514
  /**
448
515
  * 验证字符串是否为合法的 URN(任意层级)。
449
516
  *
@@ -473,27 +540,27 @@ function IsUrn(validationOptions) {
473
540
  }
474
541
  },
475
542
  defaultMessage() {
476
- return "$property must be a valid URN (urn:buka:<namespace>[:<resource>[:<identifier>]])";
543
+ return "$property must be a valid URN (urn:buka:<domain>[:<resource-type>[:<resource-id>]])";
477
544
  }
478
545
  }
479
546
  });
480
547
  };
481
548
  }
482
549
  /**
483
- * 验证字符串是否为 namespace 级 URN(仅含 namespace,无 resource 和 identifier)。
550
+ * 验证字符串是否为概念域级 URN(仅含 domain,无 resourceType 和 resourceId)。
484
551
  *
485
552
  * @example
486
553
  * ```typescript
487
554
  * class TokenPayloadDTO {
488
- * @IsNamespaceUrn()
555
+ * @IsDomainUrn()
489
556
  * aud: string
490
557
  * }
491
558
  * ```
492
559
  */
493
- function IsNamespaceUrn(validationOptions) {
560
+ function IsDomainUrn(validationOptions) {
494
561
  return function(object, propertyName) {
495
562
  registerDecorator({
496
- name: IS_NAMESPACE_URN,
563
+ name: IS_DOMAIN_URN,
497
564
  target: object.constructor,
498
565
  propertyName,
499
566
  options: validationOptions,
@@ -501,33 +568,33 @@ function IsNamespaceUrn(validationOptions) {
501
568
  validate(value) {
502
569
  if (typeof value !== "string") return false;
503
570
  try {
504
- return Urn.parse(value).isNamespaceUrn();
571
+ return Urn.parse(value).isDomainUrn();
505
572
  } catch {
506
573
  return false;
507
574
  }
508
575
  },
509
576
  defaultMessage() {
510
- return "$property must be a namespace-level URN (urn:buka:<namespace>)";
577
+ return "$property must be a domain-level URN (urn:buka:<domain>)";
511
578
  }
512
579
  }
513
580
  });
514
581
  };
515
582
  }
516
583
  /**
517
- * 验证字符串是否为资源类型级 URN(含 namespace 和 resource,无 identifier)。
584
+ * 验证字符串是否为资源类型级 URN(含 domain 和 resourceType,无 resourceId)。
518
585
  *
519
586
  * @example
520
587
  * ```typescript
521
588
  * class ResourceDTO {
522
- * @IsResourceUrn()
589
+ * @IsResourceTypeUrn()
523
590
  * resourceType: string
524
591
  * }
525
592
  * ```
526
593
  */
527
- function IsResourceUrn(validationOptions) {
594
+ function IsResourceTypeUrn(validationOptions) {
528
595
  return function(object, propertyName) {
529
596
  registerDecorator({
530
- name: IS_RESOURCE_URN,
597
+ name: IS_RESOURCE_TYPE_URN,
531
598
  target: object.constructor,
532
599
  propertyName,
533
600
  options: validationOptions,
@@ -535,33 +602,33 @@ function IsResourceUrn(validationOptions) {
535
602
  validate(value) {
536
603
  if (typeof value !== "string") return false;
537
604
  try {
538
- return Urn.parse(value).isResourceUrn();
605
+ return Urn.parse(value).isResourceTypeUrn();
539
606
  } catch {
540
607
  return false;
541
608
  }
542
609
  },
543
610
  defaultMessage() {
544
- return "$property must be a resource-level URN (urn:buka:<namespace>:<resource>)";
611
+ return "$property must be a resource-type-level URN (urn:buka:<domain>:<resource-type>)";
545
612
  }
546
613
  }
547
614
  });
548
615
  };
549
616
  }
550
617
  /**
551
- * 验证字符串是否为实例级 URN(含完整三段:namespace、resource 和 identifier)。
618
+ * 验证字符串是否为实例级 URN(含完整三段:domain、resourceType 和 resourceId)。
552
619
  *
553
620
  * @example
554
621
  * ```typescript
555
622
  * class TokenPayloadDTO {
556
- * @IsIdentifierUrn()
623
+ * @IsResourceIdUrn()
557
624
  * sub: string
558
625
  * }
559
626
  * ```
560
627
  */
561
- function IsIdentifierUrn(validationOptions) {
628
+ function IsResourceIdUrn(validationOptions) {
562
629
  return function(object, propertyName) {
563
630
  registerDecorator({
564
- name: IS_IDENTIFIER_URN,
631
+ name: IS_RESOURCE_ID_URN,
565
632
  target: object.constructor,
566
633
  propertyName,
567
634
  options: validationOptions,
@@ -569,13 +636,13 @@ function IsIdentifierUrn(validationOptions) {
569
636
  validate(value) {
570
637
  if (typeof value !== "string") return false;
571
638
  try {
572
- return Urn.parse(value).isIdentifierUrn();
639
+ return Urn.parse(value).isResourceIdUrn();
573
640
  } catch {
574
641
  return false;
575
642
  }
576
643
  },
577
644
  defaultMessage() {
578
- return "$property must be an identifier-level URN (urn:buka:<namespace>:<resource>:<identifier>)";
645
+ return "$property must be a resource-id-level URN (urn:buka:<domain>:<resource-type>:<resource-id>)";
579
646
  }
580
647
  }
581
648
  });
@@ -9683,7 +9750,7 @@ let LoggerModule = _LoggerModule = class LoggerModule {
9683
9750
  ...pretty ? { transport: { target: "pino-pretty" } } : {},
9684
9751
  level,
9685
9752
  genReqId: (req) => req.headers["x-request-id"] || crypto.randomUUID(),
9686
- autoLogging: { ignore: (req) => req.url?.startsWith("/api/v1/health") ?? false },
9753
+ autoLogging: options.autoLogging,
9687
9754
  customAttributeKeys: {
9688
9755
  reqId: "reqId",
9689
9756
  responseTime: "responseTime"
@@ -9909,6 +9976,6 @@ ObjectStorageModule = __decorate([Global(), Module({
9909
9976
  exports: [ObjectStorageService]
9910
9977
  })], ObjectStorageModule);
9911
9978
  //#endregion
9912
- export { AuthException, BUKA_MODULE_OPTIONS_TOKEN, Base32, BlindIndex, BlindIndexModule, BlindIndexService, BlindIndexV1Hasher, BukaConfigurableModuleClass, BukaExceptions, BukaModule, BukaPageQueryValidationPipe, BukaValidationPipe, BusinessException, Cardinality, Column, Composite, ConfigurableModuleClass, ConflictException, CursorPagination, DatabaseConfig, DegradeException, Dictionary, DiscreteEntity, EagerType, EncryptedPayload, EntityRef, Enum, EnvelopeEncryptionModule, EnvelopeEncryptionService, ErrorCategory, ErrorCode, ErrorCodeController, ErrorCodeExceptionFilter, ErrorCodeDefinitionDto as ErrorCodeItemDto, ErrorCodeMetadataDto, ErrorCodePartsDto, ErrorCodeRegistry, ErrorResponseSchema, ExceptionDetailSchema, ExceptionModule, FeatureException, FilterQuery, FilterQueryOperators, FilterQueryOperatorsMetadataKey, FilterQueryTransformPipe, HAS_ANY_KEY, HasAnyKey, HttpException, IS_CROCKFORD_BASE32, IS_IDENTIFIER_URN, IS_NAMESPACE_URN, IS_RESOURCE_URN, IS_SCALAR_DICTIONARY, IS_URN, InjectLogger, IsBrowserRequest, IsCrockfordBase32, IsIdentifierUrn, IsNamespaceUrn, IsResourceUrn, IsScalar, IsScalarDictionary, IsUrn, KeyEnvelope, LinearEntity, List, ListErrorCodesResponseDto, ListResponseBodyType, Logger, LoggerConfig, LoggerErrorInterceptor, LoggerModule, MATCH_JSON_SCHEMA, MODULE_OPTIONS_TOKEN, MatchJsonSchema, Model, ModelRegister, ModuleExceptions, NextCursorPageSchema, ObjectStorageModule, ObjectStorageModuleConfig, ObjectStorageService, OffsetPageSchema, OffsetPagination, OmitType, OpenBaoAppRoleAuthConfig, OpenBaoHttpClient, OpenBaoKubernetesAuthConfig, OpenBaoModule, OpenBaoModuleConfig, OpenBaoTokenAuthConfig, OpenBaoTokenManager, OpenBaoUserpassAuthConfig, OptionalPageQuery, OrderQueryType, PageQuery, ParseUUIDv7Pipe, PartialType, PendingException, PickType, PreviousCursorPageSchema, PrimaryKeyType, PrimaryKeyTypeClassMetadataPropertyKey, Property, RateLimitException, ResponseBodyType, SaltedHash, SaltedHashModule, SaltedHashService, SaltedHashV1Hasher, Slice, SwaggerPatcher, SystemException, ThirdPartyException, TimestampedEntity, Urn, VALIDATE_NESTED_DICTIONARY, ValidateNestedDictionary, ValidationException, getExceptionModuleId, getFilterQueryOperators, isScalarClass, serializeModel, setOpenBaoToken, stableStringify };
9979
+ export { AuthException, BUKA_MODULE_OPTIONS_TOKEN, Base32, BlindIndex, BlindIndexModule, BlindIndexService, BlindIndexV1Hasher, BukaConfigurableModuleClass, BukaExceptions, BukaModule, BukaPageQueryValidationPipe, BukaValidationPipe, BusinessException, Cardinality, Column, Composite, ConfigurableModuleClass, ConflictException, CursorPagination, DatabaseConfig, DegradeException, Dictionary, DiscreteEntity, EagerType, EncryptedPayload, EntityRef, Enum, EnvelopeEncryptionModule, EnvelopeEncryptionService, ErrorCategory, ErrorCode, ErrorCodeController, ErrorCodeExceptionFilter, ErrorCodeDefinitionDto as ErrorCodeItemDto, ErrorCodeMetadataDto, ErrorCodePartsDto, ErrorCodeRegistry, ErrorResponseSchema, ExceptionDetailSchema, ExceptionModule, FeatureException, FilterQuery, FilterQueryOperators, FilterQueryOperatorsMetadataKey, FilterQueryTransformPipe, HAS_ANY_KEY, HasAnyKey, HttpException, IS_CROCKFORD_BASE32, IS_DOMAIN_URN, IS_RESOURCE_ID_URN, IS_RESOURCE_TYPE_URN, IS_SCALAR_DICTIONARY, IS_URN, InjectLogger, IsBrowserRequest, IsCrockfordBase32, IsDomainUrn, IsResourceIdUrn, IsResourceTypeUrn, IsScalar, IsScalarDictionary, IsUrn, KeyEnvelope, LinearEntity, List, ListErrorCodesResponseDto, ListResponseBodyType, Logger, LoggerConfig, LoggerErrorInterceptor, LoggerModule, MATCH_JSON_SCHEMA, MODULE_OPTIONS_TOKEN, MatchJsonSchema, Model, ModelRegister, ModuleExceptions, NextCursorPageSchema, ObjectStorageModule, ObjectStorageModuleConfig, ObjectStorageService, OffsetPageSchema, OffsetPagination, OmitType, OpenBaoAppRoleAuthConfig, OpenBaoHttpClient, OpenBaoKubernetesAuthConfig, OpenBaoModule, OpenBaoModuleConfig, OpenBaoTokenAuthConfig, OpenBaoTokenManager, OpenBaoUserpassAuthConfig, OptionalPageQuery, OrderQueryType, PageQuery, ParseUUIDv7Pipe, PartialType, PendingException, PickType, PreviousCursorPageSchema, PrimaryKeyType, PrimaryKeyTypeClassMetadataPropertyKey, Property, RateLimitException, ResponseBodyType, SaltedHash, SaltedHashModule, SaltedHashService, SaltedHashV1Hasher, Slice, SwaggerPatcher, SystemException, ThirdPartyException, TimestampedEntity, Urn, VALIDATE_NESTED_DICTIONARY, ValidateNestedDictionary, ValidationException, getExceptionModuleId, getFilterQueryOperators, isScalarClass, serializeModel, setOpenBaoToken, stableStringify };
9913
9980
 
9914
9981
  //# sourceMappingURL=index.mjs.map