whoburnedmore 0.9.14 → 0.9.15

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.
Files changed (2) hide show
  1. package/dist/index.js +2002 -1850
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -8,10 +8,10 @@ var __export = (target, all) => {
8
8
  // src/index.ts
9
9
  import { spawn } from "node:child_process";
10
10
  import { createHash } from "node:crypto";
11
- import { mkdirSync as mkdirSync4, writeFileSync as writeFileSync4 } from "node:fs";
11
+ import { mkdirSync as mkdirSync5, writeFileSync as writeFileSync5 } from "node:fs";
12
12
  import { createRequire as createRequire4 } from "node:module";
13
13
  import { platform as platform3 } from "node:os";
14
- import { join as join11 } from "node:path";
14
+ import { join as join12 } from "node:path";
15
15
  import { createInterface } from "node:readline/promises";
16
16
  import pc2 from "picocolors";
17
17
 
@@ -46,22 +46,25 @@ function parseValueFlag(args, name) {
46
46
  return void 0;
47
47
  }
48
48
  function resolveCommand(args) {
49
- if (args.includes("--help") || args.includes("-h") || args.includes("help")) {
50
- return "help";
51
- }
52
- if (args.includes("--version") || args.includes("-v") || args.includes("version")) {
53
- return "version";
54
- }
55
49
  const valueFlags = /* @__PURE__ */ new Set(["--board", "--org", "--token", "--pass", "--code"]);
50
+ const flags = [];
51
+ const words = [];
56
52
  for (let i = 0; i < args.length; i++) {
57
53
  const a = args[i];
58
54
  if (a.startsWith("-")) {
55
+ flags.push(a);
59
56
  if (valueFlags.has(a)) i++;
60
57
  continue;
61
58
  }
62
- return a;
59
+ words.push(a);
60
+ }
61
+ if (flags.includes("--help") || flags.includes("-h") || words.includes("help")) {
62
+ return "help";
63
+ }
64
+ if (flags.includes("--version") || flags.includes("-v") || words.includes("version")) {
65
+ return "version";
63
66
  }
64
- return "run";
67
+ return words[0] ?? "run";
65
68
  }
66
69
 
67
70
  // src/api.ts
@@ -786,1525 +789,1003 @@ async function daemonLoop(deps) {
786
789
  // src/collect.ts
787
790
  import { execFile } from "node:child_process";
788
791
  import { createRequire as createRequire3 } from "node:module";
789
- import { dirname as dirname5, join as join10 } from "node:path";
792
+ import { dirname as dirname6, join as join11 } from "node:path";
790
793
  import { promisify } from "node:util";
791
794
 
792
795
  // src/attribution.ts
793
- import { readFileSync as readFileSync3, readdirSync, statSync as statSync2 } from "node:fs";
796
+ import { readdirSync, statSync as statSync2 } from "node:fs";
797
+ import { homedir as homedir4 } from "node:os";
798
+ import { join as join5 } from "node:path";
799
+
800
+ // src/native/claude.ts
801
+ import { readdir, readFile as readFile2 } from "node:fs/promises";
794
802
  import { homedir as homedir3 } from "node:os";
795
- import { join as join3 } from "node:path";
796
- var CLAUDE_PROJECTS = join3(homedir3(), ".claude", "projects");
797
- var CODEX_SESSIONS = join3(homedir3(), ".codex", "sessions");
798
- var MAX_FILES = 5e3;
799
- var MAX_FILE_BYTES = 64 * 1024 * 1024;
800
- var TIME_BUDGET_MS = 12e3;
801
- var MAX_STATS = 300;
802
- function createAccumulator() {
803
- return {
804
- tools: /* @__PURE__ */ new Map(),
805
- skills: /* @__PURE__ */ new Map(),
806
- agent: {
807
- messageCount: 0,
808
- subagentMessages: 0,
809
- subagentTokens: 0,
810
- totalTokens: 0,
811
- userMessageCount: 0
812
- },
813
- sessionMessages: /* @__PURE__ */ new Map()
814
- };
815
- }
816
- function createFileContext() {
817
- return { toolNames: /* @__PURE__ */ new Map() };
818
- }
819
- function recordTokens(usage) {
820
- if (!usage || typeof usage !== "object") return 0;
821
- const u = usage;
822
- const n = (v) => {
823
- const x = Math.round(Number(v));
824
- return Number.isFinite(x) && x > 0 ? x : 0;
825
- };
826
- return n(u.input_tokens) + n(u.output_tokens) + n(u.cache_creation_input_tokens) + n(u.cache_read_input_tokens);
827
- }
828
- function hasHumanText(content) {
829
- const isHuman = (t) => {
830
- const s = t.trim();
831
- return s.length > 0 && !s.startsWith("<system-reminder") && !s.startsWith("<command-") && !s.startsWith("Caveat:");
803
+ import { join as join4 } from "node:path";
804
+
805
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js
806
+ var external_exports = {};
807
+ __export(external_exports, {
808
+ BRAND: () => BRAND,
809
+ DIRTY: () => DIRTY,
810
+ EMPTY_PATH: () => EMPTY_PATH,
811
+ INVALID: () => INVALID,
812
+ NEVER: () => NEVER,
813
+ OK: () => OK,
814
+ ParseStatus: () => ParseStatus,
815
+ Schema: () => ZodType,
816
+ ZodAny: () => ZodAny,
817
+ ZodArray: () => ZodArray,
818
+ ZodBigInt: () => ZodBigInt,
819
+ ZodBoolean: () => ZodBoolean,
820
+ ZodBranded: () => ZodBranded,
821
+ ZodCatch: () => ZodCatch,
822
+ ZodDate: () => ZodDate,
823
+ ZodDefault: () => ZodDefault,
824
+ ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
825
+ ZodEffects: () => ZodEffects,
826
+ ZodEnum: () => ZodEnum,
827
+ ZodError: () => ZodError,
828
+ ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
829
+ ZodFunction: () => ZodFunction,
830
+ ZodIntersection: () => ZodIntersection,
831
+ ZodIssueCode: () => ZodIssueCode,
832
+ ZodLazy: () => ZodLazy,
833
+ ZodLiteral: () => ZodLiteral,
834
+ ZodMap: () => ZodMap,
835
+ ZodNaN: () => ZodNaN,
836
+ ZodNativeEnum: () => ZodNativeEnum,
837
+ ZodNever: () => ZodNever,
838
+ ZodNull: () => ZodNull,
839
+ ZodNullable: () => ZodNullable,
840
+ ZodNumber: () => ZodNumber,
841
+ ZodObject: () => ZodObject,
842
+ ZodOptional: () => ZodOptional,
843
+ ZodParsedType: () => ZodParsedType,
844
+ ZodPipeline: () => ZodPipeline,
845
+ ZodPromise: () => ZodPromise,
846
+ ZodReadonly: () => ZodReadonly,
847
+ ZodRecord: () => ZodRecord,
848
+ ZodSchema: () => ZodType,
849
+ ZodSet: () => ZodSet,
850
+ ZodString: () => ZodString,
851
+ ZodSymbol: () => ZodSymbol,
852
+ ZodTransformer: () => ZodEffects,
853
+ ZodTuple: () => ZodTuple,
854
+ ZodType: () => ZodType,
855
+ ZodUndefined: () => ZodUndefined,
856
+ ZodUnion: () => ZodUnion,
857
+ ZodUnknown: () => ZodUnknown,
858
+ ZodVoid: () => ZodVoid,
859
+ addIssueToContext: () => addIssueToContext,
860
+ any: () => anyType,
861
+ array: () => arrayType,
862
+ bigint: () => bigIntType,
863
+ boolean: () => booleanType,
864
+ coerce: () => coerce,
865
+ custom: () => custom,
866
+ date: () => dateType,
867
+ datetimeRegex: () => datetimeRegex,
868
+ defaultErrorMap: () => en_default,
869
+ discriminatedUnion: () => discriminatedUnionType,
870
+ effect: () => effectsType,
871
+ enum: () => enumType,
872
+ function: () => functionType,
873
+ getErrorMap: () => getErrorMap,
874
+ getParsedType: () => getParsedType,
875
+ instanceof: () => instanceOfType,
876
+ intersection: () => intersectionType,
877
+ isAborted: () => isAborted,
878
+ isAsync: () => isAsync,
879
+ isDirty: () => isDirty,
880
+ isValid: () => isValid,
881
+ late: () => late,
882
+ lazy: () => lazyType,
883
+ literal: () => literalType,
884
+ makeIssue: () => makeIssue,
885
+ map: () => mapType,
886
+ nan: () => nanType,
887
+ nativeEnum: () => nativeEnumType,
888
+ never: () => neverType,
889
+ null: () => nullType,
890
+ nullable: () => nullableType,
891
+ number: () => numberType,
892
+ object: () => objectType,
893
+ objectUtil: () => objectUtil,
894
+ oboolean: () => oboolean,
895
+ onumber: () => onumber,
896
+ optional: () => optionalType,
897
+ ostring: () => ostring,
898
+ pipeline: () => pipelineType,
899
+ preprocess: () => preprocessType,
900
+ promise: () => promiseType,
901
+ quotelessJson: () => quotelessJson,
902
+ record: () => recordType,
903
+ set: () => setType,
904
+ setErrorMap: () => setErrorMap,
905
+ strictObject: () => strictObjectType,
906
+ string: () => stringType,
907
+ symbol: () => symbolType,
908
+ transformer: () => effectsType,
909
+ tuple: () => tupleType,
910
+ undefined: () => undefinedType,
911
+ union: () => unionType,
912
+ unknown: () => unknownType,
913
+ util: () => util,
914
+ void: () => voidType
915
+ });
916
+
917
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js
918
+ var util;
919
+ (function(util2) {
920
+ util2.assertEqual = (_) => {
832
921
  };
833
- if (typeof content === "string") return isHuman(content);
834
- if (!Array.isArray(content)) return false;
835
- return content.some(
836
- (b) => b !== null && typeof b === "object" && b.type === "text" && typeof b.text === "string" && isHuman(b.text)
837
- );
838
- }
839
- function processRecord(rec, acc, ctx) {
840
- if (!rec || typeof rec !== "object") return;
841
- const r = rec;
842
- const recTokens = recordTokens(r.message?.usage);
843
- if ((r.type === "user" || r.message?.role === "user") && r.isSidechain !== true && r.isMeta !== true && hasHumanText(r.message?.content)) {
844
- acc.agent.userMessageCount += 1;
922
+ function assertIs(_arg) {
845
923
  }
846
- if (typeof r.attributionSkill === "string" && r.attributionSkill) {
847
- const s = r.attributionSkill.slice(0, 128);
848
- const sk = acc.skills.get(s) ?? { count: 0, tokens: 0 };
849
- sk.count += 1;
850
- sk.tokens += recTokens;
851
- acc.skills.set(s, sk);
924
+ util2.assertIs = assertIs;
925
+ function assertNever(_x) {
926
+ throw new Error();
852
927
  }
853
- const content = r.message?.content;
854
- if (!Array.isArray(content)) return;
855
- const isAssistant = r.type === "assistant" || r.message?.role === "assistant";
856
- const isUser = r.type === "user" || r.message?.role === "user";
857
- if (isAssistant) {
858
- const toolUses = [];
859
- for (const block of content) {
860
- if (block && typeof block === "object" && block.type === "tool_use" && typeof block.name === "string") {
861
- const name = block.name.slice(0, 128);
862
- if (!name) continue;
863
- const id = block.id;
864
- toolUses.push({ name, id: typeof id === "string" ? id : void 0 });
865
- }
866
- }
867
- const perToolTokens = toolUses.length > 0 ? Math.floor(recTokens / toolUses.length) : 0;
868
- for (const tu of toolUses) {
869
- const t = acc.tools.get(tu.name) ?? { count: 0, errors: 0, tokens: 0 };
870
- t.count += 1;
871
- t.tokens += perToolTokens;
872
- acc.tools.set(tu.name, t);
873
- if (tu.id) ctx.toolNames.set(tu.id, tu.name);
874
- }
875
- const tokens = recTokens;
876
- acc.agent.messageCount += 1;
877
- acc.agent.totalTokens += tokens;
878
- const sidechain = r.isSidechain === true;
879
- if (sidechain) {
880
- acc.agent.subagentMessages += 1;
881
- acc.agent.subagentTokens += tokens;
928
+ util2.assertNever = assertNever;
929
+ util2.arrayToEnum = (items) => {
930
+ const obj = {};
931
+ for (const item of items) {
932
+ obj[item] = item;
882
933
  }
883
- if (typeof r.sessionId === "string" && r.sessionId) {
884
- acc.sessionMessages.set(
885
- r.sessionId,
886
- (acc.sessionMessages.get(r.sessionId) ?? 0) + 1
887
- );
934
+ return obj;
935
+ };
936
+ util2.getValidEnumValues = (obj) => {
937
+ const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
938
+ const filtered = {};
939
+ for (const k of validKeys) {
940
+ filtered[k] = obj[k];
888
941
  }
889
- } else if (isUser) {
890
- for (const block of content) {
891
- if (block && typeof block === "object" && block.type === "tool_result" && block.is_error === true) {
892
- const id = block.tool_use_id;
893
- const name = typeof id === "string" ? ctx.toolNames.get(id) : void 0;
894
- if (name) {
895
- const t = acc.tools.get(name) ?? { count: 0, errors: 0, tokens: 0 };
896
- t.errors += 1;
897
- acc.tools.set(name, t);
898
- }
942
+ return util2.objectValues(filtered);
943
+ };
944
+ util2.objectValues = (obj) => {
945
+ return util2.objectKeys(obj).map(function(e) {
946
+ return obj[e];
947
+ });
948
+ };
949
+ util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
950
+ const keys = [];
951
+ for (const key in object) {
952
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
953
+ keys.push(key);
899
954
  }
900
955
  }
901
- }
902
- }
903
- function toSkillStats(map) {
904
- return [...map.entries()].map(([name, v]) => ({ name, count: v.count, tokens: v.tokens })).filter((s) => s.count > 0).sort((a, b) => b.tokens - a.tokens || b.count - a.count).slice(0, MAX_STATS).map((s) => s.tokens > 0 ? s : { name: s.name, count: s.count });
905
- }
906
- function toToolStats(map) {
907
- return [...map.entries()].map(([name, v]) => ({ name, count: v.count, errors: v.errors, tokens: v.tokens })).filter((s) => s.count > 0).sort((a, b) => b.tokens - a.tokens || b.count - a.count).slice(0, MAX_STATS).map((s) => {
908
- const base = { name: s.name, count: s.count };
909
- if (s.errors > 0) base.errors = s.errors;
910
- if (s.tokens > 0) base.tokens = s.tokens;
911
- return base;
912
- });
913
- }
914
- function accumulatorToResult(acc) {
915
- return {
916
- tools: toToolStats(acc.tools),
917
- skills: toSkillStats(acc.skills),
918
- agent: { ...acc.agent },
919
- sessionMessages: acc.sessionMessages,
920
- complete: true
956
+ return keys;
921
957
  };
922
- }
923
- function numTok(v) {
924
- const x = Math.round(Number(v));
925
- return Number.isFinite(x) && x > 0 ? x : 0;
926
- }
927
- function createCodexContext() {
928
- return { pending: [] };
929
- }
930
- function processCodexRecord(rec, acc, ctx) {
931
- if (!rec || typeof rec !== "object") return;
932
- const r = rec;
933
- if (!r.payload || typeof r.payload !== "object") return;
934
- const pl = r.payload;
935
- const ptype = pl.type;
936
- if (r.type === "session_meta" || r.type === "turn_context") return;
937
- if (ptype === "function_call" || ptype === "custom_tool_call" || ptype === "local_shell_call") {
938
- const raw = typeof pl.name === "string" ? pl.name : ptype === "local_shell_call" ? "local_shell" : "";
939
- const name = raw.slice(0, 128);
940
- if (!name) return;
941
- const id = typeof pl.call_id === "string" ? pl.call_id : void 0;
942
- ctx.pending.push({ name, id });
943
- const t = acc.tools.get(name) ?? { count: 0, errors: 0, tokens: 0 };
944
- t.count += 1;
945
- acc.tools.set(name, t);
946
- return;
947
- }
948
- if (ptype === "token_count") {
949
- const info = pl.info;
950
- const last = info?.last_token_usage;
951
- if (!last) return;
952
- const inputTokens = numTok(last.input_tokens);
953
- const cacheReadTokens = numTok(last.cached_input_tokens);
954
- const outputTokens = numTok(last.output_tokens) + numTok(last.reasoning_output_tokens);
955
- const tokens = numTok(last.total_tokens) || inputTokens + cacheReadTokens + outputTokens;
956
- if (tokens <= 0) {
957
- ctx.pending = [];
958
- return;
959
- }
960
- acc.agent.messageCount += 1;
961
- acc.agent.totalTokens += tokens;
962
- const per = ctx.pending.length > 0 ? Math.floor(tokens / ctx.pending.length) : 0;
963
- for (const tu of ctx.pending) {
964
- const t = acc.tools.get(tu.name);
965
- if (t) t.tokens += per;
958
+ util2.find = (arr, checker) => {
959
+ for (const item of arr) {
960
+ if (checker(item))
961
+ return item;
966
962
  }
967
- ctx.pending = [];
968
- }
969
- }
970
- function readLines(file) {
971
- let size = 0;
972
- try {
973
- size = statSync2(file).size;
974
- } catch {
975
- return [];
976
- }
977
- if (size > MAX_FILE_BYTES) return [];
978
- try {
979
- return readFileSync3(file, "utf8").split("\n");
980
- } catch {
981
- return [];
963
+ return void 0;
964
+ };
965
+ util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
966
+ function joinValues(array, separator = " | ") {
967
+ return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
982
968
  }
983
- }
984
- function claudeProjectDirs() {
985
- const dirs = [CLAUDE_PROJECTS];
986
- const cfg = process.env.CLAUDE_CONFIG_DIR;
987
- if (cfg) dirs.push(join3(cfg, "projects"));
988
- dirs.push(join3(homedir3(), ".config", "claude", "projects"));
989
- return [...new Set(dirs)];
990
- }
991
- function listTranscripts(dir) {
992
- const out = [];
993
- const walk = (d) => {
994
- if (out.length >= MAX_FILES) return;
995
- let entries;
996
- try {
997
- entries = readdirSync(d, { withFileTypes: true });
998
- } catch {
999
- return;
1000
- }
1001
- for (const e of entries) {
1002
- if (out.length >= MAX_FILES) return;
1003
- const p = join3(d, e.name);
1004
- if (e.isDirectory()) walk(p);
1005
- else if (e.isFile() && e.name.endsWith(".jsonl")) {
1006
- try {
1007
- out.push({ path: p, mtime: statSync2(p).mtimeMs });
1008
- } catch {
1009
- }
1010
- }
969
+ util2.joinValues = joinValues;
970
+ util2.jsonStringifyReplacer = (_, value) => {
971
+ if (typeof value === "bigint") {
972
+ return value.toString();
1011
973
  }
974
+ return value;
1012
975
  };
1013
- walk(dir);
1014
- return out.sort((a, b) => b.mtime - a.mtime).slice(0, MAX_FILES).map((f) => f.path);
1015
- }
1016
- async function collectAttribution() {
1017
- const acc = createAccumulator();
1018
- const deadline = Date.now() + TIME_BUDGET_MS;
1019
- let complete = true;
1020
- let sinceYield = 0;
1021
- const breathe = async () => {
1022
- if (++sinceYield >= 8) {
1023
- sinceYield = 0;
1024
- await new Promise((r) => setImmediate(r));
1025
- }
976
+ })(util || (util = {}));
977
+ var objectUtil;
978
+ (function(objectUtil2) {
979
+ objectUtil2.mergeShapes = (first, second) => {
980
+ return {
981
+ ...first,
982
+ ...second
983
+ // second overwrites first
984
+ };
1026
985
  };
1027
- try {
1028
- for (const dir of claudeProjectDirs()) {
1029
- for (const file of listTranscripts(dir)) {
1030
- if (Date.now() > deadline) {
1031
- complete = false;
1032
- break;
1033
- }
1034
- const ctx = createFileContext();
1035
- for (const line of readLines(file)) {
1036
- if (!line) continue;
1037
- try {
1038
- processRecord(JSON.parse(line), acc, ctx);
1039
- } catch {
1040
- }
1041
- }
1042
- await breathe();
986
+ })(objectUtil || (objectUtil = {}));
987
+ var ZodParsedType = util.arrayToEnum([
988
+ "string",
989
+ "nan",
990
+ "number",
991
+ "integer",
992
+ "float",
993
+ "boolean",
994
+ "date",
995
+ "bigint",
996
+ "symbol",
997
+ "function",
998
+ "undefined",
999
+ "null",
1000
+ "array",
1001
+ "object",
1002
+ "unknown",
1003
+ "promise",
1004
+ "void",
1005
+ "never",
1006
+ "map",
1007
+ "set"
1008
+ ]);
1009
+ var getParsedType = (data) => {
1010
+ const t = typeof data;
1011
+ switch (t) {
1012
+ case "undefined":
1013
+ return ZodParsedType.undefined;
1014
+ case "string":
1015
+ return ZodParsedType.string;
1016
+ case "number":
1017
+ return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
1018
+ case "boolean":
1019
+ return ZodParsedType.boolean;
1020
+ case "function":
1021
+ return ZodParsedType.function;
1022
+ case "bigint":
1023
+ return ZodParsedType.bigint;
1024
+ case "symbol":
1025
+ return ZodParsedType.symbol;
1026
+ case "object":
1027
+ if (Array.isArray(data)) {
1028
+ return ZodParsedType.array;
1043
1029
  }
1044
- }
1045
- for (const file of listTranscripts(CODEX_SESSIONS)) {
1046
- if (Date.now() > deadline) {
1047
- complete = false;
1048
- break;
1030
+ if (data === null) {
1031
+ return ZodParsedType.null;
1049
1032
  }
1050
- const ctx = createCodexContext();
1051
- for (const line of readLines(file)) {
1052
- if (!line) continue;
1053
- try {
1054
- processCodexRecord(JSON.parse(line), acc, ctx);
1055
- } catch {
1056
- }
1033
+ if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
1034
+ return ZodParsedType.promise;
1057
1035
  }
1058
- await breathe();
1059
- }
1060
- } catch {
1061
- complete = false;
1036
+ if (typeof Map !== "undefined" && data instanceof Map) {
1037
+ return ZodParsedType.map;
1038
+ }
1039
+ if (typeof Set !== "undefined" && data instanceof Set) {
1040
+ return ZodParsedType.set;
1041
+ }
1042
+ if (typeof Date !== "undefined" && data instanceof Date) {
1043
+ return ZodParsedType.date;
1044
+ }
1045
+ return ZodParsedType.object;
1046
+ default:
1047
+ return ZodParsedType.unknown;
1062
1048
  }
1063
- return { ...accumulatorToResult(acc), complete };
1064
- }
1065
-
1066
- // src/cursor.ts
1067
- import { spawnSync as spawnSync3 } from "node:child_process";
1068
- import { existsSync as existsSync3 } from "node:fs";
1069
- import { createRequire as createRequire2 } from "node:module";
1070
- import { homedir as homedir4, platform as platform2 } from "node:os";
1071
- import { join as join5 } from "node:path";
1049
+ };
1072
1050
 
1073
- // src/tokscale.ts
1074
- import { spawnSync as spawnSync2 } from "node:child_process";
1075
- import { createRequire } from "node:module";
1076
- import { dirname as dirname2, join as join4 } from "node:path";
1077
- var LOOKBACK_DAYS = 30;
1078
- function num(n) {
1079
- const v = Math.round(Number(n));
1080
- return Number.isFinite(v) && v > 0 ? v : 0;
1081
- }
1082
- function numCost(n) {
1083
- const v = Number(n);
1084
- return Number.isFinite(v) && v > 0 ? v : 0;
1085
- }
1086
- function mapTokscaleDay(date, json) {
1087
- const entries = json?.entries;
1088
- if (!Array.isArray(entries)) return [];
1089
- const out = [];
1090
- for (const e of entries) {
1091
- const inputTokens = num(e.input);
1092
- const outputTokens = num(e.output) + num(e.reasoning);
1093
- const cacheCreationTokens = num(e.cacheWrite);
1094
- const cacheReadTokens = num(e.cacheRead);
1095
- const costUSD = numCost(e.cost);
1096
- const total = inputTokens + outputTokens + cacheCreationTokens + cacheReadTokens;
1097
- if (total === 0 && costUSD === 0) continue;
1098
- out.push({
1099
- date,
1100
- tool: "cursor",
1101
- model: typeof e.model === "string" && e.model ? e.model : "cursor",
1102
- inputTokens,
1103
- outputTokens,
1104
- cacheCreationTokens,
1105
- cacheReadTokens,
1106
- costUSD,
1107
- origin: "cli",
1108
- verified: false
1109
- });
1110
- }
1111
- return out;
1112
- }
1113
- function resolveTokscaleBin() {
1114
- try {
1115
- const require3 = createRequire(import.meta.url);
1116
- const pkgPath = require3.resolve("tokscale/package.json");
1117
- const pkg = require3("tokscale/package.json");
1118
- const rel = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.tokscale ?? "";
1119
- if (!rel) return null;
1120
- const binPath = join4(dirname2(pkgPath), rel);
1121
- if (/\.(c|m)?js$/.test(binPath)) {
1122
- return { cmd: process.execPath, prefixArgs: [binPath] };
1123
- }
1124
- return { cmd: binPath, prefixArgs: [] };
1125
- } catch {
1126
- return null;
1127
- }
1128
- }
1129
- function runTokscaleDay(bin, day) {
1130
- const res = spawnSync2(
1131
- bin.cmd,
1132
- [
1133
- ...bin.prefixArgs,
1134
- "--client",
1135
- "cursor",
1136
- "--json",
1137
- "--since",
1138
- day,
1139
- "--until",
1140
- day,
1141
- "--group-by",
1142
- "model",
1143
- "--no-spinner"
1144
- ],
1145
- { encoding: "utf8", maxBuffer: 32 * 1024 * 1024, timeout: 6e4 }
1146
- );
1147
- if (res.status !== 0 || !res.stdout) return null;
1148
- try {
1149
- return JSON.parse(res.stdout);
1150
- } catch {
1151
- return null;
1051
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js
1052
+ var ZodIssueCode = util.arrayToEnum([
1053
+ "invalid_type",
1054
+ "invalid_literal",
1055
+ "custom",
1056
+ "invalid_union",
1057
+ "invalid_union_discriminator",
1058
+ "invalid_enum_value",
1059
+ "unrecognized_keys",
1060
+ "invalid_arguments",
1061
+ "invalid_return_type",
1062
+ "invalid_date",
1063
+ "invalid_string",
1064
+ "too_small",
1065
+ "too_big",
1066
+ "invalid_intersection_types",
1067
+ "not_multiple_of",
1068
+ "not_finite"
1069
+ ]);
1070
+ var quotelessJson = (obj) => {
1071
+ const json = JSON.stringify(obj, null, 2);
1072
+ return json.replace(/"([^"]+)":/g, "$1:");
1073
+ };
1074
+ var ZodError = class _ZodError extends Error {
1075
+ get errors() {
1076
+ return this.issues;
1152
1077
  }
1153
- }
1154
- function collectCursorViaTokscale(lookbackDays = LOOKBACK_DAYS) {
1155
- const bin = resolveTokscaleBin();
1156
- if (!bin) return [];
1157
- const today = /* @__PURE__ */ new Date();
1158
- const day = (offset) => {
1159
- const d = new Date(today.getTime() - offset * 864e5);
1160
- return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
1161
- };
1162
- if (mapTokscaleDay(day(0), runTokscaleDay(bin, day(0))).length === 0) {
1163
- if (mapTokscaleDay(day(1), runTokscaleDay(bin, day(1))).length === 0) {
1164
- return [];
1078
+ constructor(issues) {
1079
+ super();
1080
+ this.issues = [];
1081
+ this.addIssue = (sub) => {
1082
+ this.issues = [...this.issues, sub];
1083
+ };
1084
+ this.addIssues = (subs = []) => {
1085
+ this.issues = [...this.issues, ...subs];
1086
+ };
1087
+ const actualProto = new.target.prototype;
1088
+ if (Object.setPrototypeOf) {
1089
+ Object.setPrototypeOf(this, actualProto);
1090
+ } else {
1091
+ this.__proto__ = actualProto;
1165
1092
  }
1093
+ this.name = "ZodError";
1094
+ this.issues = issues;
1166
1095
  }
1167
- const out = [];
1168
- for (let i = 0; i < lookbackDays; i++) {
1169
- const d = day(i);
1170
- out.push(...mapTokscaleDay(d, runTokscaleDay(bin, d)));
1096
+ format(_mapper) {
1097
+ const mapper = _mapper || function(issue) {
1098
+ return issue.message;
1099
+ };
1100
+ const fieldErrors = { _errors: [] };
1101
+ const processError = (error) => {
1102
+ for (const issue of error.issues) {
1103
+ if (issue.code === "invalid_union") {
1104
+ issue.unionErrors.map(processError);
1105
+ } else if (issue.code === "invalid_return_type") {
1106
+ processError(issue.returnTypeError);
1107
+ } else if (issue.code === "invalid_arguments") {
1108
+ processError(issue.argumentsError);
1109
+ } else if (issue.path.length === 0) {
1110
+ fieldErrors._errors.push(mapper(issue));
1111
+ } else {
1112
+ let curr = fieldErrors;
1113
+ let i = 0;
1114
+ while (i < issue.path.length) {
1115
+ const el = issue.path[i];
1116
+ const terminal = i === issue.path.length - 1;
1117
+ if (!terminal) {
1118
+ curr[el] = curr[el] || { _errors: [] };
1119
+ } else {
1120
+ curr[el] = curr[el] || { _errors: [] };
1121
+ curr[el]._errors.push(mapper(issue));
1122
+ }
1123
+ curr = curr[el];
1124
+ i++;
1125
+ }
1126
+ }
1127
+ }
1128
+ };
1129
+ processError(this);
1130
+ return fieldErrors;
1171
1131
  }
1172
- return out;
1173
- }
1174
-
1175
- // src/cursor.ts
1176
- var EVENTS_URL = "https://cursor.com/api/dashboard/get-filtered-usage-events";
1177
- function cursorDbPath() {
1178
- const home = homedir4();
1179
- const os = platform2();
1180
- const p = os === "darwin" ? join5(home, "Library", "Application Support", "Cursor", "User", "globalStorage", "state.vscdb") : os === "win32" ? join5(process.env.APPDATA ?? join5(home, "AppData", "Roaming"), "Cursor", "User", "globalStorage", "state.vscdb") : join5(process.env.XDG_CONFIG_HOME ?? join5(home, ".config"), "Cursor", "User", "globalStorage", "state.vscdb");
1181
- return existsSync3(p) ? p : null;
1182
- }
1183
- function readCursorToken(db) {
1184
- const require3 = createRequire2(import.meta.url);
1185
- try {
1186
- const { DatabaseSync } = require3("node:sqlite");
1187
- const d = new DatabaseSync(db, { readOnly: true });
1188
- const row = d.prepare("SELECT value FROM ItemTable WHERE key = ?").get("cursorAuth/accessToken");
1189
- d.close();
1190
- if (row?.value) return String(row.value);
1191
- } catch {
1132
+ static assert(value) {
1133
+ if (!(value instanceof _ZodError)) {
1134
+ throw new Error(`Not a ZodError: ${value}`);
1135
+ }
1192
1136
  }
1193
- try {
1194
- const res = spawnSync3(
1195
- "sqlite3",
1196
- [db, "SELECT value FROM ItemTable WHERE key='cursorAuth/accessToken';"],
1197
- { encoding: "utf8", timeout: 1e4 }
1198
- );
1199
- const out = res.stdout?.trim();
1200
- if (res.status === 0 && out) return out;
1201
- } catch {
1137
+ toString() {
1138
+ return this.message;
1202
1139
  }
1203
- return null;
1204
- }
1205
- function cursorCookie(token) {
1206
- try {
1207
- const part = token.split(".")[1];
1208
- if (!part) return null;
1209
- const json = JSON.parse(
1210
- Buffer.from(part, "base64url").toString("utf8")
1211
- );
1212
- if (!json.sub) return null;
1213
- return `WorkosCursorSessionToken=${json.sub}%3A%3A${token}`;
1214
- } catch {
1215
- return null;
1140
+ get message() {
1141
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
1216
1142
  }
1217
- }
1218
- function num2(n) {
1219
- const v = Math.round(Number(n));
1220
- return Number.isFinite(v) && v > 0 ? v : 0;
1221
- }
1222
- function mapCursorEvents(events) {
1223
- const byDay = /* @__PURE__ */ new Map();
1224
- const byHour = /* @__PURE__ */ new Map();
1225
- for (const e of events) {
1226
- const tu = e.tokenUsage;
1227
- const ms = Number(e.timestamp);
1228
- if (!tu || !Number.isFinite(ms)) continue;
1229
- const d = new Date(ms);
1230
- const date = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
1231
- const model = e.model || "cursor";
1232
- const input = num2(tu.inputTokens);
1233
- const output = num2(tu.outputTokens);
1234
- const cacheWrite = num2(tu.cacheWriteTokens);
1235
- const cacheRead = num2(tu.cacheReadTokens);
1236
- const cost = Math.max(0, (Number(tu.totalCents) || 0) / 100);
1237
- const total = input + output + cacheWrite + cacheRead;
1238
- if (total === 0 && cost === 0) continue;
1239
- const key = `${date}|${model}`;
1240
- const day = byDay.get(key) ?? {
1241
- date,
1242
- tool: "cursor",
1243
- model,
1244
- inputTokens: 0,
1245
- outputTokens: 0,
1246
- cacheCreationTokens: 0,
1247
- cacheReadTokens: 0,
1248
- costUSD: 0,
1249
- origin: "cli",
1250
- verified: false
1251
- };
1252
- day.inputTokens += input;
1253
- day.outputTokens += output;
1254
- day.cacheCreationTokens += cacheWrite;
1255
- day.cacheReadTokens += cacheRead;
1256
- day.costUSD += cost;
1257
- byDay.set(key, day);
1258
- const hour = new Date(
1259
- Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours())
1260
- ).toISOString();
1261
- const blk = byHour.get(hour) ?? { startTime: hour, totalTokens: 0, costUSD: 0 };
1262
- blk.totalTokens += total;
1263
- blk.costUSD += cost;
1264
- byHour.set(hour, blk);
1143
+ get isEmpty() {
1144
+ return this.issues.length === 0;
1265
1145
  }
1266
- const entries = [...byDay.values()].map((e) => ({
1267
- ...e,
1268
- costUSD: Number(e.costUSD.toFixed(4))
1269
- }));
1270
- const blocks = [...byHour.values()].map((b) => ({
1271
- ...b,
1272
- costUSD: Number(b.costUSD.toFixed(4))
1273
- }));
1274
- return { entries, blocks };
1275
- }
1276
- async function fetchCursorEvents(cookie, maxPages = 30, pageSize = 500) {
1277
- const all = [];
1278
- for (let page = 1; page <= maxPages; page++) {
1279
- const res = await fetch(EVENTS_URL, {
1280
- method: "POST",
1281
- headers: {
1282
- "Content-Type": "application/json",
1283
- Origin: "https://cursor.com",
1284
- Cookie: cookie
1285
- },
1286
- body: JSON.stringify({ page, pageSize }),
1287
- signal: AbortSignal.timeout(2e4)
1288
- });
1289
- if (!res.ok) {
1290
- throw new Error(`cursor usage page ${page} failed (HTTP ${res.status})`);
1146
+ flatten(mapper = (issue) => issue.message) {
1147
+ const fieldErrors = {};
1148
+ const formErrors = [];
1149
+ for (const sub of this.issues) {
1150
+ if (sub.path.length > 0) {
1151
+ const firstEl = sub.path[0];
1152
+ fieldErrors[firstEl] = fieldErrors[firstEl] || [];
1153
+ fieldErrors[firstEl].push(mapper(sub));
1154
+ } else {
1155
+ formErrors.push(mapper(sub));
1156
+ }
1291
1157
  }
1292
- const body = await res.json();
1293
- const batch = body.usageEventsDisplay ?? [];
1294
- all.push(...batch);
1295
- if (batch.length < pageSize) break;
1158
+ return { formErrors, fieldErrors };
1296
1159
  }
1297
- return all;
1298
- }
1299
- async function collectCursor() {
1300
- try {
1301
- const db = cursorDbPath();
1302
- const token = db ? readCursorToken(db) : null;
1303
- const cookie = token ? cursorCookie(token) : null;
1304
- if (cookie) {
1305
- const events = await fetchCursorEvents(cookie);
1306
- const { entries, blocks } = mapCursorEvents(events);
1307
- if (entries.length > 0) return { entries, blocks, found: true };
1308
- }
1309
- } catch {
1160
+ get formErrors() {
1161
+ return this.flatten();
1310
1162
  }
1311
- try {
1312
- const entries = collectCursorViaTokscale();
1313
- if (entries.length > 0) return { entries, blocks: [], found: true };
1314
- } catch {
1163
+ };
1164
+ ZodError.create = (issues) => {
1165
+ const error = new ZodError(issues);
1166
+ return error;
1167
+ };
1168
+
1169
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js
1170
+ var errorMap = (issue, _ctx) => {
1171
+ let message;
1172
+ switch (issue.code) {
1173
+ case ZodIssueCode.invalid_type:
1174
+ if (issue.received === ZodParsedType.undefined) {
1175
+ message = "Required";
1176
+ } else {
1177
+ message = `Expected ${issue.expected}, received ${issue.received}`;
1178
+ }
1179
+ break;
1180
+ case ZodIssueCode.invalid_literal:
1181
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
1182
+ break;
1183
+ case ZodIssueCode.unrecognized_keys:
1184
+ message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
1185
+ break;
1186
+ case ZodIssueCode.invalid_union:
1187
+ message = `Invalid input`;
1188
+ break;
1189
+ case ZodIssueCode.invalid_union_discriminator:
1190
+ message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
1191
+ break;
1192
+ case ZodIssueCode.invalid_enum_value:
1193
+ message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
1194
+ break;
1195
+ case ZodIssueCode.invalid_arguments:
1196
+ message = `Invalid function arguments`;
1197
+ break;
1198
+ case ZodIssueCode.invalid_return_type:
1199
+ message = `Invalid function return type`;
1200
+ break;
1201
+ case ZodIssueCode.invalid_date:
1202
+ message = `Invalid date`;
1203
+ break;
1204
+ case ZodIssueCode.invalid_string:
1205
+ if (typeof issue.validation === "object") {
1206
+ if ("includes" in issue.validation) {
1207
+ message = `Invalid input: must include "${issue.validation.includes}"`;
1208
+ if (typeof issue.validation.position === "number") {
1209
+ message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
1210
+ }
1211
+ } else if ("startsWith" in issue.validation) {
1212
+ message = `Invalid input: must start with "${issue.validation.startsWith}"`;
1213
+ } else if ("endsWith" in issue.validation) {
1214
+ message = `Invalid input: must end with "${issue.validation.endsWith}"`;
1215
+ } else {
1216
+ util.assertNever(issue.validation);
1217
+ }
1218
+ } else if (issue.validation !== "regex") {
1219
+ message = `Invalid ${issue.validation}`;
1220
+ } else {
1221
+ message = "Invalid";
1222
+ }
1223
+ break;
1224
+ case ZodIssueCode.too_small:
1225
+ if (issue.type === "array")
1226
+ message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
1227
+ else if (issue.type === "string")
1228
+ message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
1229
+ else if (issue.type === "number")
1230
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
1231
+ else if (issue.type === "bigint")
1232
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
1233
+ else if (issue.type === "date")
1234
+ message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
1235
+ else
1236
+ message = "Invalid input";
1237
+ break;
1238
+ case ZodIssueCode.too_big:
1239
+ if (issue.type === "array")
1240
+ message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
1241
+ else if (issue.type === "string")
1242
+ message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
1243
+ else if (issue.type === "number")
1244
+ message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
1245
+ else if (issue.type === "bigint")
1246
+ message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
1247
+ else if (issue.type === "date")
1248
+ message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
1249
+ else
1250
+ message = "Invalid input";
1251
+ break;
1252
+ case ZodIssueCode.custom:
1253
+ message = `Invalid input`;
1254
+ break;
1255
+ case ZodIssueCode.invalid_intersection_types:
1256
+ message = `Intersection results could not be merged`;
1257
+ break;
1258
+ case ZodIssueCode.not_multiple_of:
1259
+ message = `Number must be a multiple of ${issue.multipleOf}`;
1260
+ break;
1261
+ case ZodIssueCode.not_finite:
1262
+ message = "Number must be finite";
1263
+ break;
1264
+ default:
1265
+ message = _ctx.defaultError;
1266
+ util.assertNever(issue);
1315
1267
  }
1316
- return { entries: [], blocks: [], found: false };
1268
+ return { message };
1269
+ };
1270
+ var en_default = errorMap;
1271
+
1272
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js
1273
+ var overrideErrorMap = en_default;
1274
+ function setErrorMap(map) {
1275
+ overrideErrorMap = map;
1276
+ }
1277
+ function getErrorMap() {
1278
+ return overrideErrorMap;
1317
1279
  }
1318
1280
 
1319
- // src/native/claude.ts
1320
- import { readdir, readFile as readFile2 } from "node:fs/promises";
1321
- import { homedir as homedir5 } from "node:os";
1322
- import { join as join7 } from "node:path";
1281
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js
1282
+ var makeIssue = (params) => {
1283
+ const { data, path, errorMaps, issueData } = params;
1284
+ const fullPath = [...path, ...issueData.path || []];
1285
+ const fullIssue = {
1286
+ ...issueData,
1287
+ path: fullPath
1288
+ };
1289
+ if (issueData.message !== void 0) {
1290
+ return {
1291
+ ...issueData,
1292
+ path: fullPath,
1293
+ message: issueData.message
1294
+ };
1295
+ }
1296
+ let errorMessage = "";
1297
+ const maps = errorMaps.filter((m) => !!m).slice().reverse();
1298
+ for (const map of maps) {
1299
+ errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
1300
+ }
1301
+ return {
1302
+ ...issueData,
1303
+ path: fullPath,
1304
+ message: errorMessage
1305
+ };
1306
+ };
1307
+ var EMPTY_PATH = [];
1308
+ function addIssueToContext(ctx, issueData) {
1309
+ const overrideMap = getErrorMap();
1310
+ const issue = makeIssue({
1311
+ issueData,
1312
+ data: ctx.data,
1313
+ path: ctx.path,
1314
+ errorMaps: [
1315
+ ctx.common.contextualErrorMap,
1316
+ // contextual error map is first priority
1317
+ ctx.schemaErrorMap,
1318
+ // then schema-bound map if available
1319
+ overrideMap,
1320
+ // then global override map
1321
+ overrideMap === en_default ? void 0 : en_default
1322
+ // then global default map
1323
+ ].filter((x) => !!x)
1324
+ });
1325
+ ctx.common.issues.push(issue);
1326
+ }
1327
+ var ParseStatus = class _ParseStatus {
1328
+ constructor() {
1329
+ this.value = "valid";
1330
+ }
1331
+ dirty() {
1332
+ if (this.value === "valid")
1333
+ this.value = "dirty";
1334
+ }
1335
+ abort() {
1336
+ if (this.value !== "aborted")
1337
+ this.value = "aborted";
1338
+ }
1339
+ static mergeArray(status, results) {
1340
+ const arrayValue = [];
1341
+ for (const s of results) {
1342
+ if (s.status === "aborted")
1343
+ return INVALID;
1344
+ if (s.status === "dirty")
1345
+ status.dirty();
1346
+ arrayValue.push(s.value);
1347
+ }
1348
+ return { status: status.value, value: arrayValue };
1349
+ }
1350
+ static async mergeObjectAsync(status, pairs) {
1351
+ const syncPairs = [];
1352
+ for (const pair of pairs) {
1353
+ const key = await pair.key;
1354
+ const value = await pair.value;
1355
+ syncPairs.push({
1356
+ key,
1357
+ value
1358
+ });
1359
+ }
1360
+ return _ParseStatus.mergeObjectSync(status, syncPairs);
1361
+ }
1362
+ static mergeObjectSync(status, pairs) {
1363
+ const finalObject = {};
1364
+ for (const pair of pairs) {
1365
+ const { key, value } = pair;
1366
+ if (key.status === "aborted")
1367
+ return INVALID;
1368
+ if (value.status === "aborted")
1369
+ return INVALID;
1370
+ if (key.status === "dirty")
1371
+ status.dirty();
1372
+ if (value.status === "dirty")
1373
+ status.dirty();
1374
+ if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
1375
+ finalObject[key.value] = value.value;
1376
+ }
1377
+ }
1378
+ return { status: status.value, value: finalObject };
1379
+ }
1380
+ };
1381
+ var INVALID = Object.freeze({
1382
+ status: "aborted"
1383
+ });
1384
+ var DIRTY = (value) => ({ status: "dirty", value });
1385
+ var OK = (value) => ({ status: "valid", value });
1386
+ var isAborted = (x) => x.status === "aborted";
1387
+ var isDirty = (x) => x.status === "dirty";
1388
+ var isValid = (x) => x.status === "valid";
1389
+ var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
1323
1390
 
1324
- // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js
1325
- var external_exports = {};
1326
- __export(external_exports, {
1327
- BRAND: () => BRAND,
1328
- DIRTY: () => DIRTY,
1329
- EMPTY_PATH: () => EMPTY_PATH,
1330
- INVALID: () => INVALID,
1331
- NEVER: () => NEVER,
1332
- OK: () => OK,
1333
- ParseStatus: () => ParseStatus,
1334
- Schema: () => ZodType,
1335
- ZodAny: () => ZodAny,
1336
- ZodArray: () => ZodArray,
1337
- ZodBigInt: () => ZodBigInt,
1338
- ZodBoolean: () => ZodBoolean,
1339
- ZodBranded: () => ZodBranded,
1340
- ZodCatch: () => ZodCatch,
1341
- ZodDate: () => ZodDate,
1342
- ZodDefault: () => ZodDefault,
1343
- ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
1344
- ZodEffects: () => ZodEffects,
1345
- ZodEnum: () => ZodEnum,
1346
- ZodError: () => ZodError,
1347
- ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
1348
- ZodFunction: () => ZodFunction,
1349
- ZodIntersection: () => ZodIntersection,
1350
- ZodIssueCode: () => ZodIssueCode,
1351
- ZodLazy: () => ZodLazy,
1352
- ZodLiteral: () => ZodLiteral,
1353
- ZodMap: () => ZodMap,
1354
- ZodNaN: () => ZodNaN,
1355
- ZodNativeEnum: () => ZodNativeEnum,
1356
- ZodNever: () => ZodNever,
1357
- ZodNull: () => ZodNull,
1358
- ZodNullable: () => ZodNullable,
1359
- ZodNumber: () => ZodNumber,
1360
- ZodObject: () => ZodObject,
1361
- ZodOptional: () => ZodOptional,
1362
- ZodParsedType: () => ZodParsedType,
1363
- ZodPipeline: () => ZodPipeline,
1364
- ZodPromise: () => ZodPromise,
1365
- ZodReadonly: () => ZodReadonly,
1366
- ZodRecord: () => ZodRecord,
1367
- ZodSchema: () => ZodType,
1368
- ZodSet: () => ZodSet,
1369
- ZodString: () => ZodString,
1370
- ZodSymbol: () => ZodSymbol,
1371
- ZodTransformer: () => ZodEffects,
1372
- ZodTuple: () => ZodTuple,
1373
- ZodType: () => ZodType,
1374
- ZodUndefined: () => ZodUndefined,
1375
- ZodUnion: () => ZodUnion,
1376
- ZodUnknown: () => ZodUnknown,
1377
- ZodVoid: () => ZodVoid,
1378
- addIssueToContext: () => addIssueToContext,
1379
- any: () => anyType,
1380
- array: () => arrayType,
1381
- bigint: () => bigIntType,
1382
- boolean: () => booleanType,
1383
- coerce: () => coerce,
1384
- custom: () => custom,
1385
- date: () => dateType,
1386
- datetimeRegex: () => datetimeRegex,
1387
- defaultErrorMap: () => en_default,
1388
- discriminatedUnion: () => discriminatedUnionType,
1389
- effect: () => effectsType,
1390
- enum: () => enumType,
1391
- function: () => functionType,
1392
- getErrorMap: () => getErrorMap,
1393
- getParsedType: () => getParsedType,
1394
- instanceof: () => instanceOfType,
1395
- intersection: () => intersectionType,
1396
- isAborted: () => isAborted,
1397
- isAsync: () => isAsync,
1398
- isDirty: () => isDirty,
1399
- isValid: () => isValid,
1400
- late: () => late,
1401
- lazy: () => lazyType,
1402
- literal: () => literalType,
1403
- makeIssue: () => makeIssue,
1404
- map: () => mapType,
1405
- nan: () => nanType,
1406
- nativeEnum: () => nativeEnumType,
1407
- never: () => neverType,
1408
- null: () => nullType,
1409
- nullable: () => nullableType,
1410
- number: () => numberType,
1411
- object: () => objectType,
1412
- objectUtil: () => objectUtil,
1413
- oboolean: () => oboolean,
1414
- onumber: () => onumber,
1415
- optional: () => optionalType,
1416
- ostring: () => ostring,
1417
- pipeline: () => pipelineType,
1418
- preprocess: () => preprocessType,
1419
- promise: () => promiseType,
1420
- quotelessJson: () => quotelessJson,
1421
- record: () => recordType,
1422
- set: () => setType,
1423
- setErrorMap: () => setErrorMap,
1424
- strictObject: () => strictObjectType,
1425
- string: () => stringType,
1426
- symbol: () => symbolType,
1427
- transformer: () => effectsType,
1428
- tuple: () => tupleType,
1429
- undefined: () => undefinedType,
1430
- union: () => unionType,
1431
- unknown: () => unknownType,
1432
- util: () => util,
1433
- void: () => voidType
1434
- });
1391
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js
1392
+ var errorUtil;
1393
+ (function(errorUtil2) {
1394
+ errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
1395
+ errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
1396
+ })(errorUtil || (errorUtil = {}));
1435
1397
 
1436
- // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js
1437
- var util;
1438
- (function(util2) {
1439
- util2.assertEqual = (_) => {
1440
- };
1441
- function assertIs(_arg) {
1442
- }
1443
- util2.assertIs = assertIs;
1444
- function assertNever(_x) {
1445
- throw new Error();
1398
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js
1399
+ var ParseInputLazyPath = class {
1400
+ constructor(parent, value, path, key) {
1401
+ this._cachedPath = [];
1402
+ this.parent = parent;
1403
+ this.data = value;
1404
+ this._path = path;
1405
+ this._key = key;
1446
1406
  }
1447
- util2.assertNever = assertNever;
1448
- util2.arrayToEnum = (items) => {
1449
- const obj = {};
1450
- for (const item of items) {
1451
- obj[item] = item;
1407
+ get path() {
1408
+ if (!this._cachedPath.length) {
1409
+ if (Array.isArray(this._key)) {
1410
+ this._cachedPath.push(...this._path, ...this._key);
1411
+ } else {
1412
+ this._cachedPath.push(...this._path, this._key);
1413
+ }
1452
1414
  }
1453
- return obj;
1454
- };
1455
- util2.getValidEnumValues = (obj) => {
1456
- const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
1457
- const filtered = {};
1458
- for (const k of validKeys) {
1459
- filtered[k] = obj[k];
1415
+ return this._cachedPath;
1416
+ }
1417
+ };
1418
+ var handleResult = (ctx, result) => {
1419
+ if (isValid(result)) {
1420
+ return { success: true, data: result.value };
1421
+ } else {
1422
+ if (!ctx.common.issues.length) {
1423
+ throw new Error("Validation failed but no issues detected.");
1460
1424
  }
1461
- return util2.objectValues(filtered);
1462
- };
1463
- util2.objectValues = (obj) => {
1464
- return util2.objectKeys(obj).map(function(e) {
1465
- return obj[e];
1466
- });
1467
- };
1468
- util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
1469
- const keys = [];
1470
- for (const key in object) {
1471
- if (Object.prototype.hasOwnProperty.call(object, key)) {
1472
- keys.push(key);
1425
+ return {
1426
+ success: false,
1427
+ get error() {
1428
+ if (this._error)
1429
+ return this._error;
1430
+ const error = new ZodError(ctx.common.issues);
1431
+ this._error = error;
1432
+ return this._error;
1473
1433
  }
1434
+ };
1435
+ }
1436
+ };
1437
+ function processCreateParams(params) {
1438
+ if (!params)
1439
+ return {};
1440
+ const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
1441
+ if (errorMap2 && (invalid_type_error || required_error)) {
1442
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
1443
+ }
1444
+ if (errorMap2)
1445
+ return { errorMap: errorMap2, description };
1446
+ const customMap = (iss, ctx) => {
1447
+ const { message } = params;
1448
+ if (iss.code === "invalid_enum_value") {
1449
+ return { message: message ?? ctx.defaultError };
1474
1450
  }
1475
- return keys;
1476
- };
1477
- util2.find = (arr, checker) => {
1478
- for (const item of arr) {
1479
- if (checker(item))
1480
- return item;
1451
+ if (typeof ctx.data === "undefined") {
1452
+ return { message: message ?? required_error ?? ctx.defaultError };
1481
1453
  }
1482
- return void 0;
1454
+ if (iss.code !== "invalid_type")
1455
+ return { message: ctx.defaultError };
1456
+ return { message: message ?? invalid_type_error ?? ctx.defaultError };
1483
1457
  };
1484
- util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
1485
- function joinValues(array, separator = " | ") {
1486
- return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
1458
+ return { errorMap: customMap, description };
1459
+ }
1460
+ var ZodType = class {
1461
+ get description() {
1462
+ return this._def.description;
1487
1463
  }
1488
- util2.joinValues = joinValues;
1489
- util2.jsonStringifyReplacer = (_, value) => {
1490
- if (typeof value === "bigint") {
1491
- return value.toString();
1492
- }
1493
- return value;
1494
- };
1495
- })(util || (util = {}));
1496
- var objectUtil;
1497
- (function(objectUtil2) {
1498
- objectUtil2.mergeShapes = (first, second) => {
1464
+ _getType(input) {
1465
+ return getParsedType(input.data);
1466
+ }
1467
+ _getOrReturnCtx(input, ctx) {
1468
+ return ctx || {
1469
+ common: input.parent.common,
1470
+ data: input.data,
1471
+ parsedType: getParsedType(input.data),
1472
+ schemaErrorMap: this._def.errorMap,
1473
+ path: input.path,
1474
+ parent: input.parent
1475
+ };
1476
+ }
1477
+ _processInputParams(input) {
1499
1478
  return {
1500
- ...first,
1501
- ...second
1502
- // second overwrites first
1479
+ status: new ParseStatus(),
1480
+ ctx: {
1481
+ common: input.parent.common,
1482
+ data: input.data,
1483
+ parsedType: getParsedType(input.data),
1484
+ schemaErrorMap: this._def.errorMap,
1485
+ path: input.path,
1486
+ parent: input.parent
1487
+ }
1503
1488
  };
1504
- };
1505
- })(objectUtil || (objectUtil = {}));
1506
- var ZodParsedType = util.arrayToEnum([
1507
- "string",
1508
- "nan",
1509
- "number",
1510
- "integer",
1511
- "float",
1512
- "boolean",
1513
- "date",
1514
- "bigint",
1515
- "symbol",
1516
- "function",
1517
- "undefined",
1518
- "null",
1519
- "array",
1520
- "object",
1521
- "unknown",
1522
- "promise",
1523
- "void",
1524
- "never",
1525
- "map",
1526
- "set"
1527
- ]);
1528
- var getParsedType = (data) => {
1529
- const t = typeof data;
1530
- switch (t) {
1531
- case "undefined":
1532
- return ZodParsedType.undefined;
1533
- case "string":
1534
- return ZodParsedType.string;
1535
- case "number":
1536
- return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
1537
- case "boolean":
1538
- return ZodParsedType.boolean;
1539
- case "function":
1540
- return ZodParsedType.function;
1541
- case "bigint":
1542
- return ZodParsedType.bigint;
1543
- case "symbol":
1544
- return ZodParsedType.symbol;
1545
- case "object":
1546
- if (Array.isArray(data)) {
1547
- return ZodParsedType.array;
1548
- }
1549
- if (data === null) {
1550
- return ZodParsedType.null;
1551
- }
1552
- if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
1553
- return ZodParsedType.promise;
1554
- }
1555
- if (typeof Map !== "undefined" && data instanceof Map) {
1556
- return ZodParsedType.map;
1557
- }
1558
- if (typeof Set !== "undefined" && data instanceof Set) {
1559
- return ZodParsedType.set;
1560
- }
1561
- if (typeof Date !== "undefined" && data instanceof Date) {
1562
- return ZodParsedType.date;
1563
- }
1564
- return ZodParsedType.object;
1565
- default:
1566
- return ZodParsedType.unknown;
1567
1489
  }
1568
- };
1569
-
1570
- // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js
1571
- var ZodIssueCode = util.arrayToEnum([
1572
- "invalid_type",
1573
- "invalid_literal",
1574
- "custom",
1575
- "invalid_union",
1576
- "invalid_union_discriminator",
1577
- "invalid_enum_value",
1578
- "unrecognized_keys",
1579
- "invalid_arguments",
1580
- "invalid_return_type",
1581
- "invalid_date",
1582
- "invalid_string",
1583
- "too_small",
1584
- "too_big",
1585
- "invalid_intersection_types",
1586
- "not_multiple_of",
1587
- "not_finite"
1588
- ]);
1589
- var quotelessJson = (obj) => {
1590
- const json = JSON.stringify(obj, null, 2);
1591
- return json.replace(/"([^"]+)":/g, "$1:");
1592
- };
1593
- var ZodError = class _ZodError extends Error {
1594
- get errors() {
1595
- return this.issues;
1490
+ _parseSync(input) {
1491
+ const result = this._parse(input);
1492
+ if (isAsync(result)) {
1493
+ throw new Error("Synchronous parse encountered promise.");
1494
+ }
1495
+ return result;
1596
1496
  }
1597
- constructor(issues) {
1598
- super();
1599
- this.issues = [];
1600
- this.addIssue = (sub) => {
1601
- this.issues = [...this.issues, sub];
1602
- };
1603
- this.addIssues = (subs = []) => {
1604
- this.issues = [...this.issues, ...subs];
1497
+ _parseAsync(input) {
1498
+ const result = this._parse(input);
1499
+ return Promise.resolve(result);
1500
+ }
1501
+ parse(data, params) {
1502
+ const result = this.safeParse(data, params);
1503
+ if (result.success)
1504
+ return result.data;
1505
+ throw result.error;
1506
+ }
1507
+ safeParse(data, params) {
1508
+ const ctx = {
1509
+ common: {
1510
+ issues: [],
1511
+ async: params?.async ?? false,
1512
+ contextualErrorMap: params?.errorMap
1513
+ },
1514
+ path: params?.path || [],
1515
+ schemaErrorMap: this._def.errorMap,
1516
+ parent: null,
1517
+ data,
1518
+ parsedType: getParsedType(data)
1605
1519
  };
1606
- const actualProto = new.target.prototype;
1607
- if (Object.setPrototypeOf) {
1608
- Object.setPrototypeOf(this, actualProto);
1609
- } else {
1610
- this.__proto__ = actualProto;
1611
- }
1612
- this.name = "ZodError";
1613
- this.issues = issues;
1520
+ const result = this._parseSync({ data, path: ctx.path, parent: ctx });
1521
+ return handleResult(ctx, result);
1614
1522
  }
1615
- format(_mapper) {
1616
- const mapper = _mapper || function(issue) {
1617
- return issue.message;
1523
+ "~validate"(data) {
1524
+ const ctx = {
1525
+ common: {
1526
+ issues: [],
1527
+ async: !!this["~standard"].async
1528
+ },
1529
+ path: [],
1530
+ schemaErrorMap: this._def.errorMap,
1531
+ parent: null,
1532
+ data,
1533
+ parsedType: getParsedType(data)
1618
1534
  };
1619
- const fieldErrors = { _errors: [] };
1620
- const processError = (error) => {
1621
- for (const issue of error.issues) {
1622
- if (issue.code === "invalid_union") {
1623
- issue.unionErrors.map(processError);
1624
- } else if (issue.code === "invalid_return_type") {
1625
- processError(issue.returnTypeError);
1626
- } else if (issue.code === "invalid_arguments") {
1627
- processError(issue.argumentsError);
1628
- } else if (issue.path.length === 0) {
1629
- fieldErrors._errors.push(mapper(issue));
1630
- } else {
1631
- let curr = fieldErrors;
1632
- let i = 0;
1633
- while (i < issue.path.length) {
1634
- const el = issue.path[i];
1635
- const terminal = i === issue.path.length - 1;
1636
- if (!terminal) {
1637
- curr[el] = curr[el] || { _errors: [] };
1638
- } else {
1639
- curr[el] = curr[el] || { _errors: [] };
1640
- curr[el]._errors.push(mapper(issue));
1641
- }
1642
- curr = curr[el];
1643
- i++;
1644
- }
1535
+ if (!this["~standard"].async) {
1536
+ try {
1537
+ const result = this._parseSync({ data, path: [], parent: ctx });
1538
+ return isValid(result) ? {
1539
+ value: result.value
1540
+ } : {
1541
+ issues: ctx.common.issues
1542
+ };
1543
+ } catch (err) {
1544
+ if (err?.message?.toLowerCase()?.includes("encountered")) {
1545
+ this["~standard"].async = true;
1645
1546
  }
1547
+ ctx.common = {
1548
+ issues: [],
1549
+ async: true
1550
+ };
1646
1551
  }
1647
- };
1648
- processError(this);
1649
- return fieldErrors;
1650
- }
1651
- static assert(value) {
1652
- if (!(value instanceof _ZodError)) {
1653
- throw new Error(`Not a ZodError: ${value}`);
1654
1552
  }
1553
+ return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
1554
+ value: result.value
1555
+ } : {
1556
+ issues: ctx.common.issues
1557
+ });
1655
1558
  }
1656
- toString() {
1657
- return this.message;
1658
- }
1659
- get message() {
1660
- return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
1559
+ async parseAsync(data, params) {
1560
+ const result = await this.safeParseAsync(data, params);
1561
+ if (result.success)
1562
+ return result.data;
1563
+ throw result.error;
1661
1564
  }
1662
- get isEmpty() {
1663
- return this.issues.length === 0;
1565
+ async safeParseAsync(data, params) {
1566
+ const ctx = {
1567
+ common: {
1568
+ issues: [],
1569
+ contextualErrorMap: params?.errorMap,
1570
+ async: true
1571
+ },
1572
+ path: params?.path || [],
1573
+ schemaErrorMap: this._def.errorMap,
1574
+ parent: null,
1575
+ data,
1576
+ parsedType: getParsedType(data)
1577
+ };
1578
+ const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
1579
+ const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
1580
+ return handleResult(ctx, result);
1664
1581
  }
1665
- flatten(mapper = (issue) => issue.message) {
1666
- const fieldErrors = {};
1667
- const formErrors = [];
1668
- for (const sub of this.issues) {
1669
- if (sub.path.length > 0) {
1670
- const firstEl = sub.path[0];
1671
- fieldErrors[firstEl] = fieldErrors[firstEl] || [];
1672
- fieldErrors[firstEl].push(mapper(sub));
1582
+ refine(check, message) {
1583
+ const getIssueProperties = (val) => {
1584
+ if (typeof message === "string" || typeof message === "undefined") {
1585
+ return { message };
1586
+ } else if (typeof message === "function") {
1587
+ return message(val);
1673
1588
  } else {
1674
- formErrors.push(mapper(sub));
1589
+ return message;
1675
1590
  }
1676
- }
1677
- return { formErrors, fieldErrors };
1678
- }
1679
- get formErrors() {
1680
- return this.flatten();
1681
- }
1682
- };
1683
- ZodError.create = (issues) => {
1684
- const error = new ZodError(issues);
1685
- return error;
1686
- };
1687
-
1688
- // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js
1689
- var errorMap = (issue, _ctx) => {
1690
- let message;
1691
- switch (issue.code) {
1692
- case ZodIssueCode.invalid_type:
1693
- if (issue.received === ZodParsedType.undefined) {
1694
- message = "Required";
1591
+ };
1592
+ return this._refinement((val, ctx) => {
1593
+ const result = check(val);
1594
+ const setError = () => ctx.addIssue({
1595
+ code: ZodIssueCode.custom,
1596
+ ...getIssueProperties(val)
1597
+ });
1598
+ if (typeof Promise !== "undefined" && result instanceof Promise) {
1599
+ return result.then((data) => {
1600
+ if (!data) {
1601
+ setError();
1602
+ return false;
1603
+ } else {
1604
+ return true;
1605
+ }
1606
+ });
1607
+ }
1608
+ if (!result) {
1609
+ setError();
1610
+ return false;
1695
1611
  } else {
1696
- message = `Expected ${issue.expected}, received ${issue.received}`;
1612
+ return true;
1697
1613
  }
1698
- break;
1699
- case ZodIssueCode.invalid_literal:
1700
- message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
1701
- break;
1702
- case ZodIssueCode.unrecognized_keys:
1703
- message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
1704
- break;
1705
- case ZodIssueCode.invalid_union:
1706
- message = `Invalid input`;
1707
- break;
1708
- case ZodIssueCode.invalid_union_discriminator:
1709
- message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
1710
- break;
1711
- case ZodIssueCode.invalid_enum_value:
1712
- message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
1713
- break;
1714
- case ZodIssueCode.invalid_arguments:
1715
- message = `Invalid function arguments`;
1716
- break;
1717
- case ZodIssueCode.invalid_return_type:
1718
- message = `Invalid function return type`;
1719
- break;
1720
- case ZodIssueCode.invalid_date:
1721
- message = `Invalid date`;
1722
- break;
1723
- case ZodIssueCode.invalid_string:
1724
- if (typeof issue.validation === "object") {
1725
- if ("includes" in issue.validation) {
1726
- message = `Invalid input: must include "${issue.validation.includes}"`;
1727
- if (typeof issue.validation.position === "number") {
1728
- message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
1729
- }
1730
- } else if ("startsWith" in issue.validation) {
1731
- message = `Invalid input: must start with "${issue.validation.startsWith}"`;
1732
- } else if ("endsWith" in issue.validation) {
1733
- message = `Invalid input: must end with "${issue.validation.endsWith}"`;
1734
- } else {
1735
- util.assertNever(issue.validation);
1736
- }
1737
- } else if (issue.validation !== "regex") {
1738
- message = `Invalid ${issue.validation}`;
1614
+ });
1615
+ }
1616
+ refinement(check, refinementData) {
1617
+ return this._refinement((val, ctx) => {
1618
+ if (!check(val)) {
1619
+ ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
1620
+ return false;
1739
1621
  } else {
1740
- message = "Invalid";
1622
+ return true;
1741
1623
  }
1742
- break;
1743
- case ZodIssueCode.too_small:
1744
- if (issue.type === "array")
1745
- message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
1746
- else if (issue.type === "string")
1747
- message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
1748
- else if (issue.type === "number")
1749
- message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
1750
- else if (issue.type === "bigint")
1751
- message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
1752
- else if (issue.type === "date")
1753
- message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
1754
- else
1755
- message = "Invalid input";
1756
- break;
1757
- case ZodIssueCode.too_big:
1758
- if (issue.type === "array")
1759
- message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
1760
- else if (issue.type === "string")
1761
- message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
1762
- else if (issue.type === "number")
1763
- message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
1764
- else if (issue.type === "bigint")
1765
- message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
1766
- else if (issue.type === "date")
1767
- message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
1768
- else
1769
- message = "Invalid input";
1770
- break;
1771
- case ZodIssueCode.custom:
1772
- message = `Invalid input`;
1773
- break;
1774
- case ZodIssueCode.invalid_intersection_types:
1775
- message = `Intersection results could not be merged`;
1776
- break;
1777
- case ZodIssueCode.not_multiple_of:
1778
- message = `Number must be a multiple of ${issue.multipleOf}`;
1779
- break;
1780
- case ZodIssueCode.not_finite:
1781
- message = "Number must be finite";
1782
- break;
1783
- default:
1784
- message = _ctx.defaultError;
1785
- util.assertNever(issue);
1624
+ });
1786
1625
  }
1787
- return { message };
1788
- };
1789
- var en_default = errorMap;
1790
-
1791
- // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js
1792
- var overrideErrorMap = en_default;
1793
- function setErrorMap(map) {
1794
- overrideErrorMap = map;
1795
- }
1796
- function getErrorMap() {
1797
- return overrideErrorMap;
1798
- }
1799
-
1800
- // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js
1801
- var makeIssue = (params) => {
1802
- const { data, path, errorMaps, issueData } = params;
1803
- const fullPath = [...path, ...issueData.path || []];
1804
- const fullIssue = {
1805
- ...issueData,
1806
- path: fullPath
1807
- };
1808
- if (issueData.message !== void 0) {
1809
- return {
1810
- ...issueData,
1811
- path: fullPath,
1812
- message: issueData.message
1626
+ _refinement(refinement) {
1627
+ return new ZodEffects({
1628
+ schema: this,
1629
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
1630
+ effect: { type: "refinement", refinement }
1631
+ });
1632
+ }
1633
+ superRefine(refinement) {
1634
+ return this._refinement(refinement);
1635
+ }
1636
+ constructor(def) {
1637
+ this.spa = this.safeParseAsync;
1638
+ this._def = def;
1639
+ this.parse = this.parse.bind(this);
1640
+ this.safeParse = this.safeParse.bind(this);
1641
+ this.parseAsync = this.parseAsync.bind(this);
1642
+ this.safeParseAsync = this.safeParseAsync.bind(this);
1643
+ this.spa = this.spa.bind(this);
1644
+ this.refine = this.refine.bind(this);
1645
+ this.refinement = this.refinement.bind(this);
1646
+ this.superRefine = this.superRefine.bind(this);
1647
+ this.optional = this.optional.bind(this);
1648
+ this.nullable = this.nullable.bind(this);
1649
+ this.nullish = this.nullish.bind(this);
1650
+ this.array = this.array.bind(this);
1651
+ this.promise = this.promise.bind(this);
1652
+ this.or = this.or.bind(this);
1653
+ this.and = this.and.bind(this);
1654
+ this.transform = this.transform.bind(this);
1655
+ this.brand = this.brand.bind(this);
1656
+ this.default = this.default.bind(this);
1657
+ this.catch = this.catch.bind(this);
1658
+ this.describe = this.describe.bind(this);
1659
+ this.pipe = this.pipe.bind(this);
1660
+ this.readonly = this.readonly.bind(this);
1661
+ this.isNullable = this.isNullable.bind(this);
1662
+ this.isOptional = this.isOptional.bind(this);
1663
+ this["~standard"] = {
1664
+ version: 1,
1665
+ vendor: "zod",
1666
+ validate: (data) => this["~validate"](data)
1813
1667
  };
1814
1668
  }
1815
- let errorMessage = "";
1816
- const maps = errorMaps.filter((m) => !!m).slice().reverse();
1817
- for (const map of maps) {
1818
- errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
1669
+ optional() {
1670
+ return ZodOptional.create(this, this._def);
1819
1671
  }
1820
- return {
1821
- ...issueData,
1822
- path: fullPath,
1823
- message: errorMessage
1824
- };
1825
- };
1826
- var EMPTY_PATH = [];
1827
- function addIssueToContext(ctx, issueData) {
1828
- const overrideMap = getErrorMap();
1829
- const issue = makeIssue({
1830
- issueData,
1831
- data: ctx.data,
1832
- path: ctx.path,
1833
- errorMaps: [
1834
- ctx.common.contextualErrorMap,
1835
- // contextual error map is first priority
1836
- ctx.schemaErrorMap,
1837
- // then schema-bound map if available
1838
- overrideMap,
1839
- // then global override map
1840
- overrideMap === en_default ? void 0 : en_default
1841
- // then global default map
1842
- ].filter((x) => !!x)
1843
- });
1844
- ctx.common.issues.push(issue);
1845
- }
1846
- var ParseStatus = class _ParseStatus {
1847
- constructor() {
1848
- this.value = "valid";
1672
+ nullable() {
1673
+ return ZodNullable.create(this, this._def);
1849
1674
  }
1850
- dirty() {
1851
- if (this.value === "valid")
1852
- this.value = "dirty";
1675
+ nullish() {
1676
+ return this.nullable().optional();
1853
1677
  }
1854
- abort() {
1855
- if (this.value !== "aborted")
1856
- this.value = "aborted";
1678
+ array() {
1679
+ return ZodArray.create(this);
1857
1680
  }
1858
- static mergeArray(status, results) {
1859
- const arrayValue = [];
1860
- for (const s of results) {
1861
- if (s.status === "aborted")
1862
- return INVALID;
1863
- if (s.status === "dirty")
1864
- status.dirty();
1865
- arrayValue.push(s.value);
1866
- }
1867
- return { status: status.value, value: arrayValue };
1681
+ promise() {
1682
+ return ZodPromise.create(this, this._def);
1868
1683
  }
1869
- static async mergeObjectAsync(status, pairs) {
1870
- const syncPairs = [];
1871
- for (const pair of pairs) {
1872
- const key = await pair.key;
1873
- const value = await pair.value;
1874
- syncPairs.push({
1875
- key,
1876
- value
1877
- });
1878
- }
1879
- return _ParseStatus.mergeObjectSync(status, syncPairs);
1684
+ or(option) {
1685
+ return ZodUnion.create([this, option], this._def);
1880
1686
  }
1881
- static mergeObjectSync(status, pairs) {
1882
- const finalObject = {};
1883
- for (const pair of pairs) {
1884
- const { key, value } = pair;
1885
- if (key.status === "aborted")
1886
- return INVALID;
1887
- if (value.status === "aborted")
1888
- return INVALID;
1889
- if (key.status === "dirty")
1890
- status.dirty();
1891
- if (value.status === "dirty")
1892
- status.dirty();
1893
- if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
1894
- finalObject[key.value] = value.value;
1895
- }
1896
- }
1897
- return { status: status.value, value: finalObject };
1687
+ and(incoming) {
1688
+ return ZodIntersection.create(this, incoming, this._def);
1898
1689
  }
1899
- };
1900
- var INVALID = Object.freeze({
1901
- status: "aborted"
1902
- });
1903
- var DIRTY = (value) => ({ status: "dirty", value });
1904
- var OK = (value) => ({ status: "valid", value });
1905
- var isAborted = (x) => x.status === "aborted";
1906
- var isDirty = (x) => x.status === "dirty";
1907
- var isValid = (x) => x.status === "valid";
1908
- var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
1909
-
1910
- // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js
1911
- var errorUtil;
1912
- (function(errorUtil2) {
1913
- errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
1914
- errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
1915
- })(errorUtil || (errorUtil = {}));
1916
-
1917
- // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js
1918
- var ParseInputLazyPath = class {
1919
- constructor(parent, value, path, key) {
1920
- this._cachedPath = [];
1921
- this.parent = parent;
1922
- this.data = value;
1923
- this._path = path;
1924
- this._key = key;
1690
+ transform(transform) {
1691
+ return new ZodEffects({
1692
+ ...processCreateParams(this._def),
1693
+ schema: this,
1694
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
1695
+ effect: { type: "transform", transform }
1696
+ });
1925
1697
  }
1926
- get path() {
1927
- if (!this._cachedPath.length) {
1928
- if (Array.isArray(this._key)) {
1929
- this._cachedPath.push(...this._path, ...this._key);
1930
- } else {
1931
- this._cachedPath.push(...this._path, this._key);
1932
- }
1933
- }
1934
- return this._cachedPath;
1698
+ default(def) {
1699
+ const defaultValueFunc = typeof def === "function" ? def : () => def;
1700
+ return new ZodDefault({
1701
+ ...processCreateParams(this._def),
1702
+ innerType: this,
1703
+ defaultValue: defaultValueFunc,
1704
+ typeName: ZodFirstPartyTypeKind.ZodDefault
1705
+ });
1935
1706
  }
1936
- };
1937
- var handleResult = (ctx, result) => {
1938
- if (isValid(result)) {
1939
- return { success: true, data: result.value };
1940
- } else {
1941
- if (!ctx.common.issues.length) {
1942
- throw new Error("Validation failed but no issues detected.");
1943
- }
1944
- return {
1945
- success: false,
1946
- get error() {
1947
- if (this._error)
1948
- return this._error;
1949
- const error = new ZodError(ctx.common.issues);
1950
- this._error = error;
1951
- return this._error;
1952
- }
1953
- };
1707
+ brand() {
1708
+ return new ZodBranded({
1709
+ typeName: ZodFirstPartyTypeKind.ZodBranded,
1710
+ type: this,
1711
+ ...processCreateParams(this._def)
1712
+ });
1954
1713
  }
1955
- };
1956
- function processCreateParams(params) {
1957
- if (!params)
1958
- return {};
1959
- const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
1960
- if (errorMap2 && (invalid_type_error || required_error)) {
1961
- throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
1714
+ catch(def) {
1715
+ const catchValueFunc = typeof def === "function" ? def : () => def;
1716
+ return new ZodCatch({
1717
+ ...processCreateParams(this._def),
1718
+ innerType: this,
1719
+ catchValue: catchValueFunc,
1720
+ typeName: ZodFirstPartyTypeKind.ZodCatch
1721
+ });
1962
1722
  }
1963
- if (errorMap2)
1964
- return { errorMap: errorMap2, description };
1965
- const customMap = (iss, ctx) => {
1966
- const { message } = params;
1967
- if (iss.code === "invalid_enum_value") {
1968
- return { message: message ?? ctx.defaultError };
1969
- }
1970
- if (typeof ctx.data === "undefined") {
1971
- return { message: message ?? required_error ?? ctx.defaultError };
1972
- }
1973
- if (iss.code !== "invalid_type")
1974
- return { message: ctx.defaultError };
1975
- return { message: message ?? invalid_type_error ?? ctx.defaultError };
1976
- };
1977
- return { errorMap: customMap, description };
1978
- }
1979
- var ZodType = class {
1980
- get description() {
1981
- return this._def.description;
1723
+ describe(description) {
1724
+ const This = this.constructor;
1725
+ return new This({
1726
+ ...this._def,
1727
+ description
1728
+ });
1982
1729
  }
1983
- _getType(input) {
1984
- return getParsedType(input.data);
1730
+ pipe(target) {
1731
+ return ZodPipeline.create(this, target);
1985
1732
  }
1986
- _getOrReturnCtx(input, ctx) {
1987
- return ctx || {
1988
- common: input.parent.common,
1989
- data: input.data,
1990
- parsedType: getParsedType(input.data),
1991
- schemaErrorMap: this._def.errorMap,
1992
- path: input.path,
1993
- parent: input.parent
1994
- };
1733
+ readonly() {
1734
+ return ZodReadonly.create(this);
1995
1735
  }
1996
- _processInputParams(input) {
1997
- return {
1998
- status: new ParseStatus(),
1999
- ctx: {
2000
- common: input.parent.common,
2001
- data: input.data,
2002
- parsedType: getParsedType(input.data),
2003
- schemaErrorMap: this._def.errorMap,
2004
- path: input.path,
2005
- parent: input.parent
2006
- }
2007
- };
1736
+ isOptional() {
1737
+ return this.safeParse(void 0).success;
2008
1738
  }
2009
- _parseSync(input) {
2010
- const result = this._parse(input);
2011
- if (isAsync(result)) {
2012
- throw new Error("Synchronous parse encountered promise.");
2013
- }
2014
- return result;
1739
+ isNullable() {
1740
+ return this.safeParse(null).success;
2015
1741
  }
2016
- _parseAsync(input) {
2017
- const result = this._parse(input);
2018
- return Promise.resolve(result);
1742
+ };
1743
+ var cuidRegex = /^c[^\s-]{8,}$/i;
1744
+ var cuid2Regex = /^[0-9a-z]+$/;
1745
+ var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
1746
+ var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
1747
+ var nanoidRegex = /^[a-z0-9_-]{21}$/i;
1748
+ var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
1749
+ var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
1750
+ var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
1751
+ var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
1752
+ var emojiRegex;
1753
+ var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
1754
+ var ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
1755
+ var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
1756
+ var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
1757
+ var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
1758
+ var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
1759
+ var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
1760
+ var dateRegex = new RegExp(`^${dateRegexSource}$`);
1761
+ function timeRegexSource(args) {
1762
+ let secondsRegexSource = `[0-5]\\d`;
1763
+ if (args.precision) {
1764
+ secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
1765
+ } else if (args.precision == null) {
1766
+ secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
2019
1767
  }
2020
- parse(data, params) {
2021
- const result = this.safeParse(data, params);
2022
- if (result.success)
2023
- return result.data;
2024
- throw result.error;
1768
+ const secondsQuantifier = args.precision ? "+" : "?";
1769
+ return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
1770
+ }
1771
+ function timeRegex(args) {
1772
+ return new RegExp(`^${timeRegexSource(args)}$`);
1773
+ }
1774
+ function datetimeRegex(args) {
1775
+ let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
1776
+ const opts = [];
1777
+ opts.push(args.local ? `Z?` : `Z`);
1778
+ if (args.offset)
1779
+ opts.push(`([+-]\\d{2}:?\\d{2})`);
1780
+ regex = `${regex}(${opts.join("|")})`;
1781
+ return new RegExp(`^${regex}$`);
1782
+ }
1783
+ function isValidIP(ip, version) {
1784
+ if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
1785
+ return true;
2025
1786
  }
2026
- safeParse(data, params) {
2027
- const ctx = {
2028
- common: {
2029
- issues: [],
2030
- async: params?.async ?? false,
2031
- contextualErrorMap: params?.errorMap
2032
- },
2033
- path: params?.path || [],
2034
- schemaErrorMap: this._def.errorMap,
2035
- parent: null,
2036
- data,
2037
- parsedType: getParsedType(data)
2038
- };
2039
- const result = this._parseSync({ data, path: ctx.path, parent: ctx });
2040
- return handleResult(ctx, result);
2041
- }
2042
- "~validate"(data) {
2043
- const ctx = {
2044
- common: {
2045
- issues: [],
2046
- async: !!this["~standard"].async
2047
- },
2048
- path: [],
2049
- schemaErrorMap: this._def.errorMap,
2050
- parent: null,
2051
- data,
2052
- parsedType: getParsedType(data)
2053
- };
2054
- if (!this["~standard"].async) {
2055
- try {
2056
- const result = this._parseSync({ data, path: [], parent: ctx });
2057
- return isValid(result) ? {
2058
- value: result.value
2059
- } : {
2060
- issues: ctx.common.issues
2061
- };
2062
- } catch (err) {
2063
- if (err?.message?.toLowerCase()?.includes("encountered")) {
2064
- this["~standard"].async = true;
2065
- }
2066
- ctx.common = {
2067
- issues: [],
2068
- async: true
2069
- };
2070
- }
2071
- }
2072
- return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
2073
- value: result.value
2074
- } : {
2075
- issues: ctx.common.issues
2076
- });
2077
- }
2078
- async parseAsync(data, params) {
2079
- const result = await this.safeParseAsync(data, params);
2080
- if (result.success)
2081
- return result.data;
2082
- throw result.error;
2083
- }
2084
- async safeParseAsync(data, params) {
2085
- const ctx = {
2086
- common: {
2087
- issues: [],
2088
- contextualErrorMap: params?.errorMap,
2089
- async: true
2090
- },
2091
- path: params?.path || [],
2092
- schemaErrorMap: this._def.errorMap,
2093
- parent: null,
2094
- data,
2095
- parsedType: getParsedType(data)
2096
- };
2097
- const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
2098
- const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
2099
- return handleResult(ctx, result);
2100
- }
2101
- refine(check, message) {
2102
- const getIssueProperties = (val) => {
2103
- if (typeof message === "string" || typeof message === "undefined") {
2104
- return { message };
2105
- } else if (typeof message === "function") {
2106
- return message(val);
2107
- } else {
2108
- return message;
2109
- }
2110
- };
2111
- return this._refinement((val, ctx) => {
2112
- const result = check(val);
2113
- const setError = () => ctx.addIssue({
2114
- code: ZodIssueCode.custom,
2115
- ...getIssueProperties(val)
2116
- });
2117
- if (typeof Promise !== "undefined" && result instanceof Promise) {
2118
- return result.then((data) => {
2119
- if (!data) {
2120
- setError();
2121
- return false;
2122
- } else {
2123
- return true;
2124
- }
2125
- });
2126
- }
2127
- if (!result) {
2128
- setError();
2129
- return false;
2130
- } else {
2131
- return true;
2132
- }
2133
- });
2134
- }
2135
- refinement(check, refinementData) {
2136
- return this._refinement((val, ctx) => {
2137
- if (!check(val)) {
2138
- ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
2139
- return false;
2140
- } else {
2141
- return true;
2142
- }
2143
- });
2144
- }
2145
- _refinement(refinement) {
2146
- return new ZodEffects({
2147
- schema: this,
2148
- typeName: ZodFirstPartyTypeKind.ZodEffects,
2149
- effect: { type: "refinement", refinement }
2150
- });
2151
- }
2152
- superRefine(refinement) {
2153
- return this._refinement(refinement);
2154
- }
2155
- constructor(def) {
2156
- this.spa = this.safeParseAsync;
2157
- this._def = def;
2158
- this.parse = this.parse.bind(this);
2159
- this.safeParse = this.safeParse.bind(this);
2160
- this.parseAsync = this.parseAsync.bind(this);
2161
- this.safeParseAsync = this.safeParseAsync.bind(this);
2162
- this.spa = this.spa.bind(this);
2163
- this.refine = this.refine.bind(this);
2164
- this.refinement = this.refinement.bind(this);
2165
- this.superRefine = this.superRefine.bind(this);
2166
- this.optional = this.optional.bind(this);
2167
- this.nullable = this.nullable.bind(this);
2168
- this.nullish = this.nullish.bind(this);
2169
- this.array = this.array.bind(this);
2170
- this.promise = this.promise.bind(this);
2171
- this.or = this.or.bind(this);
2172
- this.and = this.and.bind(this);
2173
- this.transform = this.transform.bind(this);
2174
- this.brand = this.brand.bind(this);
2175
- this.default = this.default.bind(this);
2176
- this.catch = this.catch.bind(this);
2177
- this.describe = this.describe.bind(this);
2178
- this.pipe = this.pipe.bind(this);
2179
- this.readonly = this.readonly.bind(this);
2180
- this.isNullable = this.isNullable.bind(this);
2181
- this.isOptional = this.isOptional.bind(this);
2182
- this["~standard"] = {
2183
- version: 1,
2184
- vendor: "zod",
2185
- validate: (data) => this["~validate"](data)
2186
- };
2187
- }
2188
- optional() {
2189
- return ZodOptional.create(this, this._def);
2190
- }
2191
- nullable() {
2192
- return ZodNullable.create(this, this._def);
2193
- }
2194
- nullish() {
2195
- return this.nullable().optional();
2196
- }
2197
- array() {
2198
- return ZodArray.create(this);
2199
- }
2200
- promise() {
2201
- return ZodPromise.create(this, this._def);
2202
- }
2203
- or(option) {
2204
- return ZodUnion.create([this, option], this._def);
2205
- }
2206
- and(incoming) {
2207
- return ZodIntersection.create(this, incoming, this._def);
2208
- }
2209
- transform(transform) {
2210
- return new ZodEffects({
2211
- ...processCreateParams(this._def),
2212
- schema: this,
2213
- typeName: ZodFirstPartyTypeKind.ZodEffects,
2214
- effect: { type: "transform", transform }
2215
- });
2216
- }
2217
- default(def) {
2218
- const defaultValueFunc = typeof def === "function" ? def : () => def;
2219
- return new ZodDefault({
2220
- ...processCreateParams(this._def),
2221
- innerType: this,
2222
- defaultValue: defaultValueFunc,
2223
- typeName: ZodFirstPartyTypeKind.ZodDefault
2224
- });
2225
- }
2226
- brand() {
2227
- return new ZodBranded({
2228
- typeName: ZodFirstPartyTypeKind.ZodBranded,
2229
- type: this,
2230
- ...processCreateParams(this._def)
2231
- });
2232
- }
2233
- catch(def) {
2234
- const catchValueFunc = typeof def === "function" ? def : () => def;
2235
- return new ZodCatch({
2236
- ...processCreateParams(this._def),
2237
- innerType: this,
2238
- catchValue: catchValueFunc,
2239
- typeName: ZodFirstPartyTypeKind.ZodCatch
2240
- });
2241
- }
2242
- describe(description) {
2243
- const This = this.constructor;
2244
- return new This({
2245
- ...this._def,
2246
- description
2247
- });
2248
- }
2249
- pipe(target) {
2250
- return ZodPipeline.create(this, target);
2251
- }
2252
- readonly() {
2253
- return ZodReadonly.create(this);
2254
- }
2255
- isOptional() {
2256
- return this.safeParse(void 0).success;
2257
- }
2258
- isNullable() {
2259
- return this.safeParse(null).success;
2260
- }
2261
- };
2262
- var cuidRegex = /^c[^\s-]{8,}$/i;
2263
- var cuid2Regex = /^[0-9a-z]+$/;
2264
- var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
2265
- var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
2266
- var nanoidRegex = /^[a-z0-9_-]{21}$/i;
2267
- var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
2268
- var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
2269
- var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
2270
- var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
2271
- var emojiRegex;
2272
- var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
2273
- var ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
2274
- var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
2275
- var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
2276
- var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
2277
- var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
2278
- var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
2279
- var dateRegex = new RegExp(`^${dateRegexSource}$`);
2280
- function timeRegexSource(args) {
2281
- let secondsRegexSource = `[0-5]\\d`;
2282
- if (args.precision) {
2283
- secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
2284
- } else if (args.precision == null) {
2285
- secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
2286
- }
2287
- const secondsQuantifier = args.precision ? "+" : "?";
2288
- return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
2289
- }
2290
- function timeRegex(args) {
2291
- return new RegExp(`^${timeRegexSource(args)}$`);
2292
- }
2293
- function datetimeRegex(args) {
2294
- let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
2295
- const opts = [];
2296
- opts.push(args.local ? `Z?` : `Z`);
2297
- if (args.offset)
2298
- opts.push(`([+-]\\d{2}:?\\d{2})`);
2299
- regex = `${regex}(${opts.join("|")})`;
2300
- return new RegExp(`^${regex}$`);
2301
- }
2302
- function isValidIP(ip, version) {
2303
- if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
2304
- return true;
2305
- }
2306
- if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
2307
- return true;
1787
+ if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
1788
+ return true;
2308
1789
  }
2309
1790
  return false;
2310
1791
  }
@@ -6928,447 +6409,1019 @@ var VerifyPayload = external_exports.object({
6928
6409
  function entryTotalTokens(e) {
6929
6410
  return e.inputTokens + e.outputTokens + e.cacheCreationTokens + e.cacheReadTokens;
6930
6411
  }
6931
- var LeaderboardPeriod = external_exports.enum(["today", "7d", "30d", "all"]);
6932
- var LeaderboardMetric = external_exports.enum(["tokens", "cost"]);
6933
- var OrgType = external_exports.enum(["company", "hackathon", "hackerhouse"]);
6934
- var MemberRole = external_exports.enum(["owner", "admin", "member"]);
6935
- var OrgBoardVisibility = external_exports.enum(["public", "members"]);
6936
- var HexColor = external_exports.string().regex(/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/, "must be a hex color like #f97316");
6937
- var RESERVED_SLUGS = /* @__PURE__ */ new Set([
6938
- ...RESERVED_SUBDOMAINS,
6939
- "o",
6940
- "d",
6941
- "u",
6942
- "boards",
6943
- "board",
6944
- "claim",
6945
- "signin",
6946
- "signout",
6947
- "login",
6948
- "logout",
6949
- "dashboard",
6950
- "install",
6951
- "for-teams",
6952
- "teams",
6953
- "about",
6954
- "contact",
6955
- "trust",
6956
- "cli",
6957
- "feedback",
6958
- "guides",
6959
- "guide",
6960
- "join",
6961
- "leaderboard",
6962
- "settings",
6963
- "account",
6964
- "me",
6965
- "new",
6966
- "robots",
6967
- "sitemap"
6968
- ]);
6969
- var ORG_TEXT_BLOCKLIST = /* @__PURE__ */ new Set([
6970
- "nigger",
6971
- "nigga",
6972
- "faggot",
6973
- "retard",
6974
- "rape",
6975
- "rapist",
6976
- "kike",
6977
- "spic",
6978
- "chink",
6979
- "cunt"
6980
- ]);
6981
- var ORG_TEXT_LEET = {
6982
- "0": "o",
6983
- "1": "i",
6984
- "3": "e",
6985
- "4": "a",
6986
- "5": "s",
6987
- "7": "t",
6988
- "8": "b",
6989
- "@": "a",
6990
- "$": "s"
6991
- };
6992
- function isCleanOrgText(input) {
6993
- const runs = String(input).toLowerCase().split(/[^a-z0-9@$]+/).map((run2) => run2.replace(/[0-9@$]/g, (c) => ORG_TEXT_LEET[c] ?? c).replace(/[^a-z]/g, ""));
6994
- return !runs.some((run2) => run2.length > 0 && ORG_TEXT_BLOCKLIST.has(run2));
6412
+ var LeaderboardPeriod = external_exports.enum(["today", "7d", "30d", "all"]);
6413
+ var LeaderboardMetric = external_exports.enum(["tokens", "cost"]);
6414
+ var OrgType = external_exports.enum(["company", "hackathon", "hackerhouse"]);
6415
+ var MemberRole = external_exports.enum(["owner", "admin", "member"]);
6416
+ var OrgBoardVisibility = external_exports.enum(["public", "members"]);
6417
+ var HexColor = external_exports.string().regex(/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/, "must be a hex color like #f97316");
6418
+ var RESERVED_SLUGS = /* @__PURE__ */ new Set([
6419
+ ...RESERVED_SUBDOMAINS,
6420
+ "o",
6421
+ "d",
6422
+ "u",
6423
+ "boards",
6424
+ "board",
6425
+ "claim",
6426
+ "signin",
6427
+ "signout",
6428
+ "login",
6429
+ "logout",
6430
+ "dashboard",
6431
+ "install",
6432
+ "for-teams",
6433
+ "teams",
6434
+ "about",
6435
+ "contact",
6436
+ "trust",
6437
+ "cli",
6438
+ "feedback",
6439
+ "guides",
6440
+ "guide",
6441
+ "join",
6442
+ "leaderboard",
6443
+ "settings",
6444
+ "account",
6445
+ "me",
6446
+ "new",
6447
+ "robots",
6448
+ "sitemap"
6449
+ ]);
6450
+ var ORG_TEXT_BLOCKLIST = /* @__PURE__ */ new Set([
6451
+ "nigger",
6452
+ "nigga",
6453
+ "faggot",
6454
+ "retard",
6455
+ "rape",
6456
+ "rapist",
6457
+ "kike",
6458
+ "spic",
6459
+ "chink",
6460
+ "cunt"
6461
+ ]);
6462
+ var ORG_TEXT_LEET = {
6463
+ "0": "o",
6464
+ "1": "i",
6465
+ "3": "e",
6466
+ "4": "a",
6467
+ "5": "s",
6468
+ "7": "t",
6469
+ "8": "b",
6470
+ "@": "a",
6471
+ "$": "s"
6472
+ };
6473
+ function isCleanOrgText(input) {
6474
+ const runs = String(input).toLowerCase().split(/[^a-z0-9@$]+/).map((run2) => run2.replace(/[0-9@$]/g, (c) => ORG_TEXT_LEET[c] ?? c).replace(/[^a-z]/g, ""));
6475
+ return !runs.some((run2) => run2.length > 0 && ORG_TEXT_BLOCKLIST.has(run2));
6476
+ }
6477
+ var SLUG_RE = /^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/;
6478
+ function isValidSlug(slug) {
6479
+ return typeof slug === "string" && slug.length >= 2 && slug.length <= 32 && SLUG_RE.test(slug) && // Reject consecutive hyphens — the regex above permits "a--b", which makes
6480
+ // for confusing subdomains and is never a deliberate slug.
6481
+ !slug.includes("--") && !RESERVED_SLUGS.has(slug);
6482
+ }
6483
+ var OrgSlug = external_exports.string().min(2).max(32).refine(isValidSlug, "invalid or reserved slug").refine(isCleanOrgText, "invalid or reserved slug");
6484
+ var OrgWindow = external_exports.object({
6485
+ startDate: DateString.nullable().optional(),
6486
+ endDate: DateString.nullable().optional()
6487
+ }).refine((w) => !(w.startDate && w.endDate) || w.endDate >= w.startDate, { message: "endDate must be on or after startDate", path: ["endDate"] });
6488
+ var OrgJoinPolicy = external_exports.object({
6489
+ allowCodeJoin: external_exports.boolean().default(true),
6490
+ allowDomainJoin: external_exports.boolean().default(false),
6491
+ /** Verified email domains that auto-join, e.g. ["acme.com"]. */
6492
+ emailDomains: external_exports.array(external_exports.string().min(3).max(253).toLowerCase()).max(20).default([])
6493
+ });
6494
+ var OrgApplicationInput = external_exports.object({
6495
+ type: OrgType,
6496
+ orgName: external_exports.string().min(1).max(120),
6497
+ desiredSlug: external_exports.string().min(2).max(32).optional(),
6498
+ contactName: external_exports.string().min(1).max(120),
6499
+ contactEmail: external_exports.string().email().max(254),
6500
+ website: external_exports.string().url().max(300).optional(),
6501
+ /** Rough headcount / attendee estimate, free text. */
6502
+ size: external_exports.string().max(60).optional(),
6503
+ message: external_exports.string().max(2e3).optional()
6504
+ });
6505
+ var OrgProvisionInput = external_exports.object({
6506
+ /** When provisioning straight from an application. */
6507
+ applicationId: external_exports.string().min(1).max(64).optional(),
6508
+ slug: OrgSlug,
6509
+ name: external_exports.string().min(1).max(120),
6510
+ type: OrgType,
6511
+ /** Handle (or email) of the user who becomes Owner. */
6512
+ ownerHandle: external_exports.string().min(1).max(120).optional(),
6513
+ ownerEmail: external_exports.string().email().max(254).optional(),
6514
+ description: external_exports.string().max(2e3).optional(),
6515
+ boardVisibility: OrgBoardVisibility.optional(),
6516
+ window: OrgWindow.optional(),
6517
+ /** Brand accent applied to the org homepage theming. */
6518
+ accentColor: HexColor.optional(),
6519
+ /**
6520
+ * Create the org UNOWNED and mint a one-time owner-claim ("admin sign-in")
6521
+ * token in the same call. The first person to open the link + sign in becomes
6522
+ * the owner; the token is then consumed. When set, an owner email/handle is
6523
+ * NOT required — the link is how the first admin is assigned.
6524
+ */
6525
+ issueClaimLink: external_exports.boolean().optional()
6526
+ });
6527
+ var OrgSelfServeInput = external_exports.object({
6528
+ slug: OrgSlug,
6529
+ name: external_exports.string().min(1).max(120).refine(isCleanOrgText, "name not allowed"),
6530
+ type: OrgType,
6531
+ description: external_exports.string().max(2e3).optional(),
6532
+ accentColor: HexColor.optional(),
6533
+ /** Who can view the board — defaults to the type's default when omitted. */
6534
+ boardVisibility: OrgBoardVisibility.optional(),
6535
+ /** Optional event window (mainly for hackathons). */
6536
+ window: OrgWindow.optional()
6537
+ });
6538
+ var OrgSettingsInput = external_exports.object({
6539
+ name: external_exports.string().min(1).max(120).optional(),
6540
+ description: external_exports.string().max(2e3).nullable().optional(),
6541
+ accentColor: HexColor.optional(),
6542
+ boardVisibility: OrgBoardVisibility.optional(),
6543
+ window: OrgWindow.optional(),
6544
+ joinPolicy: OrgJoinPolicy.partial().optional()
6545
+ });
6546
+ var OrgJoinInput = external_exports.object({
6547
+ /** Required only when joining via a code; domain/admin joins omit it. */
6548
+ code: external_exports.string().min(1).max(64).optional()
6549
+ });
6550
+
6551
+ // src/native/file-cache.ts
6552
+ import { mkdirSync as mkdirSync3, renameSync as renameSync3, writeFileSync as writeFileSync3 } from "node:fs";
6553
+ import { readFile, stat } from "node:fs/promises";
6554
+ import { dirname as dirname2, join as join3 } from "node:path";
6555
+ function nativeCachePath(reader, env = process.env) {
6556
+ const override = env.WHOBURNEDMORE_CONFIG_DIR?.trim();
6557
+ const dir = override || defaultConfigDir();
6558
+ return join3(dir, `native-cache-${reader}.json`);
6559
+ }
6560
+ async function loadCache(path, version) {
6561
+ try {
6562
+ const raw = await readFile(path, "utf8");
6563
+ const parsed = JSON.parse(raw);
6564
+ if (parsed && parsed.v === version && parsed.files && typeof parsed.files === "object") {
6565
+ return parsed.files;
6566
+ }
6567
+ } catch {
6568
+ }
6569
+ return {};
6570
+ }
6571
+ function saveCache(path, version, files) {
6572
+ try {
6573
+ mkdirSync3(dirname2(path), { recursive: true });
6574
+ const tmp = `${path}.tmp-${process.pid}`;
6575
+ writeFileSync3(tmp, JSON.stringify({ v: version, files }));
6576
+ renameSync3(tmp, path);
6577
+ } catch {
6578
+ }
6579
+ }
6580
+ async function readFilesWithCache(opts) {
6581
+ const now = opts.now ?? Date.now;
6582
+ const cached = await loadCache(opts.cachePath, opts.version);
6583
+ const fresh = {};
6584
+ const itemsByFile = [];
6585
+ let filesRead = 0;
6586
+ for (const f of opts.files) {
6587
+ let size;
6588
+ let mtimeMs;
6589
+ try {
6590
+ const s = await stat(f);
6591
+ size = s.size;
6592
+ mtimeMs = s.mtimeMs;
6593
+ } catch {
6594
+ continue;
6595
+ }
6596
+ const hit = cached[f];
6597
+ if (hit && hit.size === size && hit.mtimeMs === mtimeMs) {
6598
+ fresh[f] = hit;
6599
+ itemsByFile.push(hit.items);
6600
+ continue;
6601
+ }
6602
+ if (now() > opts.deadline) {
6603
+ saveCache(opts.cachePath, opts.version, { ...cached, ...fresh });
6604
+ return { itemsByFile: null, filesRead, timedOut: true };
6605
+ }
6606
+ let content;
6607
+ try {
6608
+ content = await readFile(f, "utf8");
6609
+ } catch {
6610
+ continue;
6611
+ }
6612
+ const items = opts.parseFile(content, f);
6613
+ fresh[f] = { size, mtimeMs, items };
6614
+ itemsByFile.push(items);
6615
+ filesRead += 1;
6616
+ }
6617
+ saveCache(opts.cachePath, opts.version, fresh);
6618
+ return { itemsByFile, filesRead, timedOut: false };
6619
+ }
6620
+
6621
+ // src/native/claude.ts
6622
+ function num(n) {
6623
+ const v = Math.round(Number(n));
6624
+ return Number.isFinite(v) && v > 0 ? v : 0;
6625
+ }
6626
+ function reqTokens(r) {
6627
+ return r.inputTokens + r.outputTokens + r.cacheCreationTokens + r.cacheReadTokens;
6628
+ }
6629
+ function localDate(iso) {
6630
+ const t = Date.parse(iso);
6631
+ if (!Number.isFinite(t)) return null;
6632
+ const d = new Date(t);
6633
+ const y = d.getFullYear();
6634
+ const m = String(d.getMonth() + 1).padStart(2, "0");
6635
+ const day = String(d.getDate()).padStart(2, "0");
6636
+ return `${y}-${m}-${day}`;
6637
+ }
6638
+ var syntheticCounter = 0;
6639
+ function parseClaudeLine(raw) {
6640
+ const trimmed = raw.trim();
6641
+ if (!trimmed) return null;
6642
+ let obj;
6643
+ try {
6644
+ obj = JSON.parse(trimmed);
6645
+ } catch {
6646
+ return null;
6647
+ }
6648
+ const message = obj.message;
6649
+ if (!message || typeof message !== "object") return null;
6650
+ const usage = message.usage;
6651
+ if (!usage || typeof usage !== "object") return null;
6652
+ if (message.role !== void 0 && message.role !== "assistant") return null;
6653
+ const date = localDate(String(obj.timestamp ?? ""));
6654
+ if (!date) return null;
6655
+ const tsParsed = Date.parse(String(obj.timestamp ?? ""));
6656
+ const ts = Number.isFinite(tsParsed) ? tsParsed : 0;
6657
+ const messageId = typeof message.id === "string" ? message.id : "";
6658
+ const requestId = typeof obj.requestId === "string" ? obj.requestId : "";
6659
+ const hasRealId = messageId !== "" || requestId !== "";
6660
+ const key = hasRealId ? `${messageId}|${requestId}` : `synthetic|${date}|${syntheticCounter += 1}`;
6661
+ return {
6662
+ key,
6663
+ hasRealId,
6664
+ date,
6665
+ ts,
6666
+ model: typeof message.model === "string" ? message.model : "unknown",
6667
+ inputTokens: num(usage.input_tokens),
6668
+ outputTokens: num(usage.output_tokens),
6669
+ cacheCreationTokens: num(usage.cache_creation_input_tokens),
6670
+ cacheReadTokens: num(usage.cache_read_input_tokens)
6671
+ };
6672
+ }
6673
+ function accumulateClaudeLines(acc, lines) {
6674
+ for (const line of lines) {
6675
+ const r = parseClaudeLine(line);
6676
+ if (!r) continue;
6677
+ const prev = acc.get(r.key);
6678
+ if (!prev || reqTokens(r) > reqTokens(prev)) acc.set(r.key, r);
6679
+ }
6680
+ }
6681
+ function finalizeClaudeEntries(acc) {
6682
+ const byDayModel = /* @__PURE__ */ new Map();
6683
+ for (const r of acc.values()) {
6684
+ const k = `${r.date}|${r.model}`;
6685
+ let b = byDayModel.get(k);
6686
+ if (!b) {
6687
+ b = {
6688
+ date: r.date,
6689
+ model: r.model,
6690
+ inputTokens: 0,
6691
+ outputTokens: 0,
6692
+ cacheCreationTokens: 0,
6693
+ cacheReadTokens: 0,
6694
+ requestCount: 0
6695
+ };
6696
+ byDayModel.set(k, b);
6697
+ }
6698
+ b.inputTokens += r.inputTokens;
6699
+ b.outputTokens += r.outputTokens;
6700
+ b.cacheCreationTokens += r.cacheCreationTokens;
6701
+ b.cacheReadTokens += r.cacheReadTokens;
6702
+ if (r.hasRealId) b.requestCount += 1;
6703
+ }
6704
+ const entries = [];
6705
+ for (const b of byDayModel.values()) {
6706
+ const tokens = b.inputTokens + b.outputTokens + b.cacheCreationTokens + b.cacheReadTokens;
6707
+ if (tokens === 0) continue;
6708
+ entries.push({
6709
+ date: b.date,
6710
+ tool: "claude",
6711
+ model: b.model,
6712
+ inputTokens: b.inputTokens,
6713
+ outputTokens: b.outputTokens,
6714
+ cacheCreationTokens: b.cacheCreationTokens,
6715
+ cacheReadTokens: b.cacheReadTokens,
6716
+ costUSD: estimateCostUSD(b.model, b),
6717
+ origin: "cli",
6718
+ verified: false,
6719
+ requestCount: b.requestCount
6720
+ });
6721
+ }
6722
+ return entries;
6723
+ }
6724
+ function resolveClaudeConfigRoots(env = process.env) {
6725
+ const override = env.CLAUDE_CONFIG_DIR;
6726
+ return override ? override.split(",").map((s) => s.trim()).filter(Boolean) : [join4(homedir3(), ".claude"), join4(homedir3(), ".config", "claude")];
6727
+ }
6728
+ function resolveClaudeProjectDirs(env = process.env) {
6729
+ return resolveClaudeConfigRoots(env).map((r) => join4(r, "projects"));
6730
+ }
6731
+ async function listJsonl(dir) {
6732
+ let dirents;
6733
+ try {
6734
+ dirents = await readdir(dir, { withFileTypes: true });
6735
+ } catch {
6736
+ return [];
6737
+ }
6738
+ const out = [];
6739
+ for (const d of dirents) {
6740
+ const full = join4(dir, d.name);
6741
+ if (d.isDirectory()) {
6742
+ out.push(...await listJsonl(full));
6743
+ } else if (d.isFile() && d.name.endsWith(".jsonl")) {
6744
+ out.push(full);
6745
+ }
6746
+ }
6747
+ return out;
6748
+ }
6749
+ var NATIVE_READ_BUDGET_MS = 45e3;
6750
+ var CLAUDE_CACHE_VERSION = 1;
6751
+ function toCached(r) {
6752
+ return [
6753
+ r.key,
6754
+ r.hasRealId ? 1 : 0,
6755
+ r.date,
6756
+ r.model,
6757
+ r.inputTokens,
6758
+ r.outputTokens,
6759
+ r.cacheCreationTokens,
6760
+ r.cacheReadTokens
6761
+ ];
6762
+ }
6763
+ function fromCached(t) {
6764
+ return {
6765
+ key: t[0],
6766
+ hasRealId: t[1] === 1,
6767
+ date: t[2],
6768
+ ts: 0,
6769
+ model: t[3],
6770
+ inputTokens: t[4],
6771
+ outputTokens: t[5],
6772
+ cacheCreationTokens: t[6],
6773
+ cacheReadTokens: t[7]
6774
+ };
6775
+ }
6776
+ function parseFileToCache(content, path) {
6777
+ const acc = /* @__PURE__ */ new Map();
6778
+ accumulateClaudeLines(acc, splitLines(content));
6779
+ let synIndex = 0;
6780
+ return [...acc.values()].map(
6781
+ (r) => toCached(
6782
+ r.hasRealId ? r : { ...r, key: `synthetic|${path}|${synIndex += 1}` }
6783
+ )
6784
+ );
6785
+ }
6786
+ function* splitLines(content) {
6787
+ let start = 0;
6788
+ for (let i = 0; i < content.length; i++) {
6789
+ if (content[i] === "\n") {
6790
+ yield content.slice(start, i);
6791
+ start = i + 1;
6792
+ }
6793
+ }
6794
+ if (start < content.length) yield content.slice(start);
6795
+ }
6796
+ async function collectClaudeNative(env = process.env, opts = {}) {
6797
+ const dirs = resolveClaudeProjectDirs(env);
6798
+ const files = [];
6799
+ for (const dir of dirs) files.push(...await listJsonl(dir));
6800
+ if (files.length === 0) return { entries: [], found: false, filesScanned: 0 };
6801
+ const now = opts.now ?? Date.now;
6802
+ const res = await readFilesWithCache({
6803
+ files,
6804
+ cachePath: opts.cachePath ?? nativeCachePath("claude", env),
6805
+ version: CLAUDE_CACHE_VERSION,
6806
+ parseFile: parseFileToCache,
6807
+ deadline: now() + (opts.budgetMs ?? NATIVE_READ_BUDGET_MS),
6808
+ now
6809
+ });
6810
+ if (!res.itemsByFile) {
6811
+ return {
6812
+ entries: [],
6813
+ found: false,
6814
+ filesScanned: res.filesRead,
6815
+ timedOut: true
6816
+ };
6817
+ }
6818
+ const acc = /* @__PURE__ */ new Map();
6819
+ for (const items of res.itemsByFile) {
6820
+ for (const t of items) {
6821
+ const r = fromCached(t);
6822
+ const prev = acc.get(r.key);
6823
+ if (!prev || reqTokens(r) > reqTokens(prev)) acc.set(r.key, r);
6824
+ }
6825
+ }
6826
+ return {
6827
+ entries: finalizeClaudeEntries(acc),
6828
+ found: true,
6829
+ filesScanned: res.filesRead
6830
+ };
6831
+ }
6832
+ async function collectClaudeRequests(env = process.env, opts = {}) {
6833
+ const dirs = resolveClaudeProjectDirs(env);
6834
+ const files = [];
6835
+ for (const dir of dirs) files.push(...await listJsonl(dir));
6836
+ if (files.length === 0) return { requests: [], found: false };
6837
+ const now = opts.now ?? Date.now;
6838
+ const deadline = now() + (opts.budgetMs ?? NATIVE_READ_BUDGET_MS);
6839
+ const acc = /* @__PURE__ */ new Map();
6840
+ for (const f of files) {
6841
+ if (now() > deadline) {
6842
+ return { requests: [...acc.values()], found: true, timedOut: true };
6843
+ }
6844
+ let content;
6845
+ try {
6846
+ content = await readFile2(f, "utf8");
6847
+ } catch {
6848
+ continue;
6849
+ }
6850
+ accumulateClaudeLines(acc, splitLines(content));
6851
+ }
6852
+ return { requests: [...acc.values()], found: true };
6853
+ }
6854
+
6855
+ // src/attribution.ts
6856
+ var CLAUDE_PROJECTS = join5(homedir4(), ".claude", "projects");
6857
+ var CODEX_SESSIONS = join5(homedir4(), ".codex", "sessions");
6858
+ var MAX_FILES = 5e3;
6859
+ var TIME_BUDGET_MS = NATIVE_READ_BUDGET_MS;
6860
+ var ATTRIBUTION_CACHE_VERSION = 1;
6861
+ var MAX_STATS = 300;
6862
+ function createAccumulator() {
6863
+ return {
6864
+ tools: /* @__PURE__ */ new Map(),
6865
+ skills: /* @__PURE__ */ new Map(),
6866
+ agent: {
6867
+ messageCount: 0,
6868
+ subagentMessages: 0,
6869
+ subagentTokens: 0,
6870
+ totalTokens: 0,
6871
+ userMessageCount: 0
6872
+ },
6873
+ sessionMessages: /* @__PURE__ */ new Map()
6874
+ };
6875
+ }
6876
+ function createFileContext() {
6877
+ return { toolNames: /* @__PURE__ */ new Map() };
6878
+ }
6879
+ function recordTokens(usage) {
6880
+ if (!usage || typeof usage !== "object") return 0;
6881
+ const u = usage;
6882
+ const n = (v) => {
6883
+ const x = Math.round(Number(v));
6884
+ return Number.isFinite(x) && x > 0 ? x : 0;
6885
+ };
6886
+ return n(u.input_tokens) + n(u.output_tokens) + n(u.cache_creation_input_tokens) + n(u.cache_read_input_tokens);
6887
+ }
6888
+ function hasHumanText(content) {
6889
+ const isHuman = (t) => {
6890
+ const s = t.trim();
6891
+ return s.length > 0 && !s.startsWith("<system-reminder") && !s.startsWith("<command-") && !s.startsWith("Caveat:");
6892
+ };
6893
+ if (typeof content === "string") return isHuman(content);
6894
+ if (!Array.isArray(content)) return false;
6895
+ return content.some(
6896
+ (b) => b !== null && typeof b === "object" && b.type === "text" && typeof b.text === "string" && isHuman(b.text)
6897
+ );
6898
+ }
6899
+ function processRecord(rec, acc, ctx) {
6900
+ if (!rec || typeof rec !== "object") return;
6901
+ const r = rec;
6902
+ const recTokens = recordTokens(r.message?.usage);
6903
+ if ((r.type === "user" || r.message?.role === "user") && r.isSidechain !== true && r.isMeta !== true && hasHumanText(r.message?.content)) {
6904
+ acc.agent.userMessageCount += 1;
6905
+ }
6906
+ if (typeof r.attributionSkill === "string" && r.attributionSkill) {
6907
+ const s = r.attributionSkill.slice(0, 128);
6908
+ const sk = acc.skills.get(s) ?? { count: 0, tokens: 0 };
6909
+ sk.count += 1;
6910
+ sk.tokens += recTokens;
6911
+ acc.skills.set(s, sk);
6912
+ }
6913
+ const content = r.message?.content;
6914
+ if (!Array.isArray(content)) return;
6915
+ const isAssistant = r.type === "assistant" || r.message?.role === "assistant";
6916
+ const isUser = r.type === "user" || r.message?.role === "user";
6917
+ if (isAssistant) {
6918
+ const toolUses = [];
6919
+ for (const block of content) {
6920
+ if (block && typeof block === "object" && block.type === "tool_use" && typeof block.name === "string") {
6921
+ const name = block.name.slice(0, 128);
6922
+ if (!name) continue;
6923
+ const id = block.id;
6924
+ toolUses.push({ name, id: typeof id === "string" ? id : void 0 });
6925
+ }
6926
+ }
6927
+ const perToolTokens = toolUses.length > 0 ? Math.floor(recTokens / toolUses.length) : 0;
6928
+ for (const tu of toolUses) {
6929
+ const t = acc.tools.get(tu.name) ?? { count: 0, errors: 0, tokens: 0 };
6930
+ t.count += 1;
6931
+ t.tokens += perToolTokens;
6932
+ acc.tools.set(tu.name, t);
6933
+ if (tu.id) ctx.toolNames.set(tu.id, tu.name);
6934
+ }
6935
+ const tokens = recTokens;
6936
+ acc.agent.messageCount += 1;
6937
+ acc.agent.totalTokens += tokens;
6938
+ const sidechain = r.isSidechain === true;
6939
+ if (sidechain) {
6940
+ acc.agent.subagentMessages += 1;
6941
+ acc.agent.subagentTokens += tokens;
6942
+ }
6943
+ if (typeof r.sessionId === "string" && r.sessionId) {
6944
+ acc.sessionMessages.set(
6945
+ r.sessionId,
6946
+ (acc.sessionMessages.get(r.sessionId) ?? 0) + 1
6947
+ );
6948
+ }
6949
+ } else if (isUser) {
6950
+ for (const block of content) {
6951
+ if (block && typeof block === "object" && block.type === "tool_result" && block.is_error === true) {
6952
+ const id = block.tool_use_id;
6953
+ const name = typeof id === "string" ? ctx.toolNames.get(id) : void 0;
6954
+ if (name) {
6955
+ const t = acc.tools.get(name) ?? { count: 0, errors: 0, tokens: 0 };
6956
+ t.errors += 1;
6957
+ acc.tools.set(name, t);
6958
+ }
6959
+ }
6960
+ }
6961
+ }
6962
+ }
6963
+ function toSkillStats(map) {
6964
+ return [...map.entries()].map(([name, v]) => ({ name, count: v.count, tokens: v.tokens })).filter((s) => s.count > 0).sort((a, b) => b.tokens - a.tokens || b.count - a.count).slice(0, MAX_STATS).map((s) => s.tokens > 0 ? s : { name: s.name, count: s.count });
6995
6965
  }
6996
- var SLUG_RE = /^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/;
6997
- function isValidSlug(slug) {
6998
- return typeof slug === "string" && slug.length >= 2 && slug.length <= 32 && SLUG_RE.test(slug) && // Reject consecutive hyphens — the regex above permits "a--b", which makes
6999
- // for confusing subdomains and is never a deliberate slug.
7000
- !slug.includes("--") && !RESERVED_SLUGS.has(slug);
6966
+ function toToolStats(map) {
6967
+ return [...map.entries()].map(([name, v]) => ({ name, count: v.count, errors: v.errors, tokens: v.tokens })).filter((s) => s.count > 0).sort((a, b) => b.tokens - a.tokens || b.count - a.count).slice(0, MAX_STATS).map((s) => {
6968
+ const base = { name: s.name, count: s.count };
6969
+ if (s.errors > 0) base.errors = s.errors;
6970
+ if (s.tokens > 0) base.tokens = s.tokens;
6971
+ return base;
6972
+ });
7001
6973
  }
7002
- var OrgSlug = external_exports.string().min(2).max(32).refine(isValidSlug, "invalid or reserved slug").refine(isCleanOrgText, "invalid or reserved slug");
7003
- var OrgWindow = external_exports.object({
7004
- startDate: DateString.nullable().optional(),
7005
- endDate: DateString.nullable().optional()
7006
- }).refine((w) => !(w.startDate && w.endDate) || w.endDate >= w.startDate, { message: "endDate must be on or after startDate", path: ["endDate"] });
7007
- var OrgJoinPolicy = external_exports.object({
7008
- allowCodeJoin: external_exports.boolean().default(true),
7009
- allowDomainJoin: external_exports.boolean().default(false),
7010
- /** Verified email domains that auto-join, e.g. ["acme.com"]. */
7011
- emailDomains: external_exports.array(external_exports.string().min(3).max(253).toLowerCase()).max(20).default([])
7012
- });
7013
- var OrgApplicationInput = external_exports.object({
7014
- type: OrgType,
7015
- orgName: external_exports.string().min(1).max(120),
7016
- desiredSlug: external_exports.string().min(2).max(32).optional(),
7017
- contactName: external_exports.string().min(1).max(120),
7018
- contactEmail: external_exports.string().email().max(254),
7019
- website: external_exports.string().url().max(300).optional(),
7020
- /** Rough headcount / attendee estimate, free text. */
7021
- size: external_exports.string().max(60).optional(),
7022
- message: external_exports.string().max(2e3).optional()
7023
- });
7024
- var OrgProvisionInput = external_exports.object({
7025
- /** When provisioning straight from an application. */
7026
- applicationId: external_exports.string().min(1).max(64).optional(),
7027
- slug: OrgSlug,
7028
- name: external_exports.string().min(1).max(120),
7029
- type: OrgType,
7030
- /** Handle (or email) of the user who becomes Owner. */
7031
- ownerHandle: external_exports.string().min(1).max(120).optional(),
7032
- ownerEmail: external_exports.string().email().max(254).optional(),
7033
- description: external_exports.string().max(2e3).optional(),
7034
- boardVisibility: OrgBoardVisibility.optional(),
7035
- window: OrgWindow.optional(),
7036
- /** Brand accent applied to the org homepage theming. */
7037
- accentColor: HexColor.optional(),
7038
- /**
7039
- * Create the org UNOWNED and mint a one-time owner-claim ("admin sign-in")
7040
- * token in the same call. The first person to open the link + sign in becomes
7041
- * the owner; the token is then consumed. When set, an owner email/handle is
7042
- * NOT required — the link is how the first admin is assigned.
7043
- */
7044
- issueClaimLink: external_exports.boolean().optional()
7045
- });
7046
- var OrgSelfServeInput = external_exports.object({
7047
- slug: OrgSlug,
7048
- name: external_exports.string().min(1).max(120).refine(isCleanOrgText, "name not allowed"),
7049
- type: OrgType,
7050
- description: external_exports.string().max(2e3).optional(),
7051
- accentColor: HexColor.optional(),
7052
- /** Who can view the board — defaults to the type's default when omitted. */
7053
- boardVisibility: OrgBoardVisibility.optional(),
7054
- /** Optional event window (mainly for hackathons). */
7055
- window: OrgWindow.optional()
7056
- });
7057
- var OrgSettingsInput = external_exports.object({
7058
- name: external_exports.string().min(1).max(120).optional(),
7059
- description: external_exports.string().max(2e3).nullable().optional(),
7060
- accentColor: HexColor.optional(),
7061
- boardVisibility: OrgBoardVisibility.optional(),
7062
- window: OrgWindow.optional(),
7063
- joinPolicy: OrgJoinPolicy.partial().optional()
7064
- });
7065
- var OrgJoinInput = external_exports.object({
7066
- /** Required only when joining via a code; domain/admin joins omit it. */
7067
- code: external_exports.string().min(1).max(64).optional()
7068
- });
7069
-
7070
- // src/native/file-cache.ts
7071
- import { mkdirSync as mkdirSync3, renameSync as renameSync3, writeFileSync as writeFileSync3 } from "node:fs";
7072
- import { readFile, stat } from "node:fs/promises";
7073
- import { dirname as dirname3, join as join6 } from "node:path";
7074
- function nativeCachePath(reader, env = process.env) {
7075
- const override = env.WHOBURNEDMORE_CONFIG_DIR?.trim();
7076
- const dir = override || defaultConfigDir();
7077
- return join6(dir, `native-cache-${reader}.json`);
6974
+ function accumulatorToResult(acc) {
6975
+ return {
6976
+ tools: toToolStats(acc.tools),
6977
+ skills: toSkillStats(acc.skills),
6978
+ agent: { ...acc.agent },
6979
+ sessionMessages: acc.sessionMessages,
6980
+ complete: true
6981
+ };
7078
6982
  }
7079
- async function loadCache(path, version) {
7080
- try {
7081
- const raw = await readFile(path, "utf8");
7082
- const parsed = JSON.parse(raw);
7083
- if (parsed && parsed.v === version && parsed.files && typeof parsed.files === "object") {
7084
- return parsed.files;
6983
+ function numTok(v) {
6984
+ const x = Math.round(Number(v));
6985
+ return Number.isFinite(x) && x > 0 ? x : 0;
6986
+ }
6987
+ function createCodexContext() {
6988
+ return { pending: [] };
6989
+ }
6990
+ function processCodexRecord(rec, acc, ctx) {
6991
+ if (!rec || typeof rec !== "object") return;
6992
+ const r = rec;
6993
+ if (!r.payload || typeof r.payload !== "object") return;
6994
+ const pl = r.payload;
6995
+ const ptype = pl.type;
6996
+ if (r.type === "session_meta" || r.type === "turn_context") return;
6997
+ if (ptype === "function_call" || ptype === "custom_tool_call" || ptype === "local_shell_call") {
6998
+ const raw = typeof pl.name === "string" ? pl.name : ptype === "local_shell_call" ? "local_shell" : "";
6999
+ const name = raw.slice(0, 128);
7000
+ if (!name) return;
7001
+ const id = typeof pl.call_id === "string" ? pl.call_id : void 0;
7002
+ ctx.pending.push({ name, id });
7003
+ const t = acc.tools.get(name) ?? { count: 0, errors: 0, tokens: 0 };
7004
+ t.count += 1;
7005
+ acc.tools.set(name, t);
7006
+ return;
7007
+ }
7008
+ if (ptype === "token_count") {
7009
+ const info = pl.info;
7010
+ const last = info?.last_token_usage;
7011
+ if (!last) return;
7012
+ const inputTokens = numTok(last.input_tokens);
7013
+ const cacheReadTokens = numTok(last.cached_input_tokens);
7014
+ const outputTokens = numTok(last.output_tokens) + numTok(last.reasoning_output_tokens);
7015
+ const tokens = numTok(last.total_tokens) || inputTokens + cacheReadTokens + outputTokens;
7016
+ if (tokens <= 0) {
7017
+ ctx.pending = [];
7018
+ return;
7085
7019
  }
7086
- } catch {
7020
+ acc.agent.messageCount += 1;
7021
+ acc.agent.totalTokens += tokens;
7022
+ const per = ctx.pending.length > 0 ? Math.floor(tokens / ctx.pending.length) : 0;
7023
+ for (const tu of ctx.pending) {
7024
+ const t = acc.tools.get(tu.name);
7025
+ if (t) t.tokens += per;
7026
+ }
7027
+ ctx.pending = [];
7087
7028
  }
7088
- return {};
7089
7029
  }
7090
- function saveCache(path, version, files) {
7091
- try {
7092
- mkdirSync3(dirname3(path), { recursive: true });
7093
- const tmp = `${path}.tmp-${process.pid}`;
7094
- writeFileSync3(tmp, JSON.stringify({ v: version, files }));
7095
- renameSync3(tmp, path);
7096
- } catch {
7030
+ function* splitLines2(content) {
7031
+ let start = 0;
7032
+ for (let i = 0; i < content.length; i++) {
7033
+ if (content[i] === "\n") {
7034
+ yield content.slice(start, i);
7035
+ start = i + 1;
7036
+ }
7037
+ }
7038
+ if (start < content.length) yield content.slice(start);
7039
+ }
7040
+ function serializeAcc(acc) {
7041
+ return {
7042
+ tools: [...acc.tools].map(([n, v]) => [n, v.count, v.errors, v.tokens]),
7043
+ skills: [...acc.skills].map(([n, v]) => [n, v.count, v.tokens]),
7044
+ agent: [
7045
+ acc.agent.messageCount,
7046
+ acc.agent.subagentMessages,
7047
+ acc.agent.subagentTokens,
7048
+ acc.agent.totalTokens,
7049
+ acc.agent.userMessageCount
7050
+ ],
7051
+ sessions: [...acc.sessionMessages].map(([s, c]) => [s, c])
7052
+ };
7053
+ }
7054
+ function mergeAgg(acc, agg) {
7055
+ for (const [n, count, errors, tokens] of agg.tools) {
7056
+ const cur = acc.tools.get(n) ?? { count: 0, errors: 0, tokens: 0 };
7057
+ cur.count += count;
7058
+ cur.errors += errors;
7059
+ cur.tokens += tokens;
7060
+ acc.tools.set(n, cur);
7061
+ }
7062
+ for (const [n, count, tokens] of agg.skills) {
7063
+ const cur = acc.skills.get(n) ?? { count: 0, tokens: 0 };
7064
+ cur.count += count;
7065
+ cur.tokens += tokens;
7066
+ acc.skills.set(n, cur);
7067
+ }
7068
+ acc.agent.messageCount += agg.agent[0];
7069
+ acc.agent.subagentMessages += agg.agent[1];
7070
+ acc.agent.subagentTokens += agg.agent[2];
7071
+ acc.agent.totalTokens += agg.agent[3];
7072
+ acc.agent.userMessageCount += agg.agent[4];
7073
+ for (const [s, c] of agg.sessions) {
7074
+ acc.sessionMessages.set(s, (acc.sessionMessages.get(s) ?? 0) + c);
7075
+ }
7076
+ }
7077
+ function parseClaudeAttrFile(content) {
7078
+ const acc = createAccumulator();
7079
+ const ctx = createFileContext();
7080
+ for (const line of splitLines2(content)) {
7081
+ if (!line) continue;
7082
+ try {
7083
+ processRecord(JSON.parse(line), acc, ctx);
7084
+ } catch {
7085
+ }
7086
+ }
7087
+ return [serializeAcc(acc)];
7088
+ }
7089
+ function parseCodexAttrFile(content) {
7090
+ const acc = createAccumulator();
7091
+ const ctx = createCodexContext();
7092
+ for (const line of splitLines2(content)) {
7093
+ if (!line) continue;
7094
+ try {
7095
+ processCodexRecord(JSON.parse(line), acc, ctx);
7096
+ } catch {
7097
+ }
7097
7098
  }
7099
+ return [serializeAcc(acc)];
7098
7100
  }
7099
- async function readFilesWithCache(opts) {
7100
- const now = opts.now ?? Date.now;
7101
- const cached = await loadCache(opts.cachePath, opts.version);
7102
- const fresh = {};
7103
- const itemsByFile = [];
7104
- let filesRead = 0;
7105
- for (const f of opts.files) {
7106
- let size;
7107
- let mtimeMs;
7101
+ function claudeProjectDirs() {
7102
+ const dirs = [CLAUDE_PROJECTS];
7103
+ const cfg = process.env.CLAUDE_CONFIG_DIR;
7104
+ if (cfg) dirs.push(join5(cfg, "projects"));
7105
+ dirs.push(join5(homedir4(), ".config", "claude", "projects"));
7106
+ return [...new Set(dirs)];
7107
+ }
7108
+ function listTranscripts(dir) {
7109
+ const out = [];
7110
+ const walk = (d) => {
7111
+ if (out.length >= MAX_FILES) return;
7112
+ let entries;
7108
7113
  try {
7109
- const s = await stat(f);
7110
- size = s.size;
7111
- mtimeMs = s.mtimeMs;
7114
+ entries = readdirSync(d, { withFileTypes: true });
7112
7115
  } catch {
7113
- continue;
7116
+ return;
7114
7117
  }
7115
- const hit = cached[f];
7116
- if (hit && hit.size === size && hit.mtimeMs === mtimeMs) {
7117
- fresh[f] = hit;
7118
- itemsByFile.push(hit.items);
7119
- continue;
7118
+ for (const e of entries) {
7119
+ if (out.length >= MAX_FILES) return;
7120
+ const p = join5(d, e.name);
7121
+ if (e.isDirectory()) walk(p);
7122
+ else if (e.isFile() && e.name.endsWith(".jsonl")) {
7123
+ try {
7124
+ out.push({ path: p, mtime: statSync2(p).mtimeMs });
7125
+ } catch {
7126
+ }
7127
+ }
7120
7128
  }
7121
- if (now() > opts.deadline) {
7122
- saveCache(opts.cachePath, opts.version, { ...cached, ...fresh });
7123
- return { itemsByFile: null, filesRead, timedOut: true };
7129
+ };
7130
+ walk(dir);
7131
+ return out.sort((a, b) => b.mtime - a.mtime).slice(0, MAX_FILES).map((f) => f.path);
7132
+ }
7133
+ async function collectAttribution(env = process.env) {
7134
+ const acc = createAccumulator();
7135
+ const deadline = Date.now() + TIME_BUDGET_MS;
7136
+ let complete = true;
7137
+ const mergeInto = (items) => {
7138
+ if (!items) {
7139
+ complete = false;
7140
+ return;
7124
7141
  }
7125
- let content;
7126
- try {
7127
- content = await readFile(f, "utf8");
7128
- } catch {
7129
- continue;
7142
+ for (const perFile of items) for (const agg of perFile) mergeAgg(acc, agg);
7143
+ };
7144
+ try {
7145
+ const claudeFiles = [];
7146
+ for (const dir of claudeProjectDirs()) claudeFiles.push(...listTranscripts(dir));
7147
+ if (claudeFiles.length > 0) {
7148
+ const res = await readFilesWithCache({
7149
+ files: claudeFiles,
7150
+ cachePath: nativeCachePath("attribution-claude", env),
7151
+ version: ATTRIBUTION_CACHE_VERSION,
7152
+ parseFile: parseClaudeAttrFile,
7153
+ deadline
7154
+ });
7155
+ mergeInto(res.itemsByFile);
7156
+ }
7157
+ const codexFiles = listTranscripts(CODEX_SESSIONS);
7158
+ if (codexFiles.length > 0) {
7159
+ const res = await readFilesWithCache({
7160
+ files: codexFiles,
7161
+ cachePath: nativeCachePath("attribution-codex", env),
7162
+ version: ATTRIBUTION_CACHE_VERSION,
7163
+ parseFile: parseCodexAttrFile,
7164
+ deadline
7165
+ });
7166
+ mergeInto(res.itemsByFile);
7130
7167
  }
7131
- const items = opts.parseFile(content, f);
7132
- fresh[f] = { size, mtimeMs, items };
7133
- itemsByFile.push(items);
7134
- filesRead += 1;
7168
+ } catch {
7169
+ complete = false;
7135
7170
  }
7136
- saveCache(opts.cachePath, opts.version, fresh);
7137
- return { itemsByFile, filesRead, timedOut: false };
7171
+ return { ...accumulatorToResult(acc), complete };
7138
7172
  }
7139
7173
 
7140
- // src/native/claude.ts
7141
- function num3(n) {
7174
+ // src/cursor.ts
7175
+ import { spawnSync as spawnSync3 } from "node:child_process";
7176
+ import { existsSync as existsSync3 } from "node:fs";
7177
+ import { createRequire as createRequire2 } from "node:module";
7178
+ import { homedir as homedir5, platform as platform2 } from "node:os";
7179
+ import { join as join7 } from "node:path";
7180
+
7181
+ // src/tokscale.ts
7182
+ import { spawnSync as spawnSync2 } from "node:child_process";
7183
+ import { createRequire } from "node:module";
7184
+ import { dirname as dirname3, join as join6 } from "node:path";
7185
+ var LOOKBACK_DAYS = 30;
7186
+ function num2(n) {
7142
7187
  const v = Math.round(Number(n));
7143
7188
  return Number.isFinite(v) && v > 0 ? v : 0;
7144
7189
  }
7145
- function reqTokens(r) {
7146
- return r.inputTokens + r.outputTokens + r.cacheCreationTokens + r.cacheReadTokens;
7190
+ function numCost(n) {
7191
+ const v = Number(n);
7192
+ return Number.isFinite(v) && v > 0 ? v : 0;
7147
7193
  }
7148
- function localDate(iso) {
7149
- const t = Date.parse(iso);
7150
- if (!Number.isFinite(t)) return null;
7151
- const d = new Date(t);
7152
- const y = d.getFullYear();
7153
- const m = String(d.getMonth() + 1).padStart(2, "0");
7154
- const day = String(d.getDate()).padStart(2, "0");
7155
- return `${y}-${m}-${day}`;
7194
+ function mapTokscaleDay(date, json) {
7195
+ const entries = json?.entries;
7196
+ if (!Array.isArray(entries)) return [];
7197
+ const out = [];
7198
+ for (const e of entries) {
7199
+ const inputTokens = num2(e.input);
7200
+ const outputTokens = num2(e.output) + num2(e.reasoning);
7201
+ const cacheCreationTokens = num2(e.cacheWrite);
7202
+ const cacheReadTokens = num2(e.cacheRead);
7203
+ const costUSD = numCost(e.cost);
7204
+ const total = inputTokens + outputTokens + cacheCreationTokens + cacheReadTokens;
7205
+ if (total === 0 && costUSD === 0) continue;
7206
+ out.push({
7207
+ date,
7208
+ tool: "cursor",
7209
+ model: typeof e.model === "string" && e.model ? e.model : "cursor",
7210
+ inputTokens,
7211
+ outputTokens,
7212
+ cacheCreationTokens,
7213
+ cacheReadTokens,
7214
+ costUSD,
7215
+ origin: "cli",
7216
+ verified: false
7217
+ });
7218
+ }
7219
+ return out;
7156
7220
  }
7157
- var syntheticCounter = 0;
7158
- function parseClaudeLine(raw) {
7159
- const trimmed = raw.trim();
7160
- if (!trimmed) return null;
7161
- let obj;
7221
+ function resolveTokscaleBin() {
7162
7222
  try {
7163
- obj = JSON.parse(trimmed);
7223
+ const require3 = createRequire(import.meta.url);
7224
+ const pkgPath = require3.resolve("tokscale/package.json");
7225
+ const pkg = require3("tokscale/package.json");
7226
+ const rel = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.tokscale ?? "";
7227
+ if (!rel) return null;
7228
+ const binPath = join6(dirname3(pkgPath), rel);
7229
+ if (/\.(c|m)?js$/.test(binPath)) {
7230
+ return { cmd: process.execPath, prefixArgs: [binPath] };
7231
+ }
7232
+ return { cmd: binPath, prefixArgs: [] };
7164
7233
  } catch {
7165
7234
  return null;
7166
7235
  }
7167
- const message = obj.message;
7168
- if (!message || typeof message !== "object") return null;
7169
- const usage = message.usage;
7170
- if (!usage || typeof usage !== "object") return null;
7171
- if (message.role !== void 0 && message.role !== "assistant") return null;
7172
- const date = localDate(String(obj.timestamp ?? ""));
7173
- if (!date) return null;
7174
- const tsParsed = Date.parse(String(obj.timestamp ?? ""));
7175
- const ts = Number.isFinite(tsParsed) ? tsParsed : 0;
7176
- const messageId = typeof message.id === "string" ? message.id : "";
7177
- const requestId = typeof obj.requestId === "string" ? obj.requestId : "";
7178
- const hasRealId = messageId !== "" || requestId !== "";
7179
- const key = hasRealId ? `${messageId}|${requestId}` : `synthetic|${date}|${syntheticCounter += 1}`;
7180
- return {
7181
- key,
7182
- hasRealId,
7183
- date,
7184
- ts,
7185
- model: typeof message.model === "string" ? message.model : "unknown",
7186
- inputTokens: num3(usage.input_tokens),
7187
- outputTokens: num3(usage.output_tokens),
7188
- cacheCreationTokens: num3(usage.cache_creation_input_tokens),
7189
- cacheReadTokens: num3(usage.cache_read_input_tokens)
7190
- };
7191
7236
  }
7192
- function accumulateClaudeLines(acc, lines) {
7193
- for (const line of lines) {
7194
- const r = parseClaudeLine(line);
7195
- if (!r) continue;
7196
- const prev = acc.get(r.key);
7197
- if (!prev || reqTokens(r) > reqTokens(prev)) acc.set(r.key, r);
7237
+ function runTokscaleDay(bin, day) {
7238
+ const res = spawnSync2(
7239
+ bin.cmd,
7240
+ [
7241
+ ...bin.prefixArgs,
7242
+ "--client",
7243
+ "cursor",
7244
+ "--json",
7245
+ "--since",
7246
+ day,
7247
+ "--until",
7248
+ day,
7249
+ "--group-by",
7250
+ "model",
7251
+ "--no-spinner"
7252
+ ],
7253
+ { encoding: "utf8", maxBuffer: 32 * 1024 * 1024, timeout: 6e4 }
7254
+ );
7255
+ if (res.status !== 0 || !res.stdout) return null;
7256
+ try {
7257
+ return JSON.parse(res.stdout);
7258
+ } catch {
7259
+ return null;
7198
7260
  }
7199
7261
  }
7200
- function finalizeClaudeEntries(acc) {
7201
- const byDayModel = /* @__PURE__ */ new Map();
7202
- for (const r of acc.values()) {
7203
- const k = `${r.date}|${r.model}`;
7204
- let b = byDayModel.get(k);
7205
- if (!b) {
7206
- b = {
7207
- date: r.date,
7208
- model: r.model,
7209
- inputTokens: 0,
7210
- outputTokens: 0,
7211
- cacheCreationTokens: 0,
7212
- cacheReadTokens: 0,
7213
- requestCount: 0
7214
- };
7215
- byDayModel.set(k, b);
7262
+ function collectCursorViaTokscale(lookbackDays = LOOKBACK_DAYS) {
7263
+ const bin = resolveTokscaleBin();
7264
+ if (!bin) return [];
7265
+ const today = /* @__PURE__ */ new Date();
7266
+ const day = (offset) => {
7267
+ const d = new Date(today.getTime() - offset * 864e5);
7268
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
7269
+ };
7270
+ if (mapTokscaleDay(day(0), runTokscaleDay(bin, day(0))).length === 0) {
7271
+ if (mapTokscaleDay(day(1), runTokscaleDay(bin, day(1))).length === 0) {
7272
+ return [];
7216
7273
  }
7217
- b.inputTokens += r.inputTokens;
7218
- b.outputTokens += r.outputTokens;
7219
- b.cacheCreationTokens += r.cacheCreationTokens;
7220
- b.cacheReadTokens += r.cacheReadTokens;
7221
- if (r.hasRealId) b.requestCount += 1;
7222
- }
7223
- const entries = [];
7224
- for (const b of byDayModel.values()) {
7225
- const tokens = b.inputTokens + b.outputTokens + b.cacheCreationTokens + b.cacheReadTokens;
7226
- if (tokens === 0) continue;
7227
- entries.push({
7228
- date: b.date,
7229
- tool: "claude",
7230
- model: b.model,
7231
- inputTokens: b.inputTokens,
7232
- outputTokens: b.outputTokens,
7233
- cacheCreationTokens: b.cacheCreationTokens,
7234
- cacheReadTokens: b.cacheReadTokens,
7235
- costUSD: estimateCostUSD(b.model, b),
7236
- origin: "cli",
7237
- verified: false,
7238
- requestCount: b.requestCount
7239
- });
7240
- }
7241
- return entries;
7242
- }
7243
- function resolveClaudeConfigRoots(env = process.env) {
7244
- const override = env.CLAUDE_CONFIG_DIR;
7245
- return override ? override.split(",").map((s) => s.trim()).filter(Boolean) : [join7(homedir5(), ".claude"), join7(homedir5(), ".config", "claude")];
7246
- }
7247
- function resolveClaudeProjectDirs(env = process.env) {
7248
- return resolveClaudeConfigRoots(env).map((r) => join7(r, "projects"));
7249
- }
7250
- async function listJsonl(dir) {
7251
- let dirents;
7252
- try {
7253
- dirents = await readdir(dir, { withFileTypes: true });
7254
- } catch {
7255
- return [];
7256
7274
  }
7257
7275
  const out = [];
7258
- for (const d of dirents) {
7259
- const full = join7(dir, d.name);
7260
- if (d.isDirectory()) {
7261
- out.push(...await listJsonl(full));
7262
- } else if (d.isFile() && d.name.endsWith(".jsonl")) {
7263
- out.push(full);
7264
- }
7276
+ for (let i = 0; i < lookbackDays; i++) {
7277
+ const d = day(i);
7278
+ out.push(...mapTokscaleDay(d, runTokscaleDay(bin, d)));
7265
7279
  }
7266
7280
  return out;
7267
7281
  }
7268
- var NATIVE_READ_BUDGET_MS = 45e3;
7269
- var CLAUDE_CACHE_VERSION = 1;
7270
- function toCached(r) {
7271
- return [
7272
- r.key,
7273
- r.hasRealId ? 1 : 0,
7274
- r.date,
7275
- r.model,
7276
- r.inputTokens,
7277
- r.outputTokens,
7278
- r.cacheCreationTokens,
7279
- r.cacheReadTokens
7280
- ];
7281
- }
7282
- function fromCached(t) {
7283
- return {
7284
- key: t[0],
7285
- hasRealId: t[1] === 1,
7286
- date: t[2],
7287
- ts: 0,
7288
- model: t[3],
7289
- inputTokens: t[4],
7290
- outputTokens: t[5],
7291
- cacheCreationTokens: t[6],
7292
- cacheReadTokens: t[7]
7293
- };
7282
+
7283
+ // src/cursor.ts
7284
+ var EVENTS_URL = "https://cursor.com/api/dashboard/get-filtered-usage-events";
7285
+ function cursorDbPath() {
7286
+ const home = homedir5();
7287
+ const os = platform2();
7288
+ const p = os === "darwin" ? join7(home, "Library", "Application Support", "Cursor", "User", "globalStorage", "state.vscdb") : os === "win32" ? join7(process.env.APPDATA ?? join7(home, "AppData", "Roaming"), "Cursor", "User", "globalStorage", "state.vscdb") : join7(process.env.XDG_CONFIG_HOME ?? join7(home, ".config"), "Cursor", "User", "globalStorage", "state.vscdb");
7289
+ return existsSync3(p) ? p : null;
7294
7290
  }
7295
- function parseFileToCache(content, path) {
7296
- const acc = /* @__PURE__ */ new Map();
7297
- accumulateClaudeLines(acc, splitLines(content));
7298
- let synIndex = 0;
7299
- return [...acc.values()].map(
7300
- (r) => toCached(
7301
- r.hasRealId ? r : { ...r, key: `synthetic|${path}|${synIndex += 1}` }
7302
- )
7303
- );
7291
+ function readCursorToken(db) {
7292
+ const require3 = createRequire2(import.meta.url);
7293
+ try {
7294
+ const { DatabaseSync } = require3("node:sqlite");
7295
+ const d = new DatabaseSync(db, { readOnly: true });
7296
+ const row = d.prepare("SELECT value FROM ItemTable WHERE key = ?").get("cursorAuth/accessToken");
7297
+ d.close();
7298
+ if (row?.value) return String(row.value);
7299
+ } catch {
7300
+ }
7301
+ try {
7302
+ const res = spawnSync3(
7303
+ "sqlite3",
7304
+ [db, "SELECT value FROM ItemTable WHERE key='cursorAuth/accessToken';"],
7305
+ { encoding: "utf8", timeout: 1e4 }
7306
+ );
7307
+ const out = res.stdout?.trim();
7308
+ if (res.status === 0 && out) return out;
7309
+ } catch {
7310
+ }
7311
+ return null;
7304
7312
  }
7305
- function* splitLines(content) {
7306
- let start = 0;
7307
- for (let i = 0; i < content.length; i++) {
7308
- if (content[i] === "\n") {
7309
- yield content.slice(start, i);
7310
- start = i + 1;
7311
- }
7313
+ function cursorCookie(token) {
7314
+ try {
7315
+ const part = token.split(".")[1];
7316
+ if (!part) return null;
7317
+ const json = JSON.parse(
7318
+ Buffer.from(part, "base64url").toString("utf8")
7319
+ );
7320
+ if (!json.sub) return null;
7321
+ return `WorkosCursorSessionToken=${json.sub}%3A%3A${token}`;
7322
+ } catch {
7323
+ return null;
7312
7324
  }
7313
- if (start < content.length) yield content.slice(start);
7314
7325
  }
7315
- async function collectClaudeNative(env = process.env, opts = {}) {
7316
- const dirs = resolveClaudeProjectDirs(env);
7317
- const files = [];
7318
- for (const dir of dirs) files.push(...await listJsonl(dir));
7319
- if (files.length === 0) return { entries: [], found: false, filesScanned: 0 };
7320
- const now = opts.now ?? Date.now;
7321
- const res = await readFilesWithCache({
7322
- files,
7323
- cachePath: opts.cachePath ?? nativeCachePath("claude", env),
7324
- version: CLAUDE_CACHE_VERSION,
7325
- parseFile: parseFileToCache,
7326
- deadline: now() + (opts.budgetMs ?? NATIVE_READ_BUDGET_MS),
7327
- now
7328
- });
7329
- if (!res.itemsByFile) {
7330
- return {
7331
- entries: [],
7332
- found: false,
7333
- filesScanned: res.filesRead,
7334
- timedOut: true
7326
+ function num3(n) {
7327
+ const v = Math.round(Number(n));
7328
+ return Number.isFinite(v) && v > 0 ? v : 0;
7329
+ }
7330
+ function mapCursorEvents(events) {
7331
+ const byDay = /* @__PURE__ */ new Map();
7332
+ const byHour = /* @__PURE__ */ new Map();
7333
+ for (const e of events) {
7334
+ const tu = e.tokenUsage;
7335
+ const ms = Number(e.timestamp);
7336
+ if (!tu || !Number.isFinite(ms)) continue;
7337
+ const d = new Date(ms);
7338
+ const date = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
7339
+ const model = e.model || "cursor";
7340
+ const input = num3(tu.inputTokens);
7341
+ const output = num3(tu.outputTokens);
7342
+ const cacheWrite = num3(tu.cacheWriteTokens);
7343
+ const cacheRead = num3(tu.cacheReadTokens);
7344
+ const cost = Math.max(0, (Number(tu.totalCents) || 0) / 100);
7345
+ const total = input + output + cacheWrite + cacheRead;
7346
+ if (total === 0 && cost === 0) continue;
7347
+ const key = `${date}|${model}`;
7348
+ const day = byDay.get(key) ?? {
7349
+ date,
7350
+ tool: "cursor",
7351
+ model,
7352
+ inputTokens: 0,
7353
+ outputTokens: 0,
7354
+ cacheCreationTokens: 0,
7355
+ cacheReadTokens: 0,
7356
+ costUSD: 0,
7357
+ origin: "cli",
7358
+ verified: false
7335
7359
  };
7360
+ day.inputTokens += input;
7361
+ day.outputTokens += output;
7362
+ day.cacheCreationTokens += cacheWrite;
7363
+ day.cacheReadTokens += cacheRead;
7364
+ day.costUSD += cost;
7365
+ byDay.set(key, day);
7366
+ const hour = new Date(
7367
+ Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours())
7368
+ ).toISOString();
7369
+ const blk = byHour.get(hour) ?? { startTime: hour, totalTokens: 0, costUSD: 0 };
7370
+ blk.totalTokens += total;
7371
+ blk.costUSD += cost;
7372
+ byHour.set(hour, blk);
7336
7373
  }
7337
- const acc = /* @__PURE__ */ new Map();
7338
- for (const items of res.itemsByFile) {
7339
- for (const t of items) {
7340
- const r = fromCached(t);
7341
- const prev = acc.get(r.key);
7342
- if (!prev || reqTokens(r) > reqTokens(prev)) acc.set(r.key, r);
7374
+ const entries = [...byDay.values()].map((e) => ({
7375
+ ...e,
7376
+ costUSD: Number(e.costUSD.toFixed(4))
7377
+ }));
7378
+ const blocks = [...byHour.values()].map((b) => ({
7379
+ ...b,
7380
+ costUSD: Number(b.costUSD.toFixed(4))
7381
+ }));
7382
+ return { entries, blocks };
7383
+ }
7384
+ async function fetchCursorEvents(cookie, maxPages = 30, pageSize = 500) {
7385
+ const all = [];
7386
+ for (let page = 1; page <= maxPages; page++) {
7387
+ const res = await fetch(EVENTS_URL, {
7388
+ method: "POST",
7389
+ headers: {
7390
+ "Content-Type": "application/json",
7391
+ Origin: "https://cursor.com",
7392
+ Cookie: cookie
7393
+ },
7394
+ body: JSON.stringify({ page, pageSize }),
7395
+ signal: AbortSignal.timeout(2e4)
7396
+ });
7397
+ if (!res.ok) {
7398
+ throw new Error(`cursor usage page ${page} failed (HTTP ${res.status})`);
7343
7399
  }
7400
+ const body = await res.json();
7401
+ const batch = body.usageEventsDisplay ?? [];
7402
+ all.push(...batch);
7403
+ if (batch.length < pageSize) break;
7344
7404
  }
7345
- return {
7346
- entries: finalizeClaudeEntries(acc),
7347
- found: true,
7348
- filesScanned: res.filesRead
7349
- };
7405
+ return all;
7350
7406
  }
7351
- async function collectClaudeRequests(env = process.env, opts = {}) {
7352
- const dirs = resolveClaudeProjectDirs(env);
7353
- const files = [];
7354
- for (const dir of dirs) files.push(...await listJsonl(dir));
7355
- if (files.length === 0) return { requests: [], found: false };
7356
- const now = opts.now ?? Date.now;
7357
- const deadline = now() + (opts.budgetMs ?? NATIVE_READ_BUDGET_MS);
7358
- const acc = /* @__PURE__ */ new Map();
7359
- for (const f of files) {
7360
- if (now() > deadline) {
7361
- return { requests: [...acc.values()], found: true, timedOut: true };
7362
- }
7363
- let content;
7364
- try {
7365
- content = await readFile2(f, "utf8");
7366
- } catch {
7367
- continue;
7407
+ async function collectCursor() {
7408
+ try {
7409
+ const db = cursorDbPath();
7410
+ const token = db ? readCursorToken(db) : null;
7411
+ const cookie = token ? cursorCookie(token) : null;
7412
+ if (cookie) {
7413
+ const events = await fetchCursorEvents(cookie);
7414
+ const { entries, blocks } = mapCursorEvents(events);
7415
+ if (entries.length > 0) return { entries, blocks, found: true };
7368
7416
  }
7369
- accumulateClaudeLines(acc, splitLines(content));
7417
+ } catch {
7370
7418
  }
7371
- return { requests: [...acc.values()], found: true };
7419
+ try {
7420
+ const entries = collectCursorViaTokscale();
7421
+ if (entries.length > 0) return { entries, blocks: [], found: true };
7422
+ } catch {
7423
+ }
7424
+ return { entries: [], blocks: [], found: false };
7372
7425
  }
7373
7426
 
7374
7427
  // src/native/codex.ts
@@ -7524,7 +7577,7 @@ async function listJsonl2(dir) {
7524
7577
  }
7525
7578
  return out;
7526
7579
  }
7527
- function* splitLines2(content) {
7580
+ function* splitLines3(content) {
7528
7581
  let start = 0;
7529
7582
  for (let i = 0; i < content.length; i++) {
7530
7583
  if (content[i] === "\n") {
@@ -7567,7 +7620,7 @@ async function collectCodexNative(env = process.env, opts = {}) {
7567
7620
  files,
7568
7621
  cachePath: opts.cachePath ?? nativeCachePath("codex", env),
7569
7622
  version: CODEX_CACHE_VERSION,
7570
- parseFile: (content) => parseCodexRollout(splitLines2(content)).map(toCachedSession),
7623
+ parseFile: (content) => parseCodexRollout(splitLines3(content)).map(toCachedSession),
7571
7624
  deadline: now() + (opts.budgetMs ?? NATIVE_READ_BUDGET_MS2),
7572
7625
  now
7573
7626
  });
@@ -7647,6 +7700,93 @@ async function loadLivePricing(env = process.env, now = Date.now, cachePath = pr
7647
7700
  return "baked";
7648
7701
  }
7649
7702
 
7703
+ // src/provenance-store.ts
7704
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync3, renameSync as renameSync4, writeFileSync as writeFileSync4 } from "node:fs";
7705
+ import { dirname as dirname5, join as join10 } from "node:path";
7706
+ var PROVENANCE_STORE_VERSION = 1;
7707
+ var KEY_SEP = "|";
7708
+ var keyOf = (date, tool) => `${date}${KEY_SEP}${tool}`;
7709
+ function entryTokens(e) {
7710
+ return e.inputTokens + e.outputTokens + e.cacheCreationTokens + e.cacheReadTokens;
7711
+ }
7712
+ function provenanceStorePath(env = process.env) {
7713
+ const override = env.WHOBURNEDMORE_CONFIG_DIR?.trim();
7714
+ const dir = override || defaultConfigDir();
7715
+ return join10(dir, "native-cache-provenance.json");
7716
+ }
7717
+ function loadProvenanceStore(path) {
7718
+ try {
7719
+ const parsed = JSON.parse(readFileSync3(path, "utf8"));
7720
+ if (parsed && parsed.v === PROVENANCE_STORE_VERSION && parsed.req && typeof parsed.req === "object") {
7721
+ return {
7722
+ v: PROVENANCE_STORE_VERSION,
7723
+ req: parsed.req,
7724
+ agent: parsed.agent
7725
+ };
7726
+ }
7727
+ } catch {
7728
+ }
7729
+ return null;
7730
+ }
7731
+ function saveProvenanceStore(path, store) {
7732
+ try {
7733
+ mkdirSync4(dirname5(path), { recursive: true });
7734
+ const tmp = `${path}.tmp-${process.pid}`;
7735
+ writeFileSync4(tmp, JSON.stringify(store));
7736
+ renameSync4(tmp, path);
7737
+ } catch {
7738
+ }
7739
+ }
7740
+ function reconcileProvenance(entries, agent, complete, store) {
7741
+ const prevReq = store?.req ?? {};
7742
+ const prevAgent = store?.agent;
7743
+ const curReq = /* @__PURE__ */ new Map();
7744
+ for (const e of entries) {
7745
+ if (e.requestCount === void 0) continue;
7746
+ const k = keyOf(e.date, e.tool);
7747
+ curReq.set(k, (curReq.get(k) ?? 0) + e.requestCount);
7748
+ }
7749
+ const nextReq = { ...prevReq };
7750
+ let outEntries = entries;
7751
+ if (complete) {
7752
+ for (const [k, v] of curReq) nextReq[k] = v;
7753
+ } else {
7754
+ for (const [k, v] of curReq) nextReq[k] = Math.max(prevReq[k] ?? 0, v);
7755
+ const heaviest = /* @__PURE__ */ new Map();
7756
+ for (const e of entries) {
7757
+ const k = keyOf(e.date, e.tool);
7758
+ const cur = heaviest.get(k);
7759
+ if (!cur || entryTokens(e) > entryTokens(cur)) heaviest.set(k, e);
7760
+ }
7761
+ let cloned = null;
7762
+ for (const [k, stored] of Object.entries(prevReq)) {
7763
+ const cur = curReq.get(k) ?? 0;
7764
+ if (stored <= cur) continue;
7765
+ const target = heaviest.get(k);
7766
+ if (!target) continue;
7767
+ if (!cloned) cloned = [...entries];
7768
+ const idx = cloned.indexOf(target);
7769
+ cloned[idx] = {
7770
+ ...target,
7771
+ requestCount: (target.requestCount ?? 0) + (stored - cur)
7772
+ };
7773
+ }
7774
+ if (cloned) outEntries = cloned;
7775
+ }
7776
+ let outAgent = agent;
7777
+ let nextAgent = prevAgent;
7778
+ if (complete && agent.messageCount > 0) {
7779
+ nextAgent = agent;
7780
+ } else if (!complete && prevAgent && prevAgent.totalTokens > agent.totalTokens) {
7781
+ outAgent = prevAgent;
7782
+ }
7783
+ return {
7784
+ entries: outEntries,
7785
+ agent: outAgent,
7786
+ store: { v: PROVENANCE_STORE_VERSION, req: nextReq, agent: nextAgent }
7787
+ };
7788
+ }
7789
+
7650
7790
  // src/collect.ts
7651
7791
  var execFileAsync = promisify(execFile);
7652
7792
  var SOURCES = [
@@ -7787,7 +7927,7 @@ function resolveCcusageBin() {
7787
7927
  const pkgPath = require3.resolve("ccusage/package.json");
7788
7928
  const pkg = require3("ccusage/package.json");
7789
7929
  const rel = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.ccusage ?? "ccusage";
7790
- const binPath = join10(dirname5(pkgPath), rel);
7930
+ const binPath = join11(dirname6(pkgPath), rel);
7791
7931
  if (/\.(c|m)?js$/.test(binPath)) {
7792
7932
  return { cmd: process.execPath, prefixArgs: [binPath] };
7793
7933
  }
@@ -7814,7 +7954,7 @@ function dedupeDaily(entries) {
7814
7954
  }
7815
7955
  return [...byKey.values()];
7816
7956
  }
7817
- function entryTokens(e) {
7957
+ function entryTokens2(e) {
7818
7958
  return e.inputTokens + e.outputTokens + e.cacheCreationTokens + e.cacheReadTokens;
7819
7959
  }
7820
7960
  function capByTokens(rows, max, tokens) {
@@ -7883,6 +8023,9 @@ async function runCcusage(cmd, args, env) {
7883
8023
  return (await runCcusageOnce(cmd, args, env)).json;
7884
8024
  }
7885
8025
  var COLLECT_STAGES = SOURCES.length + 4;
8026
+ function isAuthoritativeScan(attributionComplete, nativeClaude, nativeCodex) {
8027
+ return attributionComplete && nativeClaude.timedOut !== true && nativeCodex.timedOut !== true;
8028
+ }
7886
8029
  async function collectAll(onProgress) {
7887
8030
  await loadLivePricing().catch(() => {
7888
8031
  });
@@ -7890,10 +8033,10 @@ async function collectAll(onProgress) {
7890
8033
  let done = 0;
7891
8034
  const tick = () => onProgress?.(++done, COLLECT_STAGES, "");
7892
8035
  const nativeClaudeTask = collectClaudeNative().catch(
7893
- () => ({ entries: [], found: false, filesScanned: 0 })
8036
+ () => ({ entries: [], found: false, filesScanned: 0, timedOut: true })
7894
8037
  );
7895
8038
  const nativeCodexTask = collectCodexNative().catch(
7896
- () => ({ entries: [], found: false, filesScanned: 0 })
8039
+ () => ({ entries: [], found: false, filesScanned: 0, timedOut: true })
7897
8040
  );
7898
8041
  const sourceTasks = SOURCES.map(async (source) => {
7899
8042
  const env = source === "claude" ? ccusageClaudeEnv() : void 0;
@@ -7958,19 +8101,28 @@ async function collectAll(onProgress) {
7958
8101
  ...messageCount ? { messageCount } : {}
7959
8102
  };
7960
8103
  });
8104
+ const scanComplete = isAuthoritativeScan(complete, nativeClaude, nativeCodex);
8105
+ const storePath = provenanceStorePath();
8106
+ const reconciled = reconcileProvenance(
8107
+ dedupeDaily(entries),
8108
+ agent,
8109
+ scanComplete,
8110
+ loadProvenanceStore(storePath)
8111
+ );
8112
+ saveProvenanceStore(storePath, reconciled.store);
7961
8113
  return {
7962
8114
  // Cap each array to the server's accepted maximum (the shared SubmitPayload
7963
8115
  // schema: entries ≤ 20000, sessions/blocks ≤ 10000), keeping the
7964
8116
  // highest-token rows. Without this, a power user with >10000 distinct sessions
7965
8117
  // would have their ENTIRE submit rejected with a 400 instead of a capped one.
7966
8118
  // tools/skills are already bounded upstream (attribution caps).
7967
- entries: capByTokens(dedupeDaily(entries), 2e4, entryTokens),
7968
- sessions: capByTokens(dedupedSessions, 1e4, entryTokens),
8119
+ entries: capByTokens(reconciled.entries, 2e4, entryTokens2),
8120
+ sessions: capByTokens(dedupedSessions, 1e4, entryTokens2),
7969
8121
  blocks: capByTokens(dedupeBlocks(blocks), 1e4, (b) => b.totalTokens),
7970
8122
  toolsFound,
7971
8123
  tools,
7972
8124
  skills,
7973
- agent,
8125
+ agent: reconciled.agent,
7974
8126
  attributionComplete: complete
7975
8127
  };
7976
8128
  }
@@ -8375,9 +8527,9 @@ async function confirm(question) {
8375
8527
  }
8376
8528
  function showLocalDashboard(payload) {
8377
8529
  const dir = defaultConfigDir();
8378
- mkdirSync4(dir, { recursive: true });
8379
- const file = join11(dir, "dashboard.html");
8380
- writeFileSync4(
8530
+ mkdirSync5(dir, { recursive: true });
8531
+ const file = join12(dir, "dashboard.html");
8532
+ writeFileSync5(
8381
8533
  file,
8382
8534
  renderDashboardHtml(payload.entries, /* @__PURE__ */ new Date(), { webBaseUrl: webBase() })
8383
8535
  );