@klarkxy/dsh-font 0.2.5 → 0.2.7

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.
@@ -848,6 +848,281 @@ function registerSettingsSectionIcon(ctx, sectionId, order, component) {
848
848
  }, component));
849
849
  }
850
850
  //#endregion
851
+ //#region ../dsh-plugin-kit/src/log-shared.ts
852
+ const PLUGIN_LOG_LEVELS = [
853
+ "debug",
854
+ "info",
855
+ "warn",
856
+ "error",
857
+ "fault"
858
+ ];
859
+ const DEFAULT_PLUGIN_LOG_LEVEL = "info";
860
+ const PLUGIN_LOG_MAX_MESSAGE_CHARS = 16e3;
861
+ const SOURCE_RE = /^[a-z][a-z0-9-]{0,63}$/;
862
+ const EVENT_RE = /^[a-z][a-z0-9._-]{0,127}$/;
863
+ const CONTEXT_KEY_RE = /^[a-zA-Z][a-zA-Z0-9._-]{0,63}$/;
864
+ const SECRET_KEY_RE = /(?:api[_-]?key|access[_-]?token|refresh[_-]?token|bearer|authorization|cookie|set[_-]?cookie|nonce|credential|private[_-]?key|password|secret|app[_-]?secret|client[_-]?secret|z_c0|d_c0)$/i;
865
+ const CHAT_PAYLOAD_RE = /"role"\s*:\s*"(?:system|user|assistant|tool)"|"(?:messages|content|prompt|input_text|input_image|image_url)"\s*:\s*[\[{"']/i;
866
+ const CREDENTIAL_BODY_RE = /-----BEGIN (?:RSA |EC |OPENSSH |PRIVATE )?PRIVATE KEY-----|"type"\s*:\s*"service_account"|credentials\.json|\.dsh[/\\](?:credentials|auth)/i;
867
+ const AUTH_HEADER_RE = /\b(Authorization|Proxy-Authorization|Cookie|Set-Cookie)\s*:\s*[^\r\n]*/gi;
868
+ const BEARER_RE = /\bBearer\s+[A-Za-z0-9._\-+=/]{8,}/g;
869
+ const SECRET_FIELD_RE = /(["']?(?:api[_-]?key|access[_-]?token|refresh[_-]?token|token|bearer|authorization|cookie|set-cookie|nonce|credential|private[_-]?key|password|secret|app[_-]?secret|client[_-]?secret|password|z_c0|d_c0)["']?\s*[:=]\s*)(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\s,&;}]+)/gi;
870
+ const SECRET_QUERY_RE = /([?&](?:token|api[_-]?key|key|secret|password|bootstrap|code|sig|signature|credential|password)=)[^\s&#"']+/gi;
871
+ const URL_CREDENTIAL_RE = /\b(https?:\/\/)[^\s/:@]+:[^\s/@]+@/gi;
872
+ const BOOTSTRAP_RE = /\/bootstrap\/[^\s"'?&#]+/gi;
873
+ const KNOWN_TOKEN_RE = /\b(?:sk-[A-Za-z0-9_-]{10,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{20,}|tvly-[A-Za-z0-9_-]{10,}|AKIA[0-9A-Z]{16})\b/g;
874
+ const PATH_RE = /(?:[A-Za-z]:\\|\\\\)[^\s"'`<>|]+|(?:\/(?:home|Users|tmp|var|root)\/|~\/)[^\s"'`<>|]+/g;
875
+ function isPluginLogLevel(value) {
876
+ return typeof value === "string" && PLUGIN_LOG_LEVELS.includes(value);
877
+ }
878
+ function pluginLogLevelEnabled(level, minimum) {
879
+ return PLUGIN_LOG_LEVELS.indexOf(level) >= PLUGIN_LOG_LEVELS.indexOf(minimum);
880
+ }
881
+ function normalizePluginLogSource(raw) {
882
+ const stripped = String(raw || "").trim().replace(/^@[^/]+\//, "").toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "");
883
+ const bounded = (/^[a-z]/.test(stripped) ? stripped : `p-${stripped}`).slice(0, 64).replace(/-+$/g, "");
884
+ return SOURCE_RE.test(bounded) ? bounded : "dsh-plugin";
885
+ }
886
+ function normalizePluginLogEvent(raw) {
887
+ const cleaned = String(raw || "").trim().toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[^a-z]+/, "").slice(0, 128);
888
+ return EVENT_RE.test(cleaned) ? cleaned : "plugin.event";
889
+ }
890
+ /**
891
+ * Parse a level specification like `debug` or `dsh-zhihu=debug,dsh-dot:warn,info`.
892
+ * Source-specific rules win over a bare fallback level.
893
+ */
894
+ function parsePluginLogLevel(spec, source, fallback = DEFAULT_PLUGIN_LOG_LEVEL) {
895
+ if (!spec || typeof spec !== "string") return fallback;
896
+ const normalizedSource = source ? normalizePluginLogSource(source) : void 0;
897
+ let wildcard;
898
+ for (const token of spec.split(",").map((part) => part.trim()).filter(Boolean)) {
899
+ const lowered = token.toLowerCase();
900
+ if (isPluginLogLevel(lowered)) {
901
+ wildcard = lowered;
902
+ continue;
903
+ }
904
+ const match = /^([^=:]+)[=:]([a-z]+)$/i.exec(token);
905
+ if (!match) continue;
906
+ const target = match[1].trim();
907
+ const candidate = match[2].trim().toLowerCase();
908
+ if (!isPluginLogLevel(candidate)) continue;
909
+ if (target === "*") {
910
+ wildcard = candidate;
911
+ continue;
912
+ }
913
+ if (normalizedSource && normalizePluginLogSource(target) === normalizedSource) return candidate;
914
+ }
915
+ return wildcard ?? fallback;
916
+ }
917
+ function sanitizePluginLogText(text, maxChars = PLUGIN_LOG_MAX_MESSAGE_CHARS) {
918
+ if (!text) return "";
919
+ if (CREDENTIAL_BODY_RE.test(text)) return "[omitted credential material]";
920
+ if (CHAT_PAYLOAD_RE.test(text)) return "[omitted chat payload]";
921
+ return truncateLogText(text.replace(AUTH_HEADER_RE, "$1: [redacted]").replace(BEARER_RE, "Bearer [redacted]").replace(SECRET_FIELD_RE, (full, prefix) => {
922
+ const value = full.slice(prefix.length);
923
+ if (value.startsWith("\"")) return `${prefix}"[redacted]"`;
924
+ if (value.startsWith("'")) return `${prefix}'[redacted]'`;
925
+ return `${prefix}[redacted]`;
926
+ }).replace(SECRET_QUERY_RE, "$1[redacted]").replace(URL_CREDENTIAL_RE, "$1[redacted]@").replace(BOOTSTRAP_RE, "/bootstrap/[redacted]").replace(KNOWN_TOKEN_RE, "[redacted]").replace(PATH_RE, "[path]"), maxChars);
927
+ }
928
+ function sanitizePluginLogContext(input) {
929
+ if (!input) return void 0;
930
+ const output = {};
931
+ for (const [key, value] of Object.entries(input).slice(0, 32)) {
932
+ if (value === void 0 || !CONTEXT_KEY_RE.test(key)) continue;
933
+ if (typeof value === "number" && !Number.isFinite(value)) continue;
934
+ if (SECRET_KEY_RE.test(key)) {
935
+ output[key] = "[redacted]";
936
+ continue;
937
+ }
938
+ output[key] = typeof value === "string" ? sanitizePluginLogText(value, 1e3) : value;
939
+ }
940
+ if (!Object.keys(output).length) return void 0;
941
+ if (JSON.stringify(output).length <= 8e3) return output;
942
+ return {
943
+ omitted: true,
944
+ reason: "Diagnostic context exceeded its size limit."
945
+ };
946
+ }
947
+ function sanitizePluginLogError(error) {
948
+ if (error === void 0) return void 0;
949
+ const row = error && typeof error === "object" ? error : {};
950
+ const rawMessage = typeof row.message === "string" ? row.message : String(error);
951
+ const result = {
952
+ name: typeof row.name === "string" && row.name.trim() ? sanitizePluginLogText(row.name.trim(), 100) : "Error",
953
+ message: sanitizePluginLogText(rawMessage) || "Unknown error"
954
+ };
955
+ if (typeof row.stack === "string" && row.stack.trim()) result.stack = sanitizePluginLogText(row.stack, 24e3);
956
+ if (typeof row.code === "string" && /^[A-Za-z0-9_./:-]{1,100}$/.test(row.code)) result.code = sanitizePluginLogText(row.code, 100);
957
+ else if (typeof row.code === "number" && Number.isFinite(row.code)) result.code = String(row.code);
958
+ return result;
959
+ }
960
+ function mergePluginLogContext(base, extra) {
961
+ if (!base) return extra;
962
+ if (!extra) return base;
963
+ return {
964
+ ...base,
965
+ ...extra
966
+ };
967
+ }
968
+ function buildPluginLogEntry(input, meta) {
969
+ const entry = {
970
+ version: 1,
971
+ at: meta.at.toISOString(),
972
+ level: isPluginLogLevel(input.level) ? input.level : "info",
973
+ source: normalizePluginLogSource(meta.source),
974
+ surface: meta.surface,
975
+ ...meta.profile ? { profile: meta.profile } : {},
976
+ event: normalizePluginLogEvent(input.event),
977
+ message: sanitizePluginLogText(input.message || "No diagnostic message was provided.", PLUGIN_LOG_MAX_MESSAGE_CHARS),
978
+ ...meta.pid !== void 0 ? { pid: meta.pid } : {}
979
+ };
980
+ const context = sanitizePluginLogContext(mergePluginLogContext(meta.correlation, input.context));
981
+ if (context) entry.context = context;
982
+ const error = sanitizePluginLogError(input.error);
983
+ if (error) entry.error = error;
984
+ return entry;
985
+ }
986
+ function createChildPluginLogger(parent, bound) {
987
+ return {
988
+ get source() {
989
+ return parent.source;
990
+ },
991
+ get file() {
992
+ return parent.file;
993
+ },
994
+ get lastWriteError() {
995
+ return parent.lastWriteError;
996
+ },
997
+ debug: (event, message, context) => parent.debug(event, message, mergePluginLogContext(bound, context)),
998
+ info: (event, message, context) => parent.info(event, message, mergePluginLogContext(bound, context)),
999
+ warn: (event, message, error, context) => parent.warn(event, message, error, mergePluginLogContext(bound, context)),
1000
+ error: (event, message, error, context) => parent.error(event, message, error, mergePluginLogContext(bound, context)),
1001
+ fault: (event, message, error, context) => parent.fault(event, message, error, mergePluginLogContext(bound, context)),
1002
+ write: (input) => parent.write({
1003
+ ...input,
1004
+ context: mergePluginLogContext(bound, input.context)
1005
+ }),
1006
+ child: (next) => createChildPluginLogger(parent, mergePluginLogContext(bound, next) ?? {})
1007
+ };
1008
+ }
1009
+ function truncateLogText(text, maxChars) {
1010
+ if (text.length <= maxChars) return text;
1011
+ const marker = "[truncated]\n";
1012
+ if (maxChars <= 12) return text.slice(0, Math.max(0, maxChars));
1013
+ return `${marker}${text.slice(-(maxChars - 12))}`;
1014
+ }
1015
+ //#endregion
1016
+ //#region ../dsh-plugin-kit/src/client-logger.ts
1017
+ const CLIENT_PLUGIN_LOG_GLOBAL = "__KLARKXY_PLUGIN_LOGS__";
1018
+ function readStorageFlag(key) {
1019
+ try {
1020
+ const value = (globalThis.window?.localStorage)?.getItem?.(key);
1021
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
1022
+ } catch {
1023
+ return;
1024
+ }
1025
+ }
1026
+ function sharedClientBuffer(limit) {
1027
+ const carrier = globalThis;
1028
+ if (!Array.isArray(carrier["__KLARKXY_PLUGIN_LOGS__"])) try {
1029
+ carrier[CLIENT_PLUGIN_LOG_GLOBAL] = [];
1030
+ } catch {
1031
+ return [];
1032
+ }
1033
+ const list = carrier[CLIENT_PLUGIN_LOG_GLOBAL];
1034
+ const overflow = list.length - limit;
1035
+ if (overflow > 0) list.splice(0, overflow);
1036
+ return list;
1037
+ }
1038
+ function createClientPluginLogger(source, ctx, options = {}) {
1039
+ const normalized = normalizePluginLogSource(source);
1040
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
1041
+ const limit = Math.max(10, options.bufferLimit ?? 500);
1042
+ const browserCtx = ctx && typeof ctx === "object" ? ctx : void 0;
1043
+ const resolveMinimum = () => {
1044
+ if (options.minimumLevel) return options.minimumLevel;
1045
+ return parsePluginLogLevel(readStorageFlag("dsh-plugin-log-level"), normalized, DEFAULT_PLUGIN_LOG_LEVEL);
1046
+ };
1047
+ const logger = {
1048
+ source: normalized,
1049
+ file: null,
1050
+ lastWriteError: null,
1051
+ debug: (event, message, context) => logger.write({
1052
+ level: "debug",
1053
+ event,
1054
+ message,
1055
+ ...context ? { context } : {}
1056
+ }),
1057
+ info: (event, message, context) => logger.write({
1058
+ level: "info",
1059
+ event,
1060
+ message,
1061
+ ...context ? { context } : {}
1062
+ }),
1063
+ warn: (event, message, error, context) => logger.write({
1064
+ level: "warn",
1065
+ event,
1066
+ message,
1067
+ ...error !== void 0 ? { error } : {},
1068
+ ...context ? { context } : {}
1069
+ }),
1070
+ error: (event, message, error, context) => logger.write({
1071
+ level: "error",
1072
+ event,
1073
+ message,
1074
+ ...error !== void 0 ? { error } : {},
1075
+ ...context ? { context } : {}
1076
+ }),
1077
+ fault: (event, message, error, context) => logger.write({
1078
+ level: "fault",
1079
+ event,
1080
+ message,
1081
+ ...error !== void 0 ? { error } : {},
1082
+ ...context ? { context } : {}
1083
+ }),
1084
+ child: (context) => createChildPluginLogger(logger, context),
1085
+ write(input) {
1086
+ try {
1087
+ if (!pluginLogLevelEnabled(input.level, resolveMinimum())) return false;
1088
+ const entry = buildPluginLogEntry(input, {
1089
+ at: now(),
1090
+ source: normalized,
1091
+ surface: "client"
1092
+ });
1093
+ const buffer = sharedClientBuffer(limit);
1094
+ buffer.push(entry);
1095
+ const overflow = buffer.length - limit;
1096
+ if (overflow > 0) buffer.splice(0, overflow);
1097
+ if (options.forwardToHostLogger !== false && browserCtx?.logger) {
1098
+ const summary = sanitizePluginLogText(`${normalized} [${entry.event}]: ${entry.message}`, 500);
1099
+ if (entry.level === "warn" && typeof browserCtx.logger.warn === "function") browserCtx.logger.warn(summary);
1100
+ else if ((entry.level === "error" || entry.level === "fault") && typeof browserCtx.logger.error === "function") browserCtx.logger.error(summary);
1101
+ }
1102
+ if (readStorageFlag("dsh-plugin-log-console") === "1") {
1103
+ const con = globalThis.console;
1104
+ (entry.level === "debug" ? con?.debug : entry.level === "info" ? con?.info : entry.level === "warn" ? con?.warn : con?.error)?.call(con, `[${normalized}] ${entry.event}: ${entry.message}`, entry);
1105
+ }
1106
+ return true;
1107
+ } catch {
1108
+ return false;
1109
+ }
1110
+ }
1111
+ };
1112
+ return logger;
1113
+ }
1114
+ function installClientPluginLogger(ctx, source, options = {}) {
1115
+ const logger = createClientPluginLogger(source, ctx, options);
1116
+ logger.info("client.loaded", "Client plugin initialized.", options.loadedContext);
1117
+ const browserCtx = ctx && typeof ctx === "object" ? ctx : void 0;
1118
+ if (typeof browserCtx?.effect === "function") try {
1119
+ browserCtx.effect(() => () => {
1120
+ logger.debug("client.disposed", "Client plugin disposed.");
1121
+ }, `${logger.source}.client-logger`);
1122
+ } catch {}
1123
+ return logger;
1124
+ }
1125
+ //#endregion
851
1126
  //#region src/client.tsx
852
1127
  const name = "dsh-font-client";
853
1128
  const inject = [
@@ -1138,6 +1413,7 @@ function FontSettingsGroup(props) {
1138
1413
  if (fontList.state === "loading") return;
1139
1414
  const query = globalThis.queryLocalFonts;
1140
1415
  if (typeof query !== "function") {
1416
+ createClientPluginLogger(PLUGIN_NAME).debug("system-fonts.unsupported", "Local Font Access API is not available in this browser.");
1141
1417
  setFontList({
1142
1418
  state: "denied",
1143
1419
  families: []
@@ -1149,12 +1425,14 @@ function FontSettingsGroup(props) {
1149
1425
  families: current.families
1150
1426
  }));
1151
1427
  try {
1152
- const fonts = await query();
1428
+ const families = uniqueSystemFonts(await query());
1429
+ createClientPluginLogger(PLUGIN_NAME).info("system-fonts.loaded", "Loaded system font families.", { count: families.length });
1153
1430
  setFontList({
1154
1431
  state: "ready",
1155
- families: uniqueSystemFonts(fonts)
1432
+ families
1156
1433
  });
1157
- } catch {
1434
+ } catch (error) {
1435
+ createClientPluginLogger(PLUGIN_NAME).warn("system-fonts.denied", "System font enumeration was denied or failed.", error);
1158
1436
  setFontList((current) => ({
1159
1437
  state: "denied",
1160
1438
  families: current.families
@@ -1304,6 +1582,7 @@ function FontSettingsGroup(props) {
1304
1582
  });
1305
1583
  }
1306
1584
  function apply(ctx) {
1585
+ const logger = installClientPluginLogger(ctx, PLUGIN_NAME);
1307
1586
  const client = ctx;
1308
1587
  const store = createFontSettingsStore(readStorage());
1309
1588
  const conversation = createConversationFontStore(readStorage());
@@ -1328,9 +1607,13 @@ function apply(ctx) {
1328
1607
  while (sheet.cssRules.length > 0) sheet.deleteRule(0);
1329
1608
  const declarations = conversationFontDeclarations(conversation.get(), fontTokenDeclarations(document.styleSheets ?? []));
1330
1609
  if (declarations.length === 0) return;
1331
- sheet.insertRule(`${CONVERSATION_FONT_SELECTOR}{}`);
1332
- const rule = sheet.cssRules[0];
1333
- for (const [name, value] of declarations) rule.style.setProperty(name, value);
1610
+ try {
1611
+ sheet.insertRule(`${CONVERSATION_FONT_SELECTOR}{}`);
1612
+ const rule = sheet.cssRules[0];
1613
+ for (const [name, value] of declarations) rule.style.setProperty(name, value);
1614
+ } catch (error) {
1615
+ logger.warn("conversation-font.rule-failed", "Failed to apply conversation font CSS rule.", error);
1616
+ }
1334
1617
  };
1335
1618
  write();
1336
1619
  const unsubscribe = conversation.subscribe(write);