@h-ai/core 0.1.0-alpha.69 → 0.1.0-alpha.71

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.
@@ -19718,136 +19718,6 @@ var CoreConfigSchema = external_exports.strictObject({
19718
19718
  defaultLocale: external_exports.string().default("zh-CN")
19719
19719
  });
19720
19720
 
19721
- // src/functions/core-function-error.ts
19722
- function buildHaiErrorsDef(module, errorInfo, system = "hai") {
19723
- const result = {};
19724
- for (const key in errorInfo) {
19725
- const [codeNum, httpStatusStr] = errorInfo[key].split(":");
19726
- result[key] = {
19727
- code: `${system}:${module}:${codeNum}`,
19728
- httpStatus: Number(httpStatusStr),
19729
- system,
19730
- module
19731
- };
19732
- }
19733
- return result;
19734
- }
19735
- function buildHaiErrorInst(def, message, cause, suggestion) {
19736
- const inst = { ...def, message };
19737
- if (cause !== void 0)
19738
- inst.cause = cause;
19739
- if (suggestion !== void 0)
19740
- inst.suggestion = suggestion;
19741
- return inst;
19742
- }
19743
- var error62 = {
19744
- buildHaiErrorsDef,
19745
- buildHaiErrorInst
19746
- };
19747
-
19748
- // src/core-types.ts
19749
- var UnknownErrorDef = {
19750
- code: "_:_:599",
19751
- httpStatus: 500,
19752
- system: "_",
19753
- module: "_"
19754
- };
19755
- function ok(data) {
19756
- return { success: true, data };
19757
- }
19758
- function err(errorOrDef, message, cause, suggestion) {
19759
- if (errorOrDef instanceof Error) {
19760
- return {
19761
- success: false,
19762
- error: error62.buildHaiErrorInst(
19763
- UnknownErrorDef,
19764
- message || errorOrDef.message,
19765
- cause ?? errorOrDef,
19766
- suggestion
19767
- )
19768
- };
19769
- }
19770
- const nonNativeError = errorOrDef;
19771
- if ("message" in nonNativeError) {
19772
- return {
19773
- success: false,
19774
- error: nonNativeError
19775
- };
19776
- }
19777
- return {
19778
- success: false,
19779
- error: error62.buildHaiErrorInst(nonNativeError, message || "", cause, suggestion)
19780
- };
19781
- }
19782
- var CommonErrorInfo = {
19783
- // 001-099: 初始化和配置
19784
- NOT_INITIALIZED: "001:500",
19785
- INIT_FAILED: "002:500",
19786
- INIT_IN_PROGRESS: "004:500",
19787
- // 100-199: 认证 & 授权
19788
- UNAUTHORIZED: "100:401",
19789
- FORBIDDEN: "101:403",
19790
- TOKEN_EXPIRED: "102:401",
19791
- TOKEN_INVALID: "103:401",
19792
- // 200-299: 校验 & 参数
19793
- VALIDATION_ERROR: "200:400",
19794
- INVALID_REQUEST: "201:400",
19795
- PARAMETER_MISSING: "202:400",
19796
- // 300-399: 资源操作
19797
- NOT_FOUND: "300:404",
19798
- ALREADY_EXISTS: "301:409",
19799
- CONFLICT: "302:409",
19800
- // 400-499: 外部依赖
19801
- API_ERROR: "400:502",
19802
- NETWORK_ERROR: "401:502",
19803
- TIMEOUT: "402:504",
19804
- SERVICE_UNAVAILABLE: "403:503",
19805
- // 500-599: 内部错误
19806
- INTERNAL_ERROR: "500:500",
19807
- DATABASE_ERROR: "501:500",
19808
- UNKNOWN_ERROR: "599:500"
19809
- };
19810
- var HaiCommonError = error62.buildHaiErrorsDef("common", CommonErrorInfo);
19811
- var ConfigErrorInfo = {
19812
- CONFIG_FILE_NOT_FOUND: "010:500",
19813
- CONFIG_PARSE_ERROR: "011:500",
19814
- CONFIG_VALIDATION_ERROR: "012:500",
19815
- CONFIG_ENV_VAR_MISSING: "013:500",
19816
- CONFIG_NOT_LOADED: "014:500"
19817
- };
19818
- var HaiConfigError = error62.buildHaiErrorsDef("core", ConfigErrorInfo);
19819
-
19820
- // src/functions/core-function-context.ts
19821
- var storage;
19822
- var synchronousContext = Object.freeze({});
19823
- function installRequestContext(value) {
19824
- storage = value;
19825
- }
19826
- var requestContext = {
19827
- get() {
19828
- return storage?.getStore() ?? synchronousContext;
19829
- },
19830
- run(value, operation) {
19831
- const previousValue = requestContext.get();
19832
- const merged = Object.freeze({
19833
- requestId: Object.hasOwn(value, "requestId") ? value.requestId : previousValue.requestId,
19834
- scopeId: Object.hasOwn(value, "scopeId") ? value.scopeId : previousValue.scopeId,
19835
- userId: Object.hasOwn(value, "userId") ? value.userId : previousValue.userId,
19836
- jobId: Object.hasOwn(value, "jobId") ? value.jobId : previousValue.jobId,
19837
- suppressLogObservers: Object.hasOwn(value, "suppressLogObservers") ? value.suppressLogObservers : previousValue.suppressLogObservers
19838
- });
19839
- if (storage)
19840
- return storage.run(merged, operation);
19841
- const previous = synchronousContext;
19842
- synchronousContext = merged;
19843
- try {
19844
- return operation();
19845
- } finally {
19846
- synchronousContext = previous;
19847
- }
19848
- }
19849
- };
19850
-
19851
19721
  // messages/en-US.json
19852
19722
  var en_US_default = {
19853
19723
  $schema: "https://inlang.com/schema/inlang-message-format",
@@ -19901,7 +19771,9 @@ var en_US_default = {
19901
19771
  core_configValidationFailed: "Config validation failed",
19902
19772
  core_configNotLoaded: "Config '{name}' is not loaded",
19903
19773
  core_configUnsupportedInBrowser: "Browser does not support file-based config; use core.config on the server or pass browser options through core.init({ logging })",
19904
- core_cryptoRandomUnavailable: "Cryptographic random source is unavailable"
19774
+ core_cryptoRandomUnavailable: "Cryptographic random source is unavailable",
19775
+ core_runtimeStartFailed: "Module {module} failed to start",
19776
+ core_runtimeCloseFailed: "Module {module} failed to close; retry cleanup"
19905
19777
  };
19906
19778
 
19907
19779
  // messages/ja-JP.json
@@ -19957,7 +19829,9 @@ var ja_JP_default = {
19957
19829
  core_configValidationFailed: "\u8A2D\u5B9A\u306E\u691C\u8A3C\u306B\u5931\u6557\u3057\u307E\u3057\u305F",
19958
19830
  core_configNotLoaded: "\u8A2D\u5B9A\u300C{name}\u300D\u304C\u8AAD\u307F\u8FBC\u307E\u308C\u3066\u3044\u307E\u305B\u3093",
19959
19831
  core_configUnsupportedInBrowser: "\u30D6\u30E9\u30A6\u30B6\u30FC\u306F\u30D5\u30A1\u30A4\u30EB\u30D9\u30FC\u30B9\u306E\u8A2D\u5B9A\u306B\u5BFE\u5FDC\u3057\u3066\u3044\u307E\u305B\u3093\u3002\u30B5\u30FC\u30D0\u30FC\u5074\u3067core.config\u3092\u4F7F\u7528\u3059\u308B\u304B\u3001core.init({ logging })\u3067\u30D6\u30E9\u30A6\u30B6\u30FC\u7528\u306E\u30AA\u30D7\u30B7\u30E7\u30F3\u3092\u6E21\u3057\u3066\u304F\u3060\u3055\u3044",
19960
- core_cryptoRandomUnavailable: "\u6697\u53F7\u5B66\u7684\u4E71\u6570\u306E\u751F\u6210\u5143\u3092\u5229\u7528\u3067\u304D\u307E\u305B\u3093"
19832
+ core_cryptoRandomUnavailable: "\u6697\u53F7\u5B66\u7684\u4E71\u6570\u306E\u751F\u6210\u5143\u3092\u5229\u7528\u3067\u304D\u307E\u305B\u3093",
19833
+ core_runtimeStartFailed: "\u30E2\u30B8\u30E5\u30FC\u30EB {module} \u306E\u8D77\u52D5\u306B\u5931\u6557\u3057\u307E\u3057\u305F",
19834
+ core_runtimeCloseFailed: "\u30E2\u30B8\u30E5\u30FC\u30EB {module} \u306E\u7D42\u4E86\u306B\u5931\u6557\u3057\u307E\u3057\u305F\u3002\u5F8C\u51E6\u7406\u3092\u518D\u8A66\u884C\u3057\u3066\u304F\u3060\u3055\u3044"
19961
19835
  };
19962
19836
 
19963
19837
  // messages/zh-CN.json
@@ -20013,7 +19887,9 @@ var zh_CN_default2 = {
20013
19887
  core_configValidationFailed: "\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25",
20014
19888
  core_configNotLoaded: "\u914D\u7F6E '{name}' \u672A\u52A0\u8F7D",
20015
19889
  core_configUnsupportedInBrowser: "\u6D4F\u89C8\u5668\u73AF\u5883\u4E0D\u652F\u6301\u6587\u4EF6\u914D\u7F6E\uFF0C\u8BF7\u5728\u670D\u52A1\u7AEF\u4F7F\u7528 core.config \u6216\u901A\u8FC7 core.init({ logging }) \u4F20\u5165\u6D4F\u89C8\u5668\u7AEF\u9009\u9879",
20016
- core_cryptoRandomUnavailable: "\u5F53\u524D\u8FD0\u884C\u73AF\u5883\u7F3A\u5C11\u5BC6\u7801\u5B66\u5B89\u5168\u7684\u968F\u673A\u6E90"
19890
+ core_cryptoRandomUnavailable: "\u5F53\u524D\u8FD0\u884C\u73AF\u5883\u7F3A\u5C11\u5BC6\u7801\u5B66\u5B89\u5168\u7684\u968F\u673A\u6E90",
19891
+ core_runtimeStartFailed: "\u6A21\u5757 {module} \u542F\u52A8\u5931\u8D25",
19892
+ core_runtimeCloseFailed: "\u6A21\u5757 {module} \u5173\u95ED\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u6E05\u7406"
20017
19893
  };
20018
19894
 
20019
19895
  // src/i18n/core-i18n-utils.ts
@@ -20080,129 +19956,6 @@ var i18n = {
20080
19956
  createMessageGetter,
20081
19957
  coreM
20082
19958
  };
20083
- var DEFAULT_LENGTH = 21;
20084
- var SHORT_LENGTH = 10;
20085
- var UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
20086
- var NANOID_REGEX_CACHE = /* @__PURE__ */ new Map();
20087
- function generateUUID() {
20088
- if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
20089
- return crypto.randomUUID();
20090
- }
20091
- const bytes = new Uint8Array(16);
20092
- if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
20093
- crypto.getRandomValues(bytes);
20094
- } else {
20095
- throw new Error(i18n.coreM("core_cryptoRandomUnavailable"));
20096
- }
20097
- bytes[6] = bytes[6] & 15 | 64;
20098
- bytes[8] = bytes[8] & 63 | 128;
20099
- const hex3 = Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
20100
- return `${hex3.slice(0, 8)}-${hex3.slice(8, 12)}-${hex3.slice(12, 16)}-${hex3.slice(16, 20)}-${hex3.slice(20)}`;
20101
- }
20102
- var id = {
20103
- /**
20104
- * 生成标准 nanoid(默认 21 字符)。
20105
- *
20106
- * @param length - ID 长度
20107
- * @returns nanoid 字符串
20108
- *
20109
- * @example
20110
- * ```ts
20111
- * const id = core.id.generate(16)
20112
- * ```
20113
- */
20114
- generate(length = DEFAULT_LENGTH) {
20115
- return nanoid$1(length);
20116
- },
20117
- /**
20118
- * 生成短 ID(10 字符)。
20119
- *
20120
- * @example
20121
- * ```ts
20122
- * const shortId = core.id.short()
20123
- * ```
20124
- */
20125
- short() {
20126
- return nanoid$1(SHORT_LENGTH);
20127
- },
20128
- /**
20129
- * 生成带前缀的 ID。
20130
- *
20131
- * @param prefix - 前缀
20132
- * @param length - ID 长度
20133
- *
20134
- * @example
20135
- * ```ts
20136
- * const userId = core.id.withPrefix('user_')
20137
- * ```
20138
- */
20139
- withPrefix(prefix, length = DEFAULT_LENGTH) {
20140
- return `${prefix}${nanoid$1(length)}`;
20141
- },
20142
- /**
20143
- * 生成 Trace ID。
20144
- *
20145
- * @example
20146
- * ```ts
20147
- * const traceId = core.id.trace()
20148
- * ```
20149
- */
20150
- trace() {
20151
- return `trace-${nanoid$1()}`;
20152
- },
20153
- /**
20154
- * 生成 Request ID。
20155
- *
20156
- * @example
20157
- * ```ts
20158
- * const requestId = core.id.request()
20159
- * ```
20160
- */
20161
- request() {
20162
- return `req-${nanoid$1()}`;
20163
- },
20164
- /**
20165
- * 生成 UUID v4。
20166
- *
20167
- * @example
20168
- * ```ts
20169
- * const uuid = core.id.uuid()
20170
- * ```
20171
- */
20172
- uuid() {
20173
- return generateUUID();
20174
- },
20175
- /**
20176
- * 验证是否为有效的 UUID v4。
20177
- *
20178
- * @example
20179
- * ```ts
20180
- * core.id.isValidUUID('f47ac10b-58cc-4372-a567-0e02b2c3d479')
20181
- * ```
20182
- */
20183
- isValidUUID(uuid3) {
20184
- return UUID_REGEX.test(uuid3);
20185
- },
20186
- /**
20187
- * 验证是否为有效的 nanoid。
20188
- *
20189
- * @param str - 待验证字符串
20190
- * @param length - 期望长度
20191
- *
20192
- * @example
20193
- * ```ts
20194
- * core.id.isValidNanoId('abc', 3)
20195
- * ```
20196
- */
20197
- isValidNanoId(str, length = DEFAULT_LENGTH) {
20198
- let regex = NANOID_REGEX_CACHE.get(length);
20199
- if (!regex) {
20200
- regex = new RegExp(`^[A-Za-z0-9_-]{${length}}$`);
20201
- NANOID_REGEX_CACHE.set(length, regex);
20202
- }
20203
- return regex.test(str);
20204
- }
20205
- };
20206
19959
 
20207
19960
  // src/utils/core-util-type.ts
20208
19961
  function isDefined(value) {
@@ -20247,7 +20000,14 @@ var typeUtils = {
20247
20000
  };
20248
20001
 
20249
20002
  // src/utils/core-util-sanitize.ts
20250
- var DEFAULT_SENSITIVE_KEY_REGEX = /(?:^|_)(?:pass|passcode|password|secret|authorization|cookie|otp|session|token)$|(?:^|_)otp_code$|(?:^|_)private_key$|(?:^|_)access_key(?:_id|_secret)?$|(?:^|_)secret_access_key$|(?:^|_)api(?:_[a-z0-9]+)*_key$|^apikey$/i;
20003
+ var CREDENTIAL_TEXT = /\b(?:Bearer|Basic)\s+[\w.~+/-]+=*|\b(?:[\w-]*[_-])?(?:password|passwd|passcode|secret|token|session(?:[_-]?id)?|authorization|cookie|csrf|credential|api[_-]?key|private[_-]?key|(?:access|refresh|id|csrf)token|(?:otp|totp|verification|verify|captcha|sms|email|auth|one[_-]?time|two[_-]?factor)[_-]?code)(?:\\?["'])?\s*[:=]\s*(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\\"(?:[^\\]|\\\\\\\\|\\\\\\"|\\\\[^"\\])*\\"|[^\s,;&}\]]+)/gi;
20004
+ function sanitizeText(text, secretValues = []) {
20005
+ let result = text;
20006
+ for (const value of [...new Set(secretValues)].filter(Boolean).sort((a, b) => b.length - a.length))
20007
+ result = result.replaceAll(value, "[REDACTED]");
20008
+ return result.replace(/\b[a-z][a-z\d+.-]*:\/\/[^\s<>"']+/gi, (url2) => sanitizeUrl(url2)).replace(CREDENTIAL_TEXT, (match) => match.includes("[REDACTED") ? match : "[REDACTED]");
20009
+ }
20010
+ var DEFAULT_SENSITIVE_KEY_REGEX = /(?:^|_)(?:pass|passcode|password|secret|authorization|cookie|otp|session|token)$|(?:^|_)(?:otp|totp|verification|verify|captcha|sms|email|auth|one_time|two_factor)_code$|(?:^|_)private_key$|(?:^|_)access_key(?:_id|_secret)?$|(?:^|_)secret_access_key$|(?:^|_)api(?:_[a-z0-9]+)*_key$|^apikey$/i;
20251
20011
  var DEFAULT_SENSITIVE_REPLACEMENT = "[REDACTED]";
20252
20012
  var URL_LIKE_KEY_REGEX = /(?:^|_)(?:url|uri|endpoint)(?:_|$)/;
20253
20013
  var SENSITIVE_KEY_CACHE_LIMIT = 512;
@@ -20345,7 +20105,8 @@ function createSanitizeSensitiveContext(options = {}) {
20345
20105
  }
20346
20106
  function sanitizeSensitiveValueWithContext(value, key, context, cache, errorPath, errorDepth = 0) {
20347
20107
  const isPlainObjectValue = isPlainRecord(value);
20348
- const isErrorDiagnostic = errorPath !== void 0 || value instanceof Error;
20108
+ const errorValue = value instanceof Error ? value : typeof DOMException !== "undefined" && value instanceof DOMException ? value : void 0;
20109
+ const isErrorDiagnostic = errorPath !== void 0 || errorValue !== void 0;
20349
20110
  if (key !== null) {
20350
20111
  const normalizedKey = normalizeKeyForMatching(key);
20351
20112
  if (typeof value === "string" && isUrlLikeNormalizedKey(normalizedKey)) {
@@ -20361,7 +20122,7 @@ function sanitizeSensitiveValueWithContext(value, key, context, cache, errorPath
20361
20122
  if (typeof value === "function" || typeof value === "symbol")
20362
20123
  return void 0;
20363
20124
  if (value === null || typeof value !== "object")
20364
- return value;
20125
+ return typeof value === "string" ? sanitizeText(value) : value;
20365
20126
  const activePath = errorPath ?? /* @__PURE__ */ new WeakSet();
20366
20127
  if (activePath.has(value))
20367
20128
  return "[Circular]";
@@ -20373,14 +20134,15 @@ function sanitizeSensitiveValueWithContext(value, key, context, cache, errorPath
20373
20134
  return value.map((item) => sanitizeSensitiveValueWithContext(item, null, context, cache, activePath, errorDepth + 1));
20374
20135
  }
20375
20136
  const fields = { ...value };
20376
- if (value instanceof Error) {
20377
- fields.name = value.name;
20378
- fields.message = value.message;
20379
- fields.stack = value.stack;
20380
- if (Object.hasOwn(value, "cause"))
20381
- fields.cause = value.cause;
20382
- if (value instanceof AggregateError)
20383
- fields.errors = value.errors;
20137
+ if (errorValue) {
20138
+ fields.name = errorValue.name;
20139
+ fields.message = errorValue.message;
20140
+ if ("stack" in errorValue)
20141
+ fields.stack = errorValue.stack;
20142
+ if (Object.hasOwn(errorValue, "cause") && "cause" in errorValue)
20143
+ fields.cause = errorValue.cause;
20144
+ if (errorValue instanceof AggregateError)
20145
+ fields.errors = errorValue.errors;
20384
20146
  }
20385
20147
  const sanitized = {};
20386
20148
  for (const [childKey, childValue] of Object.entries(fields)) {
@@ -20430,13 +20192,293 @@ var sanitize = {
20430
20192
  defaultSensitiveReplacement: DEFAULT_SENSITIVE_REPLACEMENT,
20431
20193
  isSensitiveKey,
20432
20194
  sanitizeUrl,
20195
+ sanitizeText,
20433
20196
  sanitizeSensitiveValue,
20434
20197
  sanitizeSensitiveFields
20435
20198
  };
20436
20199
 
20437
- // src/functions/core-function-log-observer.ts
20438
- var observers = /* @__PURE__ */ new Set();
20439
- var emitting = false;
20200
+ // src/functions/core-function-context.ts
20201
+ var storage;
20202
+ var synchronousContext = Object.freeze({});
20203
+ function installRequestContext(value) {
20204
+ storage = value;
20205
+ }
20206
+ var requestContext = {
20207
+ get() {
20208
+ return storage?.getStore() ?? synchronousContext;
20209
+ },
20210
+ run(value, operation) {
20211
+ const previousValue = requestContext.get();
20212
+ const merged = Object.freeze({
20213
+ requestId: Object.hasOwn(value, "requestId") ? value.requestId : previousValue.requestId,
20214
+ traceId: value.traceId ?? (Object.hasOwn(value, "requestId") ? value.requestId : previousValue.traceId),
20215
+ scopeId: Object.hasOwn(value, "scopeId") ? value.scopeId : previousValue.scopeId,
20216
+ userId: Object.hasOwn(value, "userId") ? value.userId : previousValue.userId,
20217
+ jobId: Object.hasOwn(value, "jobId") ? value.jobId : previousValue.jobId,
20218
+ suppressLogObservers: Object.hasOwn(value, "suppressLogObservers") ? value.suppressLogObservers : previousValue.suppressLogObservers
20219
+ });
20220
+ if (storage)
20221
+ return storage.run(merged, operation);
20222
+ const previous = synchronousContext;
20223
+ synchronousContext = merged;
20224
+ try {
20225
+ return operation();
20226
+ } finally {
20227
+ synchronousContext = previous;
20228
+ }
20229
+ }
20230
+ };
20231
+ var DEFAULT_LENGTH = 21;
20232
+ var SHORT_LENGTH = 10;
20233
+ var UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
20234
+ var NANOID_REGEX_CACHE = /* @__PURE__ */ new Map();
20235
+ function generateUUID() {
20236
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
20237
+ return crypto.randomUUID();
20238
+ }
20239
+ const bytes = new Uint8Array(16);
20240
+ if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
20241
+ crypto.getRandomValues(bytes);
20242
+ } else {
20243
+ throw new Error(i18n.coreM("core_cryptoRandomUnavailable"));
20244
+ }
20245
+ bytes[6] = bytes[6] & 15 | 64;
20246
+ bytes[8] = bytes[8] & 63 | 128;
20247
+ const hex3 = Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
20248
+ return `${hex3.slice(0, 8)}-${hex3.slice(8, 12)}-${hex3.slice(12, 16)}-${hex3.slice(16, 20)}-${hex3.slice(20)}`;
20249
+ }
20250
+ var id = {
20251
+ /**
20252
+ * 生成标准 nanoid(默认 21 字符)。
20253
+ *
20254
+ * @param length - ID 长度
20255
+ * @returns nanoid 字符串
20256
+ *
20257
+ * @example
20258
+ * ```ts
20259
+ * const id = core.id.generate(16)
20260
+ * ```
20261
+ */
20262
+ generate(length = DEFAULT_LENGTH) {
20263
+ return nanoid$1(length);
20264
+ },
20265
+ /**
20266
+ * 生成短 ID(10 字符)。
20267
+ *
20268
+ * @example
20269
+ * ```ts
20270
+ * const shortId = core.id.short()
20271
+ * ```
20272
+ */
20273
+ short() {
20274
+ return nanoid$1(SHORT_LENGTH);
20275
+ },
20276
+ /**
20277
+ * 生成带前缀的 ID。
20278
+ *
20279
+ * @param prefix - 前缀
20280
+ * @param length - ID 长度
20281
+ *
20282
+ * @example
20283
+ * ```ts
20284
+ * const userId = core.id.withPrefix('user_')
20285
+ * ```
20286
+ */
20287
+ withPrefix(prefix, length = DEFAULT_LENGTH) {
20288
+ return `${prefix}${nanoid$1(length)}`;
20289
+ },
20290
+ /**
20291
+ * 生成 Trace ID。
20292
+ *
20293
+ * @example
20294
+ * ```ts
20295
+ * const traceId = core.id.trace()
20296
+ * ```
20297
+ */
20298
+ trace() {
20299
+ return `trace-${nanoid$1()}`;
20300
+ },
20301
+ /**
20302
+ * 生成 Request ID。
20303
+ *
20304
+ * @example
20305
+ * ```ts
20306
+ * const requestId = core.id.request()
20307
+ * ```
20308
+ */
20309
+ request() {
20310
+ return `req-${nanoid$1()}`;
20311
+ },
20312
+ /**
20313
+ * 生成 UUID v4。
20314
+ *
20315
+ * @example
20316
+ * ```ts
20317
+ * const uuid = core.id.uuid()
20318
+ * ```
20319
+ */
20320
+ uuid() {
20321
+ return generateUUID();
20322
+ },
20323
+ /**
20324
+ * 验证是否为有效的 UUID v4。
20325
+ *
20326
+ * @example
20327
+ * ```ts
20328
+ * core.id.isValidUUID('f47ac10b-58cc-4372-a567-0e02b2c3d479')
20329
+ * ```
20330
+ */
20331
+ isValidUUID(uuid3) {
20332
+ return UUID_REGEX.test(uuid3);
20333
+ },
20334
+ /**
20335
+ * 验证是否为有效的 nanoid。
20336
+ *
20337
+ * @param str - 待验证字符串
20338
+ * @param length - 期望长度
20339
+ *
20340
+ * @example
20341
+ * ```ts
20342
+ * core.id.isValidNanoId('abc', 3)
20343
+ * ```
20344
+ */
20345
+ isValidNanoId(str, length = DEFAULT_LENGTH) {
20346
+ let regex = NANOID_REGEX_CACHE.get(length);
20347
+ if (!regex) {
20348
+ regex = new RegExp(`^[A-Za-z0-9_-]{${length}}$`);
20349
+ NANOID_REGEX_CACHE.set(length, regex);
20350
+ }
20351
+ return regex.test(str);
20352
+ }
20353
+ };
20354
+
20355
+ // src/functions/core-function-error.ts
20356
+ function formatMessage(error63) {
20357
+ return error63.traceId && /^[\w.:-]{1,128}$/.test(error63.traceId) && !error63.message.endsWith(`(traceId: ${error63.traceId})`) ? `${error63.message} (traceId: ${error63.traceId})` : error63.message;
20358
+ }
20359
+ function toPublic(error63, traceId, locale) {
20360
+ const context = requestContext.get();
20361
+ const candidate = traceId ?? context.traceId ?? context.requestId ?? error63.traceId;
20362
+ const safeTraceId = candidate && /^[\w.:-]{1,128}$/.test(candidate) ? candidate : id.uuid();
20363
+ const result = {
20364
+ code: error63.code,
20365
+ message: (error63.httpStatus ?? 400) >= 500 ? i18n.coreM("core_errorInternal", { locale }) : sanitize.sanitizeText(error63.message),
20366
+ traceId: safeTraceId,
20367
+ ...error63.httpStatus !== void 0 ? { httpStatus: error63.httpStatus } : {},
20368
+ ...error63.system ? { system: error63.system } : {},
20369
+ ...error63.module ? { module: error63.module } : {}
20370
+ };
20371
+ if (error63.publicExt)
20372
+ result.ext = sanitize.sanitizeSensitiveFields(error63.publicExt);
20373
+ if ((error63.httpStatus === 400 || error63.httpStatus === 422) && Array.isArray(error63.cause)) {
20374
+ result.cause = error63.cause.flatMap((item) => item && typeof item === "object" && "field" in item && typeof item.field === "string" && "message" in item && typeof item.message === "string" ? [{ field: item.field, message: sanitize.sanitizeText(item.message) }] : []);
20375
+ }
20376
+ result.message = formatMessage(result);
20377
+ return result;
20378
+ }
20379
+ function buildHaiErrorsDef(module, errorInfo, system = "hai") {
20380
+ const result = {};
20381
+ for (const key in errorInfo) {
20382
+ const [codeNum, httpStatusStr] = errorInfo[key].split(":");
20383
+ result[key] = {
20384
+ code: `${system}:${module}:${codeNum}`,
20385
+ httpStatus: Number(httpStatusStr),
20386
+ system,
20387
+ module
20388
+ };
20389
+ }
20390
+ return result;
20391
+ }
20392
+ function buildHaiErrorInst(def, message, cause, suggestion) {
20393
+ const inst = { ...def, message };
20394
+ if (cause !== void 0)
20395
+ inst.cause = cause;
20396
+ if (suggestion !== void 0)
20397
+ inst.suggestion = suggestion;
20398
+ return inst;
20399
+ }
20400
+ var error62 = {
20401
+ buildHaiErrorsDef,
20402
+ buildHaiErrorInst,
20403
+ formatMessage,
20404
+ toPublic
20405
+ };
20406
+
20407
+ // src/core-types.ts
20408
+ var UnknownErrorDef = {
20409
+ code: "_:_:599",
20410
+ httpStatus: 500,
20411
+ system: "_",
20412
+ module: "_"
20413
+ };
20414
+ function ok(data) {
20415
+ return { success: true, data };
20416
+ }
20417
+ function err(errorOrDef, message, cause, suggestion) {
20418
+ if (errorOrDef instanceof Error) {
20419
+ return {
20420
+ success: false,
20421
+ error: error62.buildHaiErrorInst(
20422
+ UnknownErrorDef,
20423
+ message || errorOrDef.message,
20424
+ cause ?? errorOrDef,
20425
+ suggestion
20426
+ )
20427
+ };
20428
+ }
20429
+ const nonNativeError = errorOrDef;
20430
+ if ("message" in nonNativeError) {
20431
+ return {
20432
+ success: false,
20433
+ error: nonNativeError
20434
+ };
20435
+ }
20436
+ return {
20437
+ success: false,
20438
+ error: error62.buildHaiErrorInst(nonNativeError, message || "", cause, suggestion)
20439
+ };
20440
+ }
20441
+ var CommonErrorInfo = {
20442
+ // 001-099: 初始化和配置
20443
+ NOT_INITIALIZED: "001:500",
20444
+ INIT_FAILED: "002:500",
20445
+ INIT_IN_PROGRESS: "004:500",
20446
+ // 100-199: 认证 & 授权
20447
+ UNAUTHORIZED: "100:401",
20448
+ FORBIDDEN: "101:403",
20449
+ TOKEN_EXPIRED: "102:401",
20450
+ TOKEN_INVALID: "103:401",
20451
+ // 200-299: 校验 & 参数
20452
+ VALIDATION_ERROR: "200:400",
20453
+ INVALID_REQUEST: "201:400",
20454
+ PARAMETER_MISSING: "202:400",
20455
+ // 300-399: 资源操作
20456
+ NOT_FOUND: "300:404",
20457
+ ALREADY_EXISTS: "301:409",
20458
+ CONFLICT: "302:409",
20459
+ // 400-499: 外部依赖
20460
+ API_ERROR: "400:502",
20461
+ NETWORK_ERROR: "401:502",
20462
+ TIMEOUT: "402:504",
20463
+ SERVICE_UNAVAILABLE: "403:503",
20464
+ // 500-599: 内部错误
20465
+ INTERNAL_ERROR: "500:500",
20466
+ DATABASE_ERROR: "501:500",
20467
+ UNKNOWN_ERROR: "599:500"
20468
+ };
20469
+ var HaiCommonError = error62.buildHaiErrorsDef("common", CommonErrorInfo);
20470
+ var ConfigErrorInfo = {
20471
+ CONFIG_FILE_NOT_FOUND: "010:500",
20472
+ CONFIG_PARSE_ERROR: "011:500",
20473
+ CONFIG_VALIDATION_ERROR: "012:500",
20474
+ CONFIG_ENV_VAR_MISSING: "013:500",
20475
+ CONFIG_NOT_LOADED: "014:500"
20476
+ };
20477
+ var HaiConfigError = error62.buildHaiErrorsDef("core", ConfigErrorInfo);
20478
+
20479
+ // src/functions/core-function-log-observer.ts
20480
+ var observers = /* @__PURE__ */ new Set();
20481
+ var emitting = false;
20440
20482
  function observeLogs(observer) {
20441
20483
  observers.add(observer);
20442
20484
  return () => {
@@ -20463,6 +20505,21 @@ function emitLogRecord(record2) {
20463
20505
  }
20464
20506
  function sanitizeLogFields(value, paths) {
20465
20507
  const result = sanitize.sanitizeSensitiveFields(value);
20508
+ const seen = /* @__PURE__ */ new WeakSet();
20509
+ const clean = (record2) => {
20510
+ if (seen.has(record2))
20511
+ return;
20512
+ seen.add(record2);
20513
+ for (const [key, item] of Object.entries(record2)) {
20514
+ if (typeof item === "string")
20515
+ record2[key] = sanitize.sanitizeText(item);
20516
+ else if (item && typeof item === "object" && (Array.isArray(item) || Object.getPrototypeOf(item) === Object.prototype))
20517
+ clean(item);
20518
+ }
20519
+ };
20520
+ clean(result);
20521
+ if (!result.traceId && result.requestId)
20522
+ result.traceId = result.requestId;
20466
20523
  for (const path of paths)
20467
20524
  redactPath(result, path.match(/\*|[^.[\]"']+/g) ?? []);
20468
20525
  return result;
@@ -20817,6 +20874,99 @@ var object2 = {
20817
20874
  fromEntries
20818
20875
  };
20819
20876
 
20877
+ // src/utils/core-util-runtime.ts
20878
+ function failure2(module, phase, detail) {
20879
+ const fields = [];
20880
+ if (detail && typeof detail === "object" && "ext" in detail && detail.ext && typeof detail.ext === "object" && "fields" in detail.ext && Array.isArray(detail.ext.fields)) {
20881
+ fields.push(...detail.ext.fields.filter((field) => typeof field === "string" && /^[\w.[\]-]{1,200}$/.test(field)));
20882
+ }
20883
+ if (detail && typeof detail === "object" && "issues" in detail && Array.isArray(detail.issues)) {
20884
+ for (const issue2 of detail.issues) {
20885
+ if (issue2 && typeof issue2 === "object" && "path" in issue2 && Array.isArray(issue2.path)) {
20886
+ const path = issue2.path.filter((part) => typeof part === "string" || typeof part === "number").join(".");
20887
+ if (/^[\w.[\]-]{1,200}$/.test(path))
20888
+ fields.push(path);
20889
+ }
20890
+ }
20891
+ }
20892
+ const code = detail && typeof detail === "object" && "code" in detail && (typeof detail.code === "number" || typeof detail.code === "string") ? detail.code : void 0;
20893
+ return { success: false, error: { ...HaiCommonError.INIT_FAILED, message: i18n.coreM(phase === "start" ? "core_runtimeStartFailed" : "core_runtimeCloseFailed", { params: { module } }), ext: { module, phase, ...code !== void 0 ? { code } : {}, ...fields.length ? { fields } : {} } } };
20894
+ }
20895
+ function createRuntime(definitions) {
20896
+ const steps = definitions.map((step) => ({ ...step }));
20897
+ const owned = [];
20898
+ let initialized = false;
20899
+ let starting;
20900
+ let closing;
20901
+ async function cleanup() {
20902
+ initialized = false;
20903
+ while (owned.length) {
20904
+ const step = owned.at(-1);
20905
+ try {
20906
+ const result = await step.close();
20907
+ if (result && !result.success)
20908
+ return failure2(step.name, "close", result.error);
20909
+ owned.pop();
20910
+ } catch (cause) {
20911
+ return failure2(step.name, "close", cause);
20912
+ }
20913
+ }
20914
+ return { success: true, data: void 0 };
20915
+ }
20916
+ async function initialize() {
20917
+ if (owned.length) {
20918
+ const cleaned = await cleanup();
20919
+ if (!cleaned.success)
20920
+ return cleaned;
20921
+ }
20922
+ for (const step of steps) {
20923
+ let startFailure;
20924
+ try {
20925
+ if (step.enabled && !step.enabled())
20926
+ continue;
20927
+ owned.push(step);
20928
+ const result = await step.start();
20929
+ if (result && !result.success)
20930
+ startFailure = failure2(step.name, "start", result.error);
20931
+ } catch (cause) {
20932
+ startFailure = failure2(step.name, "start", cause);
20933
+ }
20934
+ if (startFailure) {
20935
+ const cleaned = await cleanup();
20936
+ if (!cleaned.success)
20937
+ startFailure.error.ext = { ...startFailure.error.ext, cleanup: cleaned.error.ext };
20938
+ return startFailure;
20939
+ }
20940
+ }
20941
+ initialized = true;
20942
+ return { success: true, data: void 0 };
20943
+ }
20944
+ return {
20945
+ get isInitialized() {
20946
+ return initialized;
20947
+ },
20948
+ async start() {
20949
+ if (closing)
20950
+ await closing;
20951
+ if (initialized)
20952
+ return { success: true, data: void 0 };
20953
+ starting ??= initialize().finally(() => {
20954
+ starting = void 0;
20955
+ });
20956
+ return starting;
20957
+ },
20958
+ close() {
20959
+ closing ??= (async () => {
20960
+ await starting;
20961
+ return cleanup();
20962
+ })().finally(() => {
20963
+ closing = void 0;
20964
+ });
20965
+ return closing;
20966
+ }
20967
+ };
20968
+ }
20969
+
20820
20970
  // src/utils/core-util-string.ts
20821
20971
  var LEADING_LOWERCASE_REGEX = /^[a-z]/;
20822
20972
  function capitalize(str) {
@@ -21137,6 +21287,7 @@ function createCore(loggerFns) {
21137
21287
  * ```
21138
21288
  */
21139
21289
  module: {
21290
+ createRuntime,
21140
21291
  createNotInitializedKit,
21141
21292
  requiresSharedState
21142
21293
  }
@@ -21144,5 +21295,5 @@ function createCore(loggerFns) {
21144
21295
  }
21145
21296
 
21146
21297
  export { CoreConfigSchema, EnvSchema, HaiCommonError, HaiConfigError, LogFormatSchema, LogLevelSchema, LoggingConfigSchema, __commonJS, __toESM, createCore, emitLogRecord, err, i18n, installRequestContext, installRequestLocales, ok, requestContext, sanitize, sanitizeLogFields, typeUtils };
21147
- //# sourceMappingURL=chunk-MUQFCAQ5.js.map
21148
- //# sourceMappingURL=chunk-MUQFCAQ5.js.map
21298
+ //# sourceMappingURL=chunk-QPG7M3S3.js.map
21299
+ //# sourceMappingURL=chunk-QPG7M3S3.js.map