@brainervirus/workit-cursor 8.22.1 → 8.22.3

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.
@@ -958,8 +958,6 @@ var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/
958
958
  var base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;
959
959
  var httpProtocol = /^https?$/;
960
960
  var e164 = /^\+[1-9]\d{6,14}$/;
961
- var creditCard = /^\d(?:[ -]?\d){11,18}$/;
962
- var iban = /^[A-Z]{2}(?!00|01|99)\d{2}[A-Z0-9]{11,30}$/;
963
961
  var dateSource = `(?:(?:\\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])))`;
964
962
  function anchor(source) {
965
963
  return new RegExp(`^${source}$`);
@@ -1805,41 +1803,6 @@ var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => {
1805
1803
  def.pattern ?? (def.pattern = e164);
1806
1804
  $ZodStringFormat.init(inst, def);
1807
1805
  });
1808
- var CC_SANITIZE = /[- ]/g;
1809
- function isLuhnAlgo(digits) {
1810
- let length = digits.length;
1811
- let bit = 1;
1812
- let sum = 0;
1813
- while (length) {
1814
- const value = digits.charCodeAt(--length) - 48;
1815
- bit ^= 1;
1816
- sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value;
1817
- }
1818
- return sum % 10 === 0;
1819
- }
1820
- function isValidCreditCard(input) {
1821
- if (!creditCard.test(input))
1822
- return false;
1823
- return isLuhnAlgo(input.replace(CC_SANITIZE, ""));
1824
- }
1825
- function isIso7064Mod97(iban2) {
1826
- let remainder = 0;
1827
- const len = iban2.length;
1828
- for (let i = 4;i < len; i++) {
1829
- const code = iban2.charCodeAt(i);
1830
- remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;
1831
- }
1832
- for (let i = 0;i < 4; i++) {
1833
- const code = iban2.charCodeAt(i);
1834
- remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;
1835
- }
1836
- return remainder === 1;
1837
- }
1838
- function isValidIBAN(input) {
1839
- if (!iban.test(input))
1840
- return false;
1841
- return isIso7064Mod97(input);
1842
- }
1843
1806
  function isValidJWT(token, algorithm = null) {
1844
1807
  try {
1845
1808
  const tokensParts = token.split(".");
@@ -3152,9 +3115,6 @@ function settle(inst, answer) {
3152
3115
  recursive.set(inst, answer === PROVEN);
3153
3116
  return answer;
3154
3117
  }
3155
- function isRecursiveSchema(inst) {
3156
- return isRecursive(inst, new Set, true) !== NONE;
3157
- }
3158
3118
  function bucketFor(state, inst) {
3159
3119
  let bucket = state.buckets.get(inst);
3160
3120
  if (!bucket) {
@@ -3441,1604 +3401,6 @@ function registry() {
3441
3401
  }
3442
3402
  (_a2 = globalThis).__zod_globalRegistry ?? (_a2.__zod_globalRegistry = registry());
3443
3403
  var globalRegistry = globalThis.__zod_globalRegistry;
3444
- // node_modules/zod/v4/core/compile.js
3445
- var INVALID = Symbol.for("zod.compile.invalid");
3446
- var FALLBACK_FLAG = Symbol.for("zod.compile.fallback");
3447
-
3448
- class ZodCompileAsyncError extends Error {
3449
- constructor(message = "z.compile does not support async refinements, transforms, or checks") {
3450
- super(message);
3451
- this.name = "ZodCompileAsyncError";
3452
- }
3453
- }
3454
-
3455
- class ZodCompileUnsupportedError extends Error {
3456
- constructor(feature, islandable = true) {
3457
- super(`z.compile does not support ${feature}; this schema must use the runtime parser`);
3458
- this.name = "ZodCompileUnsupportedError";
3459
- this.islandable = islandable;
3460
- }
3461
- }
3462
- function compileValidator(schema, parser) {
3463
- try {
3464
- return compileFn(schema, { assertOnly: true });
3465
- } catch {
3466
- return parser;
3467
- }
3468
- }
3469
- function compile(schema, options) {
3470
- try {
3471
- const parser = compileFn(schema);
3472
- const clone = withParser(schema, parser);
3473
- clone._zod.bag.validator = compileValidator(schema, parser);
3474
- return clone;
3475
- } catch (err) {
3476
- if (options?.strict)
3477
- throw err;
3478
- return schema;
3479
- }
3480
- }
3481
- function withParser(schema, parser) {
3482
- if (isRecursiveSchema(schema)) {
3483
- throw new ZodCompileUnsupportedError("a schema whose subtree contains a reference cycle");
3484
- }
3485
- const clone2 = clone(schema);
3486
- const liveRun = schema._zod.run;
3487
- const originalRun = liveRun.__originalRun ?? liveRun;
3488
- const wrapped = (payload, ctx) => {
3489
- if (ctx?.async || ctx?.direction === "backward" || ctx?.skipChecks || ctx?.[FALLBACK_FLAG]) {
3490
- return originalRun(payload, ctx);
3491
- }
3492
- if (ctx && isBackEdge(ctx, payload.value)) {
3493
- return originalRun(payload, ctx);
3494
- }
3495
- const out = parser(payload.value);
3496
- if (out !== INVALID) {
3497
- payload.value = out;
3498
- return payload;
3499
- }
3500
- if (ctx)
3501
- ctx[FALLBACK_FLAG] = true;
3502
- return originalRun(payload, ctx);
3503
- };
3504
- wrapped.__originalRun = originalRun;
3505
- clone2._zod.bag.fallbackRun = originalRun;
3506
- clone2._zod.bag.validator = parser;
3507
- clone2._zod.run = wrapped;
3508
- if (!liveRun.__originalRun)
3509
- installCompiledUserMethods(clone2, schema, parser);
3510
- return clone2;
3511
- }
3512
- function installCompiledUserMethods(target, source, parser) {
3513
- const targetAny = target;
3514
- const sourceAny = source;
3515
- if (typeof sourceAny.safeParse === "function") {
3516
- const originalSafeParse = sourceAny.safeParse;
3517
- targetAny.safeParse = (data, params) => {
3518
- const out = parser(data);
3519
- if (out !== INVALID) {
3520
- return { success: true, data: out };
3521
- }
3522
- return originalSafeParse(data, params);
3523
- };
3524
- }
3525
- if (typeof sourceAny.parse === "function") {
3526
- const originalParse = sourceAny.parse;
3527
- targetAny.parse = (data, params) => {
3528
- const out = parser(data);
3529
- if (out !== INVALID) {
3530
- return out;
3531
- }
3532
- return originalParse(data, params);
3533
- };
3534
- }
3535
- }
3536
- function compileFn(schema, options) {
3537
- let recursive = true;
3538
- try {
3539
- recursive = isRecursiveSchema(schema);
3540
- } catch {}
3541
- if (recursive) {
3542
- throw new ZodCompileUnsupportedError("a schema whose subtree contains a reference cycle");
3543
- }
3544
- const ctx = {
3545
- constants: new Map,
3546
- constantCounter: 0,
3547
- varCounter: 0,
3548
- definite: true
3549
- };
3550
- const doc = new Doc(["input"]);
3551
- const outputAccessor = generateCheck(doc, ctx, schema, "input", !options?.assertOnly);
3552
- doc.write(outputAccessor === null ? `return true;` : `return ${outputAccessor};`);
3553
- const constantNames = ["INVALID", ...ctx.constants.keys()];
3554
- const constantValues = [INVALID, ...ctx.constants.values()];
3555
- const code = doc.content.join(`
3556
- `);
3557
- const fullCode = options?.debug ? constantNames.length > 0 ? `// Constants: ${constantNames.join(", ")}
3558
- ${code}` : code : "";
3559
- const F = Function;
3560
- const factoryCode = `return (input) => {
3561
- ${code}
3562
- }`;
3563
- let fn;
3564
- try {
3565
- const factory = new F(...constantNames, factoryCode);
3566
- fn = factory(...constantValues);
3567
- } catch (err) {
3568
- throw new ZodCompileUnsupportedError(`this schema (generated code failed to evaluate: ${err.message})`);
3569
- }
3570
- if (options?.debug) {
3571
- fn.code = fullCode;
3572
- }
3573
- fn.definite = ctx.definite;
3574
- return fn;
3575
- }
3576
- function addConstant(ctx, value) {
3577
- for (const [name, v] of ctx.constants) {
3578
- if (v === value)
3579
- return name;
3580
- }
3581
- const name = `c${ctx.constantCounter++}`;
3582
- ctx.constants.set(name, value);
3583
- return name;
3584
- }
3585
- function addUserConstant(ctx, fn) {
3586
- ctx.definite = false;
3587
- return addConstant(ctx, fn);
3588
- }
3589
- function newVar(ctx) {
3590
- return `v${ctx.varCounter++}`;
3591
- }
3592
- function runtimeRun(schema, value) {
3593
- const result = schema._zod.run({ value, issues: [] }, {});
3594
- if (result && typeof result.then === "function")
3595
- return INVALID;
3596
- const r = result;
3597
- return r.issues.length === 0 ? r.value : INVALID;
3598
- }
3599
- function compileChild(doc, ctx, schema, accessor, needsValue = true) {
3600
- const contentLen = doc.content.length;
3601
- const constantCount = ctx.constants.size;
3602
- const constantCounter = ctx.constantCounter;
3603
- const varCounter = ctx.varCounter;
3604
- try {
3605
- return generateCheck(doc, ctx, schema, accessor, needsValue);
3606
- } catch (err) {
3607
- if (!(err instanceof ZodCompileUnsupportedError) || !err.islandable)
3608
- throw err;
3609
- doc.content.length = contentLen;
3610
- if (ctx.constants.size > constantCount) {
3611
- const trailing = Array.from(ctx.constants.keys()).slice(constantCount);
3612
- for (const k of trailing)
3613
- ctx.constants.delete(k);
3614
- }
3615
- ctx.constantCounter = constantCounter;
3616
- ctx.varCounter = varCounter;
3617
- return emitRuntimeIsland(doc, ctx, schema, accessor);
3618
- }
3619
- }
3620
- function emitRuntimeIsland(doc, ctx, schema, accessor) {
3621
- ctx.definite = false;
3622
- const schemaConst = addConstant(ctx, schema);
3623
- const runConst = addConstant(ctx, runtimeRun);
3624
- const outVar = newVar(ctx);
3625
- doc.write(`const ${outVar} = ${runConst}(${schemaConst}, ${accessor});`);
3626
- doc.write(`if (${outVar} === INVALID) return INVALID;`);
3627
- return outVar;
3628
- }
3629
- var WHEN_DEFAULTED_CHECKS = new Set([
3630
- "max_size",
3631
- "min_size",
3632
- "size_equals",
3633
- "max_length",
3634
- "min_length",
3635
- "length_equals"
3636
- ]);
3637
- function generateChecks(doc, ctx, schema, accessor) {
3638
- const schemaChecks = schema._zod.def.checks;
3639
- if (!schemaChecks || schemaChecks.length === 0)
3640
- return accessor;
3641
- let currentAccessor = accessor;
3642
- for (const check of schemaChecks) {
3643
- const def = check._zod.def;
3644
- if (def.when && !WHEN_DEFAULTED_CHECKS.has(def.check)) {
3645
- throw new ZodCompileUnsupportedError(`check with a custom "when" condition`);
3646
- }
3647
- switch (def.check) {
3648
- case "greater_than":
3649
- generateGreaterThanCheck(doc, ctx, def, currentAccessor);
3650
- break;
3651
- case "less_than":
3652
- generateLessThanCheck(doc, ctx, def, currentAccessor);
3653
- break;
3654
- case "multiple_of":
3655
- generateMultipleOfCheck(doc, ctx, def, currentAccessor);
3656
- break;
3657
- case "number_format":
3658
- generateNumberFormatCheck(doc, def, currentAccessor);
3659
- break;
3660
- case "min_length": {
3661
- const min = numericOperand(def.minimum, "min_length");
3662
- const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length >= ${min} && ${currentAccessor}.length < ${def.minimum * 2}`);
3663
- doc.write(`if (${len} < ${min}) return INVALID;`);
3664
- break;
3665
- }
3666
- case "max_length": {
3667
- const max = numericOperand(def.maximum, "max_length");
3668
- const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length > ${max}`);
3669
- doc.write(`if (${len} > ${max}) return INVALID;`);
3670
- break;
3671
- }
3672
- case "length_equals": {
3673
- const exact = numericOperand(def.length, "length_equals");
3674
- const len = codePointLengthVar(doc, ctx, currentAccessor, `${currentAccessor}.length >= ${exact} && ${currentAccessor}.length <= ${def.length * 2}`);
3675
- doc.write(`if (${len} !== ${exact}) return INVALID;`);
3676
- break;
3677
- }
3678
- case "min_size":
3679
- doc.write(`if (${currentAccessor}.size < ${numericOperand(def.minimum, "min_size")}) return INVALID;`);
3680
- break;
3681
- case "max_size":
3682
- doc.write(`if (${currentAccessor}.size > ${numericOperand(def.maximum, "max_size")}) return INVALID;`);
3683
- break;
3684
- case "size_equals":
3685
- doc.write(`if (${currentAccessor}.size !== ${numericOperand(def.size, "size_equals")}) return INVALID;`);
3686
- break;
3687
- case "string_format":
3688
- currentAccessor = generateStringFormatCheck(doc, ctx, def, currentAccessor);
3689
- break;
3690
- case "custom":
3691
- currentAccessor = generateCustomRefineCheck(doc, ctx, check, currentAccessor);
3692
- break;
3693
- case "bigint_format":
3694
- generateBigIntFormatCheck(doc, def, currentAccessor);
3695
- break;
3696
- case "mime_type":
3697
- generateMimeTypeCheck(doc, ctx, def, currentAccessor);
3698
- break;
3699
- case "property":
3700
- generatePropertyCheck(doc, ctx, def, currentAccessor);
3701
- break;
3702
- case "properties":
3703
- generatePropertiesChecks(doc, ctx, def, currentAccessor);
3704
- break;
3705
- case "overwrite": {
3706
- const newAccessor = newVar(ctx);
3707
- generateOverwriteCheck(doc, ctx, check, currentAccessor, newAccessor);
3708
- currentAccessor = newAccessor;
3709
- break;
3710
- }
3711
- default: {
3712
- throw new ZodCompileUnsupportedError(`check type ${def.check}`);
3713
- }
3714
- }
3715
- }
3716
- return currentAccessor;
3717
- }
3718
- function codePointLengthVar(doc, ctx, accessor, inDoubt) {
3719
- const cpLen = addConstant(ctx, codePointLength);
3720
- const v = newVar(ctx);
3721
- doc.write(`const ${v} = typeof ${accessor} === "string" && ${inDoubt} ? ${cpLen}(${accessor}) : ${accessor}.length;`);
3722
- return v;
3723
- }
3724
- function numericOperand(value, label) {
3725
- if (typeof value !== "number" || !Number.isFinite(value)) {
3726
- throw new ZodCompileUnsupportedError(`${label} bound of type ${typeof value}`);
3727
- }
3728
- return `${value}`;
3729
- }
3730
- function comparisonOperand(ctx, value) {
3731
- if (typeof value === "bigint")
3732
- return `${value}n`;
3733
- if (typeof value === "number") {
3734
- if (Number.isNaN(value))
3735
- throw new ZodCompileUnsupportedError("comparison check with NaN bound");
3736
- return `${value}`;
3737
- }
3738
- if (value instanceof Date) {
3739
- if (Number.isNaN(value.getTime())) {
3740
- throw new ZodCompileUnsupportedError("comparison check with Invalid Date bound");
3741
- }
3742
- return addConstant(ctx, value);
3743
- }
3744
- throw new ZodCompileUnsupportedError(`comparison check bound of type ${typeof value}`);
3745
- }
3746
- function generateGreaterThanCheck(doc, ctx, def, accessor) {
3747
- const op = def.inclusive ? "<" : "<=";
3748
- doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx, def.value)}) return INVALID;`);
3749
- }
3750
- function generateLessThanCheck(doc, ctx, def, accessor) {
3751
- const op = def.inclusive ? ">" : ">=";
3752
- doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx, def.value)}) return INVALID;`);
3753
- }
3754
- function generateMultipleOfCheck(doc, ctx, def, accessor) {
3755
- if (typeof def.value === "bigint") {
3756
- if (def.value === BigInt(0))
3757
- throw new ZodCompileUnsupportedError("multiple_of check with a zero divisor");
3758
- doc.write(`if (${accessor} % ${def.value}n !== 0n) return INVALID;`);
3759
- } else {
3760
- const remainder = addConstant(ctx, floatSafeRemainder);
3761
- doc.write(`if (${remainder}(${accessor}, ${numericOperand(def.value, "multiple_of")}) !== 0) return INVALID;`);
3762
- }
3763
- }
3764
- function generateNumberFormatCheck(doc, def, accessor) {
3765
- const format = def.format;
3766
- switch (format) {
3767
- case "safeint":
3768
- doc.write(`if (!Number.isSafeInteger(${accessor})) return INVALID;`);
3769
- break;
3770
- case "int32":
3771
- doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < -2147483648 || ${accessor} > 2147483647) return INVALID;`);
3772
- break;
3773
- case "uint32":
3774
- doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < 0 || ${accessor} > 4294967295) return INVALID;`);
3775
- break;
3776
- case "float32":
3777
- doc.write(`if (!Number.isFinite(${accessor}) || ${accessor} < -3.4028234663852886e38 || ${accessor} > 3.4028234663852886e38) return INVALID;`);
3778
- break;
3779
- case "float64":
3780
- doc.write(`if (!Number.isFinite(${accessor})) return INVALID;`);
3781
- break;
3782
- default: {
3783
- throw new ZodCompileUnsupportedError(`number format ${format}`);
3784
- }
3785
- }
3786
- }
3787
- function generateBigIntFormatCheck(doc, def, accessor) {
3788
- const format = def.format;
3789
- if (!format)
3790
- return;
3791
- switch (format) {
3792
- case "int64":
3793
- doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`);
3794
- break;
3795
- case "uint64":
3796
- doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`);
3797
- break;
3798
- default: {
3799
- throw new ZodCompileUnsupportedError(`bigint format ${format}`);
3800
- }
3801
- }
3802
- }
3803
- function generateMimeTypeCheck(doc, ctx, def, accessor) {
3804
- const mimeTypes = def.mime;
3805
- if (mimeTypes && mimeTypes.length > 0) {
3806
- const mimeSet = addConstant(ctx, new Set(mimeTypes));
3807
- doc.write(`if (!${mimeSet}.has(${accessor}.type)) return INVALID;`);
3808
- }
3809
- }
3810
- function generatePropertiesChecks(doc, ctx, def, accessor) {
3811
- if (def.when) {
3812
- throw new ZodCompileUnsupportedError(`check with a custom "when" condition`);
3813
- }
3814
- doc.write(`if (${accessor} == null) return INVALID;`);
3815
- const shape = def.shape;
3816
- for (const key of Reflect.ownKeys(shape)) {
3817
- const keyExpr = typeof key === "symbol" ? addConstant(ctx, key) : esc(key);
3818
- const inputVar = newVar(ctx);
3819
- doc.write(`const ${inputVar} = ${accessor}[${keyExpr}];`);
3820
- compileChild(doc, ctx, shape[key], inputVar, false);
3821
- }
3822
- }
3823
- function generatePropertyCheck(doc, ctx, def, accessor) {
3824
- const propAccessor = `${accessor}[${JSON.stringify(def.property)}]`;
3825
- generateCheck(doc, ctx, def.schema, propAccessor);
3826
- }
3827
- function generateOverwriteCheck(doc, ctx, check, currentAccessor, newAccessor) {
3828
- const tx = check._zod.def.tx;
3829
- if (!tx) {
3830
- throw new ZodCompileUnsupportedError("overwrite check without a transform function");
3831
- }
3832
- if (isAsyncFunction(tx)) {
3833
- throw new ZodCompileAsyncError("z.compile: async overwrite transforms are not supported");
3834
- }
3835
- const txConst = addConstant(ctx, tx);
3836
- doc.write(`const ${newAccessor} = ${txConst}(${currentAccessor});`);
3837
- }
3838
- function throwAsync() {
3839
- throw new $ZodAsyncError;
3840
- }
3841
- function pushIssue(issue) {
3842
- this.issues.push(issue);
3843
- }
3844
- function generateCustomRefineCheck(doc, ctx, check, accessor) {
3845
- const def = check._zod.def;
3846
- if (def.fn) {
3847
- if (isAsyncFunction(def.fn)) {
3848
- throw new ZodCompileAsyncError("z.compile: async .refine() predicates are not supported");
3849
- }
3850
- const fnConst = addUserConstant(ctx, def.fn);
3851
- const throwAsyncConst = addConstant(ctx, throwAsync);
3852
- const resVar = newVar(ctx);
3853
- doc.write(`const ${resVar} = ${fnConst}(${accessor});`);
3854
- doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`);
3855
- doc.write(`if (!${resVar}) return INVALID;`);
3856
- return accessor;
3857
- }
3858
- if (check._zod.check) {
3859
- if (isAsyncFunction(check._zod.check)) {
3860
- throw new ZodCompileAsyncError("z.compile: async .superRefine() / check functions are not supported");
3861
- }
3862
- const checkFn = check._zod.check;
3863
- const helperFn = (value) => {
3864
- const fakePayload = { value, issues: [], addIssue: pushIssue };
3865
- const result = checkFn(fakePayload);
3866
- if (result instanceof Promise)
3867
- throwAsync();
3868
- return fakePayload.issues.length === 0 ? fakePayload.value : INVALID;
3869
- };
3870
- const helperConst = addUserConstant(ctx, helperFn);
3871
- const outVar = newVar(ctx);
3872
- doc.write(`const ${outVar} = ${helperConst}(${accessor});`);
3873
- doc.write(`if (${outVar} === INVALID) return INVALID;`);
3874
- return outVar;
3875
- }
3876
- throw new ZodCompileUnsupportedError("custom check without a predicate or check function");
3877
- }
3878
- var PATTERN_IS_COMPLETE = new Set([
3879
- "cidrv4",
3880
- "cuid",
3881
- "cuid2",
3882
- "date",
3883
- "datetime",
3884
- "duration",
3885
- "e164",
3886
- "email",
3887
- "emoji",
3888
- "ends_with",
3889
- "guid",
3890
- "includes",
3891
- "ipv4",
3892
- "ksuid",
3893
- "lowercase",
3894
- "mac",
3895
- "nanoid",
3896
- "regex",
3897
- "starts_with",
3898
- "time",
3899
- "ulid",
3900
- "uppercase",
3901
- "uuid",
3902
- "xid"
3903
- ]);
3904
- function generateStringFormatCheck(doc, ctx, def, accessor, needsValue = true) {
3905
- const fmt = def.format;
3906
- if (fmt === "base64") {
3907
- const validator = addConstant(ctx, isValidBase64);
3908
- doc.write(`if (!${validator}(${accessor})) return INVALID;`);
3909
- return accessor;
3910
- }
3911
- if (fmt === "base64url") {
3912
- const validator = addConstant(ctx, isValidBase64URL);
3913
- doc.write(`if (!${validator}(${accessor})) return INVALID;`);
3914
- return accessor;
3915
- }
3916
- if (fmt === "jwt") {
3917
- const validator = addConstant(ctx, isValidJWT);
3918
- const alg = addConstant(ctx, def.alg ?? null);
3919
- doc.write(`if (!${validator}(${accessor}, ${alg})) return INVALID;`);
3920
- return accessor;
3921
- }
3922
- if (fmt === "ipv6") {
3923
- const validator = addConstant(ctx, isValidIPv6);
3924
- doc.write(`if (!${validator}(${accessor})) return INVALID;`);
3925
- return accessor;
3926
- }
3927
- if (fmt === "cidrv6") {
3928
- const validator = addConstant(ctx, isValidCIDRv6);
3929
- doc.write(`if (!${validator}(${accessor})) return INVALID;`);
3930
- return accessor;
3931
- }
3932
- if (fmt === "credit_card") {
3933
- const validator = addConstant(ctx, isValidCreditCard);
3934
- doc.write(`if (!${validator}(${accessor})) return INVALID;`);
3935
- return accessor;
3936
- }
3937
- if (fmt === "iban") {
3938
- const validator = addConstant(ctx, isValidIBAN);
3939
- doc.write(`if (!${validator}(${accessor})) return INVALID;`);
3940
- return accessor;
3941
- }
3942
- const formatDef = def;
3943
- if (fmt === "url" || fmt === "httpurl" || formatDef.normalize || formatDef.hostname !== undefined || formatDef.protocol !== undefined) {
3944
- const parseConst = addConstant(ctx, validateURL);
3945
- const defConst = addConstant(ctx, def);
3946
- const trimVar = newVar(ctx);
3947
- const urlVar = newVar(ctx);
3948
- doc.write(`const ${trimVar} = ${accessor}.trim();`);
3949
- doc.write(`const ${urlVar} = ${parseConst}(${trimVar}, ${defConst});`);
3950
- doc.write(`if (typeof ${urlVar} === "number") return INVALID;`);
3951
- if (formatDef.hostname !== undefined) {
3952
- const hostnameConst = addConstant(ctx, urlHostnameOk);
3953
- doc.write(`if (!${hostnameConst}(${urlVar}, ${defConst}.hostname)) return INVALID;`);
3954
- }
3955
- if (formatDef.protocol !== undefined) {
3956
- const protocolConst = addConstant(ctx, urlProtocolOk);
3957
- doc.write(`if (!${protocolConst}(${urlVar}, ${defConst}.protocol)) return INVALID;`);
3958
- }
3959
- if (!needsValue)
3960
- return null;
3961
- const outputVar = newVar(ctx);
3962
- const outputExpr = formatDef.normalize ? `${urlVar}.href` : `${addConstant(ctx, stripTabAndNewline)}(${trimVar})`;
3963
- doc.write(`const ${outputVar} = ${outputExpr};`);
3964
- return outputVar;
3965
- }
3966
- const customFn = def.fn;
3967
- if (customFn) {
3968
- if (isAsyncFunction(customFn))
3969
- throw new ZodCompileUnsupportedError(`async string format ${fmt}`);
3970
- const fnConst = addConstant(ctx, customFn);
3971
- doc.write(`if (!${fnConst}(${accessor})) return INVALID;`);
3972
- return accessor;
3973
- }
3974
- if (PATTERN_IS_COMPLETE.has(fmt) && def.pattern) {
3975
- const patternConst = addConstant(ctx, def.pattern);
3976
- doc.write(`${patternConst}.lastIndex = 0;`);
3977
- doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`);
3978
- return accessor;
3979
- }
3980
- const format = def.format;
3981
- switch (format) {
3982
- case "regex":
3983
- throw new ZodCompileUnsupportedError("regex format without a pattern");
3984
- case "lowercase":
3985
- doc.write(`if (${accessor} !== ${accessor}.toLowerCase()) return INVALID;`);
3986
- break;
3987
- case "uppercase":
3988
- doc.write(`if (${accessor} !== ${accessor}.toUpperCase()) return INVALID;`);
3989
- break;
3990
- case "includes":
3991
- doc.write(`if (!${accessor}.includes(${esc(def.includes)})) return INVALID;`);
3992
- break;
3993
- case "starts_with": {
3994
- const prefix = def.prefix;
3995
- doc.write(`if (${accessor}.slice(0, ${prefix.length}) !== ${esc(prefix)}) return INVALID;`);
3996
- break;
3997
- }
3998
- case "ends_with": {
3999
- const suffix = def.suffix;
4000
- doc.write(`if (${accessor}.slice(-${suffix.length}) !== ${esc(suffix)}) return INVALID;`);
4001
- break;
4002
- }
4003
- default: {
4004
- throw new ZodCompileUnsupportedError(`string format ${format}`);
4005
- }
4006
- }
4007
- return accessor;
4008
- }
4009
- function generateCheck(doc, ctx, schema, accessor, needsValue = true) {
4010
- const def = schema._zod.def;
4011
- const type = def.type;
4012
- if (def.coerce) {
4013
- throw new ZodCompileUnsupportedError(`coercion (z.coerce.${type}())`);
4014
- }
4015
- const buildsValue = needsValue || !!def.checks?.length;
4016
- let typeAccessor;
4017
- switch (type) {
4018
- case "string":
4019
- typeAccessor = generateStringCheck(doc, ctx, schema, accessor, buildsValue);
4020
- break;
4021
- case "number":
4022
- typeAccessor = generateNumberCheck(doc, schema, accessor);
4023
- break;
4024
- case "boolean":
4025
- typeAccessor = generateBooleanCheck(doc, accessor);
4026
- break;
4027
- case "bigint":
4028
- typeAccessor = generateBigIntCheck(doc, schema, accessor);
4029
- break;
4030
- case "symbol":
4031
- typeAccessor = generateSymbolCheck(doc, accessor);
4032
- break;
4033
- case "undefined":
4034
- typeAccessor = generateUndefinedCheck(doc, accessor);
4035
- break;
4036
- case "null":
4037
- typeAccessor = generateNullCheck(doc, accessor);
4038
- break;
4039
- case "any":
4040
- case "unknown":
4041
- typeAccessor = accessor;
4042
- break;
4043
- case "never":
4044
- doc.write("return INVALID;");
4045
- typeAccessor = accessor;
4046
- break;
4047
- case "void":
4048
- typeAccessor = generateVoidCheck(doc, accessor);
4049
- break;
4050
- case "nan":
4051
- typeAccessor = generateNaNCheck(doc, accessor);
4052
- break;
4053
- case "date":
4054
- typeAccessor = generateDateCheck(doc, accessor);
4055
- break;
4056
- case "object":
4057
- typeAccessor = generateObjectCheck(doc, ctx, schema, accessor, buildsValue);
4058
- break;
4059
- case "optional":
4060
- typeAccessor = generateOptionalCheck(doc, ctx, schema, accessor, buildsValue);
4061
- break;
4062
- case "nullable":
4063
- typeAccessor = generateNullableCheck(doc, ctx, schema, accessor, buildsValue);
4064
- break;
4065
- case "array":
4066
- typeAccessor = generateArrayCheck(doc, ctx, schema, accessor, buildsValue);
4067
- break;
4068
- case "literal":
4069
- typeAccessor = generateLiteralCheck(doc, ctx, schema, accessor);
4070
- break;
4071
- case "enum":
4072
- typeAccessor = generateEnumCheck(doc, ctx, schema, accessor);
4073
- break;
4074
- case "readonly": {
4075
- const innerOut = generateWrapperCheck(doc, ctx, schema, accessor);
4076
- const frozenVar = newVar(ctx);
4077
- doc.write(`const ${frozenVar} = Object.freeze(${innerOut});`);
4078
- typeAccessor = frozenVar;
4079
- break;
4080
- }
4081
- case "success":
4082
- generateWrapperCheck(doc, ctx, schema, accessor);
4083
- typeAccessor = "true";
4084
- break;
4085
- case "default":
4086
- case "prefault":
4087
- typeAccessor = generateDefaultCheck(doc, ctx, schema, accessor);
4088
- break;
4089
- case "nonoptional":
4090
- typeAccessor = generateNonOptionalCheck(doc, ctx, schema, accessor);
4091
- break;
4092
- case "tuple":
4093
- typeAccessor = generateTupleCheck(doc, ctx, schema, accessor);
4094
- break;
4095
- case "union":
4096
- typeAccessor = generateUnionCheck(doc, ctx, schema, accessor);
4097
- break;
4098
- case "intersection":
4099
- typeAccessor = generateIntersectionCheck(doc, ctx, schema, accessor);
4100
- break;
4101
- case "record":
4102
- typeAccessor = generateRecordCheck(doc, ctx, schema, accessor);
4103
- break;
4104
- case "map":
4105
- typeAccessor = generateMapCheck(doc, ctx, schema, accessor);
4106
- break;
4107
- case "set":
4108
- typeAccessor = generateSetCheck(doc, ctx, schema, accessor);
4109
- break;
4110
- case "file":
4111
- typeAccessor = generateFileCheck(doc, accessor);
4112
- break;
4113
- case "template_literal":
4114
- typeAccessor = generateTemplateLiteralCheck(doc, ctx, schema, accessor);
4115
- break;
4116
- case "lazy":
4117
- typeAccessor = generateLazyCheck(doc, ctx, schema, accessor);
4118
- break;
4119
- case "pipe":
4120
- typeAccessor = generatePipeCheck(doc, ctx, schema, accessor);
4121
- break;
4122
- case "custom":
4123
- typeAccessor = generateCustomCheck(doc, ctx, schema, accessor);
4124
- break;
4125
- case "transform":
4126
- typeAccessor = generateTransformCheck(doc, ctx, schema, accessor);
4127
- break;
4128
- case "catch":
4129
- typeAccessor = generateCatchCheck(doc, ctx, schema, accessor);
4130
- break;
4131
- default: {
4132
- throw new ZodCompileUnsupportedError(`schema type ${type}`);
4133
- }
4134
- }
4135
- if (typeAccessor === null)
4136
- return null;
4137
- return generateChecks(doc, ctx, schema, typeAccessor);
4138
- }
4139
- function generateStringCheck(doc, ctx, schema, accessor, needsValue = true) {
4140
- doc.write(`if (typeof ${accessor} !== "string") return INVALID;`);
4141
- const def = schema._zod.def;
4142
- if (def.format === undefined)
4143
- return accessor;
4144
- return generateStringFormatCheck(doc, ctx, def, accessor, needsValue);
4145
- }
4146
- function generateNumberCheck(doc, schema, accessor) {
4147
- doc.write(`if (typeof ${accessor} !== "number" || !Number.isFinite(${accessor})) return INVALID;`);
4148
- const def = schema._zod.def;
4149
- if (def.check === "number_format" && def.format) {
4150
- generateNumberFormatCheck(doc, { format: def.format }, accessor);
4151
- }
4152
- return accessor;
4153
- }
4154
- function generateBooleanCheck(doc, accessor) {
4155
- doc.write(`if (typeof ${accessor} !== "boolean") return INVALID;`);
4156
- return accessor;
4157
- }
4158
- function generateBigIntCheck(doc, schema, accessor) {
4159
- doc.write(`if (typeof ${accessor} !== "bigint") return INVALID;`);
4160
- const def = schema._zod.def;
4161
- if (def.format) {
4162
- switch (def.format) {
4163
- case "int64":
4164
- doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`);
4165
- break;
4166
- case "uint64":
4167
- doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`);
4168
- break;
4169
- }
4170
- }
4171
- return accessor;
4172
- }
4173
- function generateSymbolCheck(doc, accessor) {
4174
- doc.write(`if (typeof ${accessor} !== "symbol") return INVALID;`);
4175
- return accessor;
4176
- }
4177
- function generateUndefinedCheck(doc, accessor) {
4178
- doc.write(`if (${accessor} !== undefined) return INVALID;`);
4179
- return accessor;
4180
- }
4181
- function generateNullCheck(doc, accessor) {
4182
- doc.write(`if (${accessor} !== null) return INVALID;`);
4183
- return accessor;
4184
- }
4185
- function generateVoidCheck(doc, accessor) {
4186
- doc.write(`if (${accessor} !== undefined) return INVALID;`);
4187
- return accessor;
4188
- }
4189
- function generateNaNCheck(doc, accessor) {
4190
- doc.write(`if (typeof ${accessor} !== "number" || !Number.isNaN(${accessor})) return INVALID;`);
4191
- return accessor;
4192
- }
4193
- function generateDateCheck(doc, accessor) {
4194
- doc.write(`if (!(${accessor} instanceof Date) || Number.isNaN(${accessor}.getTime())) return INVALID;`);
4195
- return accessor;
4196
- }
4197
- function generateObjectCheck(doc, ctx, schema, accessor, buildsValue = true) {
4198
- const def = schema._zod.def;
4199
- doc.write(`if (typeof ${accessor} !== "object" || ${accessor} === null || Array.isArray(${accessor})) return INVALID;`);
4200
- const shape = def.shape;
4201
- const keys = Object.keys(shape);
4202
- const symbolKeys = Object.getOwnPropertySymbols(shape);
4203
- const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys;
4204
- const keyExpr = (k) => typeof k === "symbol" ? addConstant(ctx, k) : esc(k);
4205
- const propKey = (k) => typeof k === "symbol" ? `[${keyExpr(k)}]` : esc(k);
4206
- const propShape = shape;
4207
- if (keys.includes("__proto__")) {
4208
- throw new ZodCompileUnsupportedError('object shape key "__proto__"');
4209
- }
4210
- const propOutputs = new Map;
4211
- for (const key of allKeys) {
4212
- const propSchema = propShape[key];
4213
- const kx = keyExpr(key);
4214
- const inputVar = newVar(ctx);
4215
- doc.write(`const ${inputVar} = ${accessor}[${kx}];`);
4216
- if (propSchema._zod.optin !== undefined) {
4217
- const outputVar = newVar(ctx);
4218
- doc.write(`let ${outputVar} = (() => {`);
4219
- doc.indented((d) => {
4220
- const outputAccessor = compileChild(d, ctx, propSchema, inputVar);
4221
- d.write(`return ${outputAccessor};`);
4222
- });
4223
- doc.write(`})();`);
4224
- if (propSchema._zod.optout === "optional") {
4225
- doc.write(`if (${outputVar} === INVALID) {`);
4226
- doc.indented((d) => {
4227
- d.write(`if (${kx} in ${accessor}) return INVALID;`);
4228
- d.write(`${outputVar} = undefined;`);
4229
- });
4230
- doc.write(`}`);
4231
- } else {
4232
- doc.write(`if (${outputVar} === INVALID) return INVALID;`);
4233
- }
4234
- propOutputs.set(key, outputVar);
4235
- } else {
4236
- if (requiresPresenceCheck(propSchema)) {
4237
- doc.write(`if (!(${kx} in ${accessor})) return INVALID;`);
4238
- }
4239
- const outputAccessor = compileChild(doc, ctx, propSchema, inputVar, buildsValue);
4240
- if (outputAccessor !== null)
4241
- propOutputs.set(key, outputAccessor);
4242
- }
4243
- }
4244
- const catchall = def.catchall;
4245
- let unknownKeysMode = "none";
4246
- if (catchall) {
4247
- const catchallType = catchall._zod.def.type;
4248
- if (catchallType === "never") {
4249
- const condition = keys.map((k) => `k !== ${esc(k)}`).join(" && ") || "true";
4250
- doc.write(`for (const k in ${accessor}) {`);
4251
- doc.indented((d) => {
4252
- d.write(`if (${condition}) return INVALID;`);
4253
- });
4254
- doc.write(`}`);
4255
- } else if ((catchallType === "unknown" || catchallType === "any") && !catchall._zod.def.checks?.length) {
4256
- unknownKeysMode = "passthrough";
4257
- } else {
4258
- unknownKeysMode = "schema";
4259
- }
4260
- }
4261
- const outputVar = newVar(ctx);
4262
- const hasConditionalKeys = allKeys.some((k) => mayOmitUndefined(propShape[k]) || dropsWhenAbsent(propShape[k]));
4263
- if (!buildsValue) {
4264
- if (unknownKeysMode === "schema") {
4265
- const knownSet = keys.length > 0 ? addConstant(ctx, new Set(keys)) : null;
4266
- doc.write(`for (const k in ${accessor}) {`);
4267
- doc.indented((d) => {
4268
- d.write(`if (k === "__proto__") continue;`);
4269
- if (knownSet)
4270
- d.write(`if (${knownSet}.has(k)) continue;`);
4271
- const valVar = newVar(ctx);
4272
- d.write(`const ${valVar} = ${accessor}[k];`);
4273
- compileChild(d, ctx, catchall, valVar, false);
4274
- });
4275
- doc.write(`}`);
4276
- }
4277
- return null;
4278
- }
4279
- if (!hasConditionalKeys) {
4280
- const propLiterals = allKeys.map((k) => `${propKey(k)}: ${propOutputs.get(k)}`).join(", ");
4281
- doc.write(`const ${outputVar} = { ${propLiterals} };`);
4282
- } else {
4283
- doc.write(`const ${outputVar} = {};`);
4284
- for (const k of allKeys) {
4285
- const kx = keyExpr(k);
4286
- const out = propOutputs.get(k);
4287
- if (dropsWhenAbsent(propShape[k])) {
4288
- doc.write(`if (${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`);
4289
- } else if (mayOmitUndefined(propShape[k])) {
4290
- doc.write(`if (${out} !== undefined || ${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`);
4291
- } else {
4292
- doc.write(`${outputVar}[${kx}] = ${out};`);
4293
- }
4294
- }
4295
- }
4296
- if (unknownKeysMode !== "none") {
4297
- const knownSet = keys.length > 0 ? addConstant(ctx, new Set(keys)) : null;
4298
- doc.write(`for (const k in ${accessor}) {`);
4299
- doc.indented((d) => {
4300
- d.write(`if (k === "__proto__") continue;`);
4301
- if (knownSet)
4302
- d.write(`if (${knownSet}.has(k)) continue;`);
4303
- if (unknownKeysMode === "passthrough") {
4304
- d.write(`${outputVar}[k] = ${accessor}[k];`);
4305
- } else {
4306
- const valVar = newVar(ctx);
4307
- d.write(`const ${valVar} = ${accessor}[k];`);
4308
- const catchallOut = compileChild(d, ctx, catchall, valVar);
4309
- d.write(`${outputVar}[k] = ${catchallOut};`);
4310
- }
4311
- });
4312
- doc.write(`}`);
4313
- }
4314
- return outputVar;
4315
- }
4316
- function generateOptionalCheck(doc, ctx, schema, accessor, buildsValue = true) {
4317
- const def = schema._zod.def;
4318
- if (isExactOptional(schema)) {
4319
- return generateCheck(doc, ctx, def.innerType, accessor, buildsValue);
4320
- }
4321
- if (def.innerType._zod.optin === "defaulted") {
4322
- const outputVar = newVar(ctx);
4323
- const branchVar = newVar(ctx);
4324
- doc.write(`let ${outputVar};`);
4325
- doc.write(`if (${accessor} === undefined) {`);
4326
- doc.indented((d) => {
4327
- d.write(`const ${branchVar} = (() => {`);
4328
- d.indented((d2) => {
4329
- const innerOutput = generateCheck(d2, ctx, def.innerType, accessor);
4330
- d2.write(`return ${innerOutput};`);
4331
- });
4332
- d.write(`})();`);
4333
- d.write(`if (${branchVar} !== INVALID) ${outputVar} = ${branchVar};`);
4334
- });
4335
- doc.write(`} else {`);
4336
- doc.indented((d) => {
4337
- const innerOutput = generateCheck(d, ctx, def.innerType, accessor);
4338
- d.write(`${outputVar} = ${innerOutput};`);
4339
- });
4340
- doc.write(`}`);
4341
- return outputVar;
4342
- }
4343
- const outputVar = buildsValue ? newVar(ctx) : null;
4344
- if (outputVar)
4345
- doc.write(`let ${outputVar};`);
4346
- doc.write(`if (${accessor} !== undefined) {`);
4347
- doc.indented((d) => {
4348
- const innerOutput = generateCheck(d, ctx, def.innerType, accessor, buildsValue);
4349
- if (outputVar && innerOutput !== null)
4350
- d.write(`${outputVar} = ${innerOutput};`);
4351
- });
4352
- doc.write(`}`);
4353
- return outputVar;
4354
- }
4355
- function isExactOptional(schema) {
4356
- return schema._zod.traits?.has("$ZodExactOptional") === true;
4357
- }
4358
- function requiresPresenceCheck(schema) {
4359
- return schema._zod.optin === undefined && fastPathAcceptsAbsence(schema);
4360
- }
4361
- function fastPathAcceptsAbsence(schema) {
4362
- if (schema._zod.def.coerce)
4363
- return true;
4364
- const def = schema._zod.def;
4365
- switch (def.type) {
4366
- case "any":
4367
- case "unknown":
4368
- case "undefined":
4369
- case "void":
4370
- case "default":
4371
- case "prefault":
4372
- case "transform":
4373
- case "custom":
4374
- case "lazy":
4375
- return true;
4376
- case "string":
4377
- case "number":
4378
- case "boolean":
4379
- case "bigint":
4380
- case "symbol":
4381
- case "null":
4382
- case "never":
4383
- case "nan":
4384
- case "date":
4385
- case "object":
4386
- case "array":
4387
- case "tuple":
4388
- case "record":
4389
- case "map":
4390
- case "set":
4391
- case "file":
4392
- case "template_literal":
4393
- return false;
4394
- case "nonoptional":
4395
- return def.innerType ? fastPathAcceptsAbsence(def.innerType) : false;
4396
- case "literal":
4397
- return !!def.values?.includes(undefined);
4398
- case "enum":
4399
- return !!schema._zod.values?.has(undefined);
4400
- case "optional":
4401
- case "nullable":
4402
- case "readonly":
4403
- case "success":
4404
- return def.innerType ? fastPathAcceptsAbsence(def.innerType) : true;
4405
- case "catch":
4406
- return true;
4407
- case "union":
4408
- return def.options ? def.options.some(fastPathAcceptsAbsence) : true;
4409
- case "intersection":
4410
- if (!def.left || !def.right)
4411
- return true;
4412
- return fastPathAcceptsAbsence(def.left) && fastPathAcceptsAbsence(def.right);
4413
- case "pipe":
4414
- return def.in ? fastPathAcceptsAbsence(def.in) : true;
4415
- default:
4416
- return true;
4417
- }
4418
- }
4419
- function dropsWhenAbsent(schema) {
4420
- return schema._zod.optin === "optional" && schema._zod.optout === "optional";
4421
- }
4422
- function mayOmitUndefined(schema) {
4423
- return (schema._zod.optin !== "defaulted" || schema._zod.optout === "optional") && mayOutputUndefined(schema);
4424
- }
4425
- function mayOutputUndefined(schema) {
4426
- const def = schema._zod.def;
4427
- switch (def.type) {
4428
- case "string":
4429
- case "number":
4430
- case "boolean":
4431
- case "bigint":
4432
- case "symbol":
4433
- case "null":
4434
- case "nan":
4435
- case "date":
4436
- case "object":
4437
- case "array":
4438
- case "tuple":
4439
- case "record":
4440
- case "map":
4441
- case "set":
4442
- case "file":
4443
- case "template_literal":
4444
- case "never":
4445
- case "success":
4446
- return false;
4447
- case "literal":
4448
- return !!def.values?.includes(undefined);
4449
- case "enum":
4450
- return !!schema._zod.values?.has(undefined);
4451
- case "optional":
4452
- return true;
4453
- case "nullable":
4454
- case "readonly":
4455
- case "nonoptional":
4456
- return def.innerType ? mayOutputUndefined(def.innerType) : true;
4457
- case "union":
4458
- return def.options ? def.options.some(mayOutputUndefined) : true;
4459
- case "intersection":
4460
- return !def.left || !def.right || mayOutputUndefined(def.left) || mayOutputUndefined(def.right);
4461
- case "pipe":
4462
- return def.out ? mayOutputUndefined(def.out) : true;
4463
- default:
4464
- return true;
4465
- }
4466
- }
4467
- function generateNullableCheck(doc, ctx, schema, accessor, buildsValue = true) {
4468
- const def = schema._zod.def;
4469
- const outputVar = buildsValue ? newVar(ctx) : null;
4470
- if (outputVar)
4471
- doc.write(`let ${outputVar} = null;`);
4472
- doc.write(`if (${accessor} !== null) {`);
4473
- doc.indented((d) => {
4474
- const innerOutput = generateCheck(d, ctx, def.innerType, accessor, buildsValue);
4475
- if (outputVar && innerOutput !== null)
4476
- d.write(`${outputVar} = ${innerOutput};`);
4477
- });
4478
- doc.write(`}`);
4479
- return outputVar;
4480
- }
4481
- function generateArrayCheck(doc, ctx, schema, accessor, buildsValue = true) {
4482
- const def = schema._zod.def;
4483
- doc.write(`if (!Array.isArray(${accessor})) return INVALID;`);
4484
- const outputVar = buildsValue ? newVar(ctx) : null;
4485
- const iVar = newVar(ctx);
4486
- const elemVar = newVar(ctx);
4487
- if (outputVar)
4488
- doc.write(`const ${outputVar} = new Array(${accessor}.length);`);
4489
- doc.write(`for (let ${iVar} = 0; ${iVar} < ${accessor}.length; ${iVar}++) {`);
4490
- doc.indented((d) => {
4491
- d.write(`const ${elemVar} = ${accessor}[${iVar}];`);
4492
- const elemOutput = compileChild(d, ctx, def.element, elemVar, buildsValue);
4493
- if (outputVar && elemOutput !== null)
4494
- d.write(`${outputVar}[${iVar}] = ${elemOutput};`);
4495
- });
4496
- doc.write(`}`);
4497
- return outputVar;
4498
- }
4499
- function generateLiteralCheck(doc, ctx, schema, accessor) {
4500
- const def = schema._zod.def;
4501
- const values = def.values;
4502
- if (values.length !== 1) {
4503
- const literalSet = addConstant(ctx, new Set(values));
4504
- doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`);
4505
- return accessor;
4506
- }
4507
- const value = values[0];
4508
- if (typeof value === "number" && Number.isNaN(value)) {
4509
- const literalSet = addConstant(ctx, new Set(values));
4510
- doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`);
4511
- return accessor;
4512
- }
4513
- if (typeof value === "string") {
4514
- doc.write(`if (${accessor} !== ${esc(value)}) return INVALID;`);
4515
- } else if (typeof value === "number" || typeof value === "boolean") {
4516
- doc.write(`if (${accessor} !== ${value}) return INVALID;`);
4517
- } else if (value === null) {
4518
- doc.write(`if (${accessor} !== null) return INVALID;`);
4519
- } else if (value === undefined) {
4520
- doc.write(`if (${accessor} !== undefined) return INVALID;`);
4521
- } else if (typeof value === "bigint") {
4522
- doc.write(`if (${accessor} !== ${value}n) return INVALID;`);
4523
- } else {
4524
- throw new ZodCompileUnsupportedError(`literal type ${typeof value}`);
4525
- }
4526
- return accessor;
4527
- }
4528
- function generateEnumCheck(doc, ctx, schema, accessor) {
4529
- const values = schema._zod.values;
4530
- if (!values) {
4531
- throw new ZodCompileUnsupportedError("enum schema without enumerated values");
4532
- }
4533
- const enumSet = addConstant(ctx, values);
4534
- doc.write(`if (!${enumSet}.has(${accessor})) return INVALID;`);
4535
- return accessor;
4536
- }
4537
- function generateWrapperCheck(doc, ctx, schema, accessor) {
4538
- const def = schema._zod.def;
4539
- return generateCheck(doc, ctx, def.innerType, accessor);
4540
- }
4541
- function generateDefaultCheck(doc, ctx, schema, accessor) {
4542
- const def = schema._zod.def;
4543
- const descriptor = Object.getOwnPropertyDescriptor(schema._zod.def, "defaultValue");
4544
- const defaultGetter = descriptor ? () => schema._zod.def.defaultValue : undefined;
4545
- if (schema._zod.def.type === "prefault") {
4546
- if (!defaultGetter) {
4547
- return generateCheck(doc, ctx, def.innerType, accessor);
4548
- }
4549
- const defaultFn = addConstant(ctx, defaultGetter);
4550
- const inputVar = newVar(ctx);
4551
- doc.write(`let ${inputVar} = ${accessor};`);
4552
- doc.write(`if (${accessor} === undefined) ${inputVar} = ${defaultFn}();`);
4553
- return generateCheck(doc, ctx, def.innerType, inputVar);
4554
- }
4555
- const outputVar = newVar(ctx);
4556
- if (defaultGetter) {
4557
- const defaultFn = addConstant(ctx, defaultGetter);
4558
- const cloneFn = addConstant(ctx, shallowClone);
4559
- doc.write(`let ${outputVar};`);
4560
- doc.write(`if (${accessor} === undefined) {`);
4561
- doc.indented((d) => {
4562
- d.write(`${outputVar} = ${cloneFn}(${defaultFn}());`);
4563
- });
4564
- doc.write(`} else {`);
4565
- doc.indented((d) => {
4566
- const innerOutput = generateCheck(d, ctx, def.innerType, accessor);
4567
- d.write(`${outputVar} = ${innerOutput} === undefined ? ${cloneFn}(${defaultFn}()) : ${innerOutput};`);
4568
- });
4569
- doc.write(`}`);
4570
- } else {
4571
- doc.write(`let ${outputVar};`);
4572
- doc.write(`if (${accessor} !== undefined) {`);
4573
- doc.indented((d) => {
4574
- const innerOutput = generateCheck(d, ctx, def.innerType, accessor);
4575
- d.write(`${outputVar} = ${innerOutput};`);
4576
- });
4577
- doc.write(`}`);
4578
- }
4579
- return outputVar;
4580
- }
4581
- function generateNonOptionalCheck(doc, ctx, schema, accessor) {
4582
- const def = schema._zod.def;
4583
- const innerOutput = generateCheck(doc, ctx, def.innerType, accessor);
4584
- const outputVar = newVar(ctx);
4585
- doc.write(`const ${outputVar} = ${innerOutput};`);
4586
- doc.write(`if (${outputVar} === undefined) return INVALID;`);
4587
- return outputVar;
4588
- }
4589
- function generateTupleCheck(doc, ctx, schema, accessor) {
4590
- const def = schema._zod.def;
4591
- const items = def.items;
4592
- const rest = def.rest;
4593
- doc.write(`if (!Array.isArray(${accessor})) return INVALID;`);
4594
- const optinStart = getTupleOptStart(items, "optin");
4595
- const optoutStart = getTupleOptStart(items, "optout");
4596
- if (rest) {
4597
- doc.write(`if (${accessor}.length < ${optinStart}) return INVALID;`);
4598
- } else {
4599
- doc.write(`if (${accessor}.length < ${optinStart} || ${accessor}.length > ${items.length}) return INVALID;`);
4600
- }
4601
- const outputVar = newVar(ctx);
4602
- doc.write(`const ${outputVar} = [];`);
4603
- for (let i = 0;i < items.length; i++) {
4604
- const itemSchema = items[i];
4605
- if (i >= optoutStart) {
4606
- doc.write(`if (${outputVar}.length === ${i}) {`);
4607
- doc.indented((d) => {
4608
- d.write(`if (${i} < ${accessor}.length) {`);
4609
- d.indented((d2) => {
4610
- const elemVar = newVar(ctx);
4611
- d2.write(`const ${elemVar} = ${accessor}[${i}];`);
4612
- const elemOutput = compileChild(d2, ctx, itemSchema, elemVar);
4613
- d2.write(`${outputVar}[${i}] = ${elemOutput};`);
4614
- });
4615
- d.write(`} else {`);
4616
- d.indented((d2) => {
4617
- if (dropsWhenAbsent(itemSchema)) {
4618
- d2.write(`${outputVar}.length = ${i};`);
4619
- return;
4620
- }
4621
- const elemVar = newVar(ctx);
4622
- const branchVar = newVar(ctx);
4623
- d2.write(`const ${elemVar} = undefined;`);
4624
- d2.write(`const ${branchVar} = (() => {`);
4625
- d2.indented((d3) => {
4626
- const elemOutput = compileChild(d3, ctx, itemSchema, elemVar);
4627
- d3.write(`return ${elemOutput};`);
4628
- });
4629
- d2.write(`})();`);
4630
- d2.write(`if (${branchVar} === INVALID || ${branchVar} === undefined) ${outputVar}.length = ${i};`);
4631
- d2.write(`else ${outputVar}[${i}] = ${branchVar};`);
4632
- });
4633
- d.write(`}`);
4634
- });
4635
- doc.write(`}`);
4636
- } else {
4637
- const elemVar = newVar(ctx);
4638
- doc.write(`const ${elemVar} = ${accessor}[${i}];`);
4639
- const elemOutput = compileChild(doc, ctx, itemSchema, elemVar);
4640
- doc.write(`${outputVar}[${i}] = ${elemOutput};`);
4641
- }
4642
- }
4643
- if (rest) {
4644
- const iVar = newVar(ctx);
4645
- const elemVar = newVar(ctx);
4646
- doc.write(`for (let ${iVar} = ${items.length}; ${iVar} < ${accessor}.length; ${iVar}++) {`);
4647
- doc.indented((d) => {
4648
- d.write(`const ${elemVar} = ${accessor}[${iVar}];`);
4649
- const elemOutput = compileChild(d, ctx, rest, elemVar);
4650
- d.write(`${outputVar}[${iVar}] = ${elemOutput};`);
4651
- });
4652
- doc.write(`}`);
4653
- }
4654
- return outputVar;
4655
- }
4656
- function getTupleOptStart(items, key) {
4657
- for (let i = items.length - 1;i >= 0; i--) {
4658
- const omittable = key === "optin" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === "optional";
4659
- if (!omittable)
4660
- return i + 1;
4661
- }
4662
- return 0;
4663
- }
4664
- function generateUnionCheck(doc, ctx, schema, accessor) {
4665
- const def = schema._zod.def;
4666
- const options = def.options;
4667
- if (def.discriminator) {
4668
- return generateDiscriminatedUnionCheck(doc, ctx, def, accessor);
4669
- }
4670
- if (def.inclusive === false) {
4671
- throw new ZodCompileUnsupportedError("exclusive unions (z.xor)");
4672
- }
4673
- if (options.length === 0) {
4674
- doc.write("return INVALID;");
4675
- return accessor;
4676
- }
4677
- if (options.length === 1) {
4678
- return generateCheck(doc, ctx, options[0], accessor);
4679
- }
4680
- const allLiterals = options.every((opt) => opt._zod.def.type === "literal" && !opt._zod.def.checks?.length);
4681
- if (allLiterals) {
4682
- const values = new Set(options.flatMap((opt) => opt._zod.def.values));
4683
- const valuesConst = addConstant(ctx, values);
4684
- doc.write(`if (!${valuesConst}.has(${accessor})) return INVALID;`);
4685
- return accessor;
4686
- }
4687
- const outputVar = newVar(ctx);
4688
- doc.write(`let ${outputVar};`);
4689
- for (let i = 0;i < options.length; i++) {
4690
- const opt = options[i];
4691
- if (i === 0) {
4692
- doc.write(`${outputVar} = (() => {`);
4693
- } else {
4694
- doc.write(`if (${outputVar} === INVALID) ${outputVar} = (() => {`);
4695
- }
4696
- doc.indented((d) => {
4697
- const branchOutput = generateCheck(d, ctx, opt, accessor);
4698
- d.write(`return ${branchOutput};`);
4699
- });
4700
- doc.write(`})();`);
4701
- }
4702
- doc.write(`if (${outputVar} === INVALID) return INVALID;`);
4703
- return outputVar;
4704
- }
4705
- function generateDiscriminatedUnionCheck(doc, ctx, def, accessor) {
4706
- if (def.unionFallback) {
4707
- throw new ZodCompileUnsupportedError("discriminated union with unionFallback");
4708
- }
4709
- if (def.options.length === 0) {
4710
- doc.write("return INVALID;");
4711
- return accessor;
4712
- }
4713
- const discVar = newVar(ctx);
4714
- const outputVar = newVar(ctx);
4715
- doc.write(`const ${discVar} = ${accessor}?.[${esc(def.discriminator)}];`);
4716
- doc.write(`let ${outputVar};`);
4717
- let firstBranch = true;
4718
- const claimed = new Set;
4719
- for (const option of def.options) {
4720
- const values = option._zod.propValues?.[def.discriminator];
4721
- if (!values || values.size === 0) {
4722
- throw new ZodCompileUnsupportedError("discriminated union option without static discriminator values");
4723
- }
4724
- for (const value of values) {
4725
- if (claimed.has(value)) {
4726
- throw new ZodCompileUnsupportedError(`duplicate discriminator value ${String(value)}`);
4727
- }
4728
- claimed.add(value);
4729
- }
4730
- const conditions = Array.from(values, (value) => literalEquality(ctx, discVar, value));
4731
- const prefix = firstBranch ? "if" : "else if";
4732
- doc.write(`${prefix} (${conditions.join(" || ")}) {`);
4733
- doc.indented((d) => {
4734
- const branchOutput = generateCheck(d, ctx, option, accessor);
4735
- d.write(`${outputVar} = ${branchOutput};`);
4736
- });
4737
- doc.write(`}`);
4738
- firstBranch = false;
4739
- }
4740
- doc.write(`else { return INVALID; }`);
4741
- return outputVar;
4742
- }
4743
- function literalEquality(ctx, accessor, value) {
4744
- if (typeof value === "string")
4745
- return `${accessor} === ${esc(value)}`;
4746
- if (typeof value === "number") {
4747
- if (Number.isNaN(value))
4748
- return `Number.isNaN(${accessor})`;
4749
- return `${accessor} === ${value}`;
4750
- }
4751
- if (typeof value === "boolean")
4752
- return `${accessor} === ${value}`;
4753
- if (value === null)
4754
- return `${accessor} === null`;
4755
- if (value === undefined)
4756
- return `${accessor} === undefined`;
4757
- if (typeof value === "bigint")
4758
- return `${accessor} === ${value}n`;
4759
- if (typeof value === "symbol") {
4760
- const symbolConst = addConstant(ctx, value);
4761
- return `${accessor} === ${symbolConst}`;
4762
- }
4763
- throw new ZodCompileUnsupportedError(`literal discriminator value ${String(value)}`);
4764
- }
4765
- function generateIntersectionCheck(doc, ctx, schema, accessor) {
4766
- const def = schema._zod.def;
4767
- ctx.definite = false;
4768
- const leftOutput = compileChild(doc, ctx, def.left, accessor);
4769
- const rightOutput = compileChild(doc, ctx, def.right, accessor);
4770
- const mergeConst = addConstant(ctx, mergeValues);
4771
- const mergedVar = newVar(ctx);
4772
- doc.write(`const ${mergedVar} = ${mergeConst}(${leftOutput}, ${rightOutput});`);
4773
- doc.write(`if (!${mergedVar}.valid) return INVALID;`);
4774
- return `${mergedVar}.data`;
4775
- }
4776
- function generateRecordCheck(doc, ctx, schema, accessor) {
4777
- const def = schema._zod.def;
4778
- const isPlainObjectConst = addConstant(ctx, isPlainObject);
4779
- doc.write(`if (!${isPlainObjectConst}(${accessor})) return INVALID;`);
4780
- const outputVar = newVar(ctx);
4781
- const kVar = newVar(ctx);
4782
- const valVar = newVar(ctx);
4783
- doc.write(`const ${outputVar} = {};`);
4784
- const recordDef = def;
4785
- const keyValues = recordDef.partial ? undefined : def.keyType._zod.values;
4786
- if (keyValues) {
4787
- const inputKeys = [];
4788
- for (const key of keyValues) {
4789
- if (!(typeof key === "string" || typeof key === "number" || typeof key === "symbol")) {
4790
- throw new ZodCompileUnsupportedError(`record key value ${String(key)}`);
4791
- }
4792
- const inputKey = typeof key === "number" ? key.toString() : key;
4793
- if (inputKey === "__proto__") {
4794
- throw new ZodCompileUnsupportedError('record key "__proto__"');
4795
- }
4796
- inputKeys.push(inputKey);
4797
- const keyConst = addConstant(ctx, key);
4798
- const outKey = generateCheck(doc, ctx, def.keyType, keyConst);
4799
- const valueVar = newVar(ctx);
4800
- doc.write(`const ${valueVar} = ${accessor}[${literalPropertyKey(ctx, inputKey)}];`);
4801
- const valOutput = compileChild(doc, ctx, def.valueType, valueVar);
4802
- doc.write(`${outputVar}[${outKey}] = ${valOutput};`);
4803
- }
4804
- const knownKeysConst = addConstant(ctx, new Set(inputKeys));
4805
- doc.write(`for (const ${kVar} in ${accessor}) {`);
4806
- doc.indented((d) => {
4807
- d.write(`if (${knownKeysConst}.has(${kVar})) continue;`);
4808
- if (recordDef.mode === "loose") {
4809
- d.write(`if (${kVar} !== "__proto__") ${outputVar}[${kVar}] = ${accessor}[${kVar}];`);
4810
- } else {
4811
- d.write(`return INVALID;`);
4812
- }
4813
- });
4814
- doc.write(`}`);
4815
- return outputVar;
4816
- }
4817
- const keyDef = def.keyType._zod.def;
4818
- const keyIsBareString = keyDef.type === "string" && keyDef.format === undefined && !keyDef.coerce && (keyDef.checks?.length ?? 0) === 0;
4819
- if (!keyIsBareString) {
4820
- const isLoose = def.mode === "loose";
4821
- const keyFn = compileFn(def.keyType);
4822
- if (keyFn.definite === false)
4823
- ctx.definite = false;
4824
- const keyFast = addConstant(ctx, keyFn);
4825
- const numericConst = addConstant(ctx, number);
4826
- const outKeyVar = newVar(ctx);
4827
- emitOwnKeys(doc, ctx, accessor, kVar, (d) => {
4828
- d.write(`let ${outKeyVar} = ${keyFast}(${kVar});`);
4829
- d.write(`if (${outKeyVar} === INVALID && typeof ${kVar} === "string" && ${numericConst}.test(${kVar})) ${outKeyVar} = ${keyFast}(Number(${kVar}));`);
4830
- if (isLoose) {
4831
- d.write(`if (${outKeyVar} === INVALID) { ${outputVar}[${kVar}] = ${accessor}[${kVar}]; continue; }`);
4832
- } else {
4833
- d.write(`if (${outKeyVar} === INVALID) return INVALID;`);
4834
- }
4835
- d.write(`if (${outKeyVar} === "__proto__") continue;`);
4836
- const valueVar = newVar(ctx);
4837
- d.write(`const ${valueVar} = ${accessor}[${kVar}];`);
4838
- const valOutput = compileChild(d, ctx, def.valueType, valueVar);
4839
- d.write(`${outputVar}[${outKeyVar}] = ${valOutput};`);
4840
- });
4841
- return outputVar;
4842
- }
4843
- emitOwnKeys(doc, ctx, accessor, kVar, (d) => {
4844
- d.write(`const ${valVar} = ${accessor}[${kVar}];`);
4845
- const valOutput = compileChild(d, ctx, def.valueType, valVar);
4846
- d.write(`${outputVar}[${kVar}] = ${valOutput};`);
4847
- }, `return INVALID;`);
4848
- return outputVar;
4849
- }
4850
- function emitOwnKeys(doc, ctx, accessor, kVar, body, onSymbol) {
4851
- const propIsEnumerableConst = addConstant(ctx, Object.prototype.propertyIsEnumerable);
4852
- const symsVar = newVar(ctx);
4853
- const keysVar = newVar(ctx);
4854
- const iVar = newVar(ctx);
4855
- doc.write(`const ${symsVar} = Object.getOwnPropertySymbols(${accessor});`);
4856
- doc.write(`const ${keysVar} = Object.getOwnPropertyNames(${accessor});`);
4857
- doc.write(`for (let ${iVar} = 0; ${iVar} < ${keysVar}.length; ${iVar}++) {`);
4858
- doc.indented((d) => {
4859
- d.write(`const ${kVar} = ${keysVar}[${iVar}];`);
4860
- d.write(`if (${kVar} === "__proto__" || !${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`);
4861
- body(d);
4862
- });
4863
- doc.write(`}`);
4864
- doc.write(`for (let ${iVar} = 0; ${iVar} < ${symsVar}.length; ${iVar}++) {`);
4865
- doc.indented((d) => {
4866
- d.write(`const ${kVar} = ${symsVar}[${iVar}];`);
4867
- d.write(`if (!${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`);
4868
- if (onSymbol)
4869
- d.write(onSymbol);
4870
- else
4871
- body(d);
4872
- });
4873
- doc.write(`}`);
4874
- }
4875
- function literalPropertyKey(ctx, key) {
4876
- if (typeof key === "string")
4877
- return esc(key);
4878
- return addConstant(ctx, key);
4879
- }
4880
- function generateMapCheck(doc, ctx, schema, accessor) {
4881
- const def = schema._zod.def;
4882
- doc.write(`if (!(${accessor} instanceof Map)) return INVALID;`);
4883
- const outputVar = newVar(ctx);
4884
- const kVar = newVar(ctx);
4885
- const valVar = newVar(ctx);
4886
- doc.write(`const ${outputVar} = new Map();`);
4887
- doc.write(`for (const [${kVar}, ${valVar}] of ${accessor}) {`);
4888
- doc.indented((d) => {
4889
- const keyOutput = generateCheck(d, ctx, def.keyType, kVar);
4890
- const valOutput = generateCheck(d, ctx, def.valueType, valVar);
4891
- d.write(`${outputVar}.set(${keyOutput}, ${valOutput});`);
4892
- });
4893
- doc.write(`}`);
4894
- return outputVar;
4895
- }
4896
- function generateSetCheck(doc, ctx, schema, accessor) {
4897
- const def = schema._zod.def;
4898
- doc.write(`if (!(${accessor} instanceof Set)) return INVALID;`);
4899
- const outputVar = newVar(ctx);
4900
- const valVar = newVar(ctx);
4901
- doc.write(`const ${outputVar} = new Set();`);
4902
- doc.write(`for (const ${valVar} of ${accessor}) {`);
4903
- doc.indented((d) => {
4904
- const valOutput = generateCheck(d, ctx, def.valueType, valVar);
4905
- d.write(`${outputVar}.add(${valOutput});`);
4906
- });
4907
- doc.write(`}`);
4908
- return outputVar;
4909
- }
4910
- function generateFileCheck(doc, accessor) {
4911
- doc.write(`if (!(${accessor} instanceof File)) return INVALID;`);
4912
- return accessor;
4913
- }
4914
- function generateTemplateLiteralCheck(doc, ctx, schema, accessor) {
4915
- doc.write(`if (typeof ${accessor} !== "string") return INVALID;`);
4916
- const pattern = schema._zod.pattern;
4917
- if (pattern) {
4918
- const patternConst = addConstant(ctx, pattern);
4919
- doc.write(`${patternConst}.lastIndex = 0;`);
4920
- doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`);
4921
- }
4922
- return accessor;
4923
- }
4924
- function generateLazyCheck(doc, ctx, schema, accessor) {
4925
- const def = schema._zod.def;
4926
- const getterConst = addUserConstant(ctx, def.getter);
4927
- const cacheConst = addConstant(ctx, { parser: null });
4928
- doc.write(`if (!${cacheConst}.parser) {`);
4929
- doc.indented((d) => {
4930
- d.write(`const inner = ${getterConst}();`);
4931
- d.write(`${cacheConst}.parser = function(input) {`);
4932
- d.indented((d2) => {
4933
- d2.write(`const result = inner._zod.run({ value: input, issues: [] }, {});`);
4934
- d2.write(`return result.issues.length === 0 ? result.value : INVALID;`);
4935
- });
4936
- d.write(`};`);
4937
- });
4938
- doc.write(`}`);
4939
- const outputVar = newVar(ctx);
4940
- doc.write(`const ${outputVar} = ${cacheConst}.parser(${accessor});`);
4941
- doc.write(`if (${outputVar} === INVALID) return INVALID;`);
4942
- return outputVar;
4943
- }
4944
- function generatePipeCheck(doc, ctx, schema, accessor) {
4945
- const def = schema._zod.def;
4946
- const inputOutput = generateCheck(doc, ctx, def.in, accessor);
4947
- if (def.transform) {
4948
- if (isAsyncFunction(def.transform)) {
4949
- throw new ZodCompileAsyncError("z.compile: async transforms in pipes are not supported");
4950
- }
4951
- const transformFn = def.transform;
4952
- const helperFn = (value) => {
4953
- const fakePayload = { value, issues: [], addIssue: pushIssue };
4954
- const result = transformFn(value, fakePayload);
4955
- if (result instanceof Promise)
4956
- return INVALID;
4957
- return fakePayload.issues.length === 0 ? result : INVALID;
4958
- };
4959
- const helperConst = addUserConstant(ctx, helperFn);
4960
- const transformedVar = newVar(ctx);
4961
- doc.write(`const ${transformedVar} = ${helperConst}(${inputOutput});`);
4962
- doc.write(`if (${transformedVar} === INVALID) return INVALID;`);
4963
- return generateCheck(doc, ctx, def.out, transformedVar);
4964
- } else {
4965
- return generateCheck(doc, ctx, def.out, inputOutput);
4966
- }
4967
- }
4968
- function isAsyncFunction(fn) {
4969
- return typeof fn === "function" && (fn.constructor.name === "AsyncFunction" || fn[Symbol.toStringTag] === "AsyncFunction");
4970
- }
4971
- function generateCustomCheck(doc, ctx, schema, accessor) {
4972
- const def = schema._zod.def;
4973
- if (def.fn) {
4974
- if (isAsyncFunction(def.fn)) {
4975
- throw new ZodCompileAsyncError("z.compile: async custom predicates are not supported");
4976
- }
4977
- const fnConst = addUserConstant(ctx, def.fn);
4978
- const throwAsyncConst = addConstant(ctx, throwAsync);
4979
- const resVar = newVar(ctx);
4980
- doc.write(`const ${resVar} = ${fnConst}(${accessor});`);
4981
- doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`);
4982
- doc.write(`if (!${resVar}) return INVALID;`);
4983
- } else {
4984
- throw new ZodCompileUnsupportedError("custom schema without a predicate function");
4985
- }
4986
- return accessor;
4987
- }
4988
- function runtimeCatch(innerSchema, catchValue, value) {
4989
- const result = innerSchema._zod.run({ value, issues: [] }, {});
4990
- if (result && typeof result.then === "function")
4991
- return INVALID;
4992
- const r = result;
4993
- if (r.issues.length === 0)
4994
- return r.value;
4995
- return catchValue();
4996
- }
4997
- function generateCatchCheck(doc, ctx, schema, accessor) {
4998
- const def = schema._zod.def;
4999
- if (!def.catchValue[CONSTANT_CATCH]) {
5000
- throw new ZodCompileUnsupportedError("catch with a callback (only a constant catch value compiles)", false);
5001
- }
5002
- const outputVar = newVar(ctx);
5003
- doc.write(`let ${outputVar} = (() => {`);
5004
- doc.indented((d) => {
5005
- const innerOut = compileChild(d, ctx, def.innerType, accessor);
5006
- d.write(`return ${innerOut};`);
5007
- });
5008
- doc.write(`})();`);
5009
- const innerConst = addConstant(ctx, def.innerType);
5010
- const catchConst = addUserConstant(ctx, def.catchValue);
5011
- const catchHelperConst = addConstant(ctx, runtimeCatch);
5012
- doc.write(`if (${outputVar} === INVALID) {`);
5013
- doc.indented((d) => {
5014
- d.write(`${outputVar} = ${catchHelperConst}(${innerConst}, ${catchConst}, ${accessor});`);
5015
- d.write(`if (${outputVar} === INVALID) return INVALID;`);
5016
- });
5017
- doc.write(`}`);
5018
- return outputVar;
5019
- }
5020
- function generateTransformCheck(doc, ctx, schema, accessor) {
5021
- const def = schema._zod.def;
5022
- if (def.transform) {
5023
- if (isAsyncFunction(def.transform)) {
5024
- throw new ZodCompileAsyncError("z.compile: async transforms are not supported");
5025
- }
5026
- const transformFn = def.transform;
5027
- const helperFn = (value) => {
5028
- const fakePayload = { value, issues: [], addIssue: pushIssue };
5029
- const result = transformFn(value, fakePayload);
5030
- if (result instanceof Promise)
5031
- return INVALID;
5032
- return fakePayload.issues.length === 0 ? result : INVALID;
5033
- };
5034
- const helperConst = addUserConstant(ctx, helperFn);
5035
- const outputVar = newVar(ctx);
5036
- doc.write(`const ${outputVar} = ${helperConst}(${accessor});`);
5037
- doc.write(`if (${outputVar} === INVALID) return INVALID;`);
5038
- return outputVar;
5039
- }
5040
- return accessor;
5041
- }
5042
3404
  // node_modules/zod/v4/core/api.js
5043
3405
  function snapshotChecks(def) {
5044
3406
  if (def.checks)
@@ -7519,15 +5881,6 @@ function superRefine(fn, params) {
7519
5881
  // packages/workit-core/src/core/task-contract.ts
7520
5882
  var SCHEMA_VERSION = 1;
7521
5883
  var POLICY_VERSION = "1.0.0";
7522
- var OPERATION_FAMILIES = [
7523
- "task",
7524
- "policy",
7525
- "evidence",
7526
- "finding",
7527
- "decision",
7528
- "worker",
7529
- "state"
7530
- ];
7531
5884
  var uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
7532
5885
  var digestPattern = /^[0-9a-f]{64}$/;
7533
5886
  var invalidUnicode = (value) => {
@@ -8263,7 +6616,6 @@ var advertisedOperationSchemas = {
8263
6616
  worker: advertised(workerOperations),
8264
6617
  state: advertised(stateOperations)
8265
6618
  };
8266
- var compiledOperationSchemas = Object.fromEntries(OPERATION_FAMILIES.map((family) => [family, compile(operationSchemas[family])]));
8267
6619
  var success = (revisionValue, workspaceRevisionValue, data) => ({
8268
6620
  ok: true,
8269
6621
  schemaVersion: 1,
@@ -8285,8 +6637,7 @@ function resolveIdRef(kind, ref, ids) {
8285
6637
  function parseOperation(family, input) {
8286
6638
  if (typeof input === "object" && input !== null && "schemaVersion" in input && input.schemaVersion !== SCHEMA_VERSION)
8287
6639
  return failure2("unsupported_version", "unsupported schema version", { operation: family });
8288
- const compiled = compiledOperationSchemas[family].safeParse(input);
8289
- const parsed = compiled.success ? operationSchemas[family].safeParse(input) : compiled;
6640
+ const parsed = operationSchemas[family].safeParse(input);
8290
6641
  if (parsed.success)
8291
6642
  return success(null, null, parsed.data);
8292
6643
  const fields = parsed.error.issues.map((issue) => ({
@@ -18506,9 +16857,17 @@ var sessionMarkerFile = (input, session, store) => {
18506
16857
  return path20.join(dir, "hooks", `skills-${name}.json`);
18507
16858
  };
18508
16859
  var list2 = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
18509
- var readSessionMarker = (file) => {
16860
+ var EMPTY = { nudged: [], loaded: [], raw: [], stops: [], judges: [] };
16861
+ var readRaw = (file) => {
16862
+ try {
16863
+ return fs16.readFileSync(file, "utf8");
16864
+ } catch {
16865
+ return "";
16866
+ }
16867
+ };
16868
+ var parseMarker = (text) => {
18510
16869
  try {
18511
- const value = JSON.parse(fs16.readFileSync(file, "utf8"));
16870
+ const value = JSON.parse(text);
18512
16871
  return {
18513
16872
  nudged: list2(value.nudged),
18514
16873
  loaded: list2(value.loaded),
@@ -18517,13 +16876,36 @@ var readSessionMarker = (file) => {
18517
16876
  judges: list2(value.judges)
18518
16877
  };
18519
16878
  } catch {
18520
- return { nudged: [], loaded: [], raw: [], stops: [], judges: [] };
16879
+ return { ...EMPTY };
16880
+ }
16881
+ };
16882
+ var readSessionMarker = (file) => parseMarker(readRaw(file));
16883
+ var writeAtomic = (file, marker) => {
16884
+ fs16.mkdirSync(path20.dirname(file), { recursive: true });
16885
+ const temp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
16886
+ try {
16887
+ fs16.writeFileSync(temp, JSON.stringify(marker));
16888
+ fs16.renameSync(temp, file);
16889
+ } catch (error) {
16890
+ fs16.rmSync(temp, { force: true });
16891
+ throw error;
18521
16892
  }
18522
16893
  };
18523
16894
  var writeSessionMarker = (file, marker) => {
18524
16895
  try {
18525
- fs16.mkdirSync(path20.dirname(file), { recursive: true });
18526
- fs16.writeFileSync(file, JSON.stringify(marker));
16896
+ writeAtomic(file, marker);
16897
+ } catch {}
16898
+ };
16899
+ var updateSessionMarker = (file, change) => {
16900
+ try {
16901
+ for (let attempt = 0;attempt < 2; attempt++) {
16902
+ const before = readRaw(file);
16903
+ const next = change(parseMarker(before));
16904
+ if (attempt === 0 && readRaw(file) !== before)
16905
+ continue;
16906
+ writeAtomic(file, next);
16907
+ return;
16908
+ }
18527
16909
  } catch {}
18528
16910
  };
18529
16911
  var trackJudge = (input, agentId, running) => {
@@ -18531,9 +16913,10 @@ var trackJudge = (input, agentId, running) => {
18531
16913
  const file = session && agentId ? sessionMarkerFile(input, session) : null;
18532
16914
  if (!file || !agentId)
18533
16915
  return;
18534
- const marker = readSessionMarker(file);
18535
- const rest = marker.judges.filter((id) => id !== agentId);
18536
- writeSessionMarker(file, { ...marker, judges: running ? [...rest, agentId] : rest });
16916
+ updateSessionMarker(file, (marker) => {
16917
+ const rest = marker.judges.filter((id) => id !== agentId);
16918
+ return { ...marker, judges: running ? [...rest, agentId] : rest };
16919
+ });
18537
16920
  };
18538
16921
 
18539
16922
  // packages/workit-core/src/hooks/shell-words.ts
@@ -20182,8 +18565,8 @@ var offPolicyPush = (action, repo, facts, remote) => {
20182
18565
  var nudgeFor = (action, host, session) => {
20183
18566
  switch (action.kind) {
20184
18567
  case "commit": {
20185
- const prefix = host === "cursor" && session ? `WORKIT_SESSION_ID=${session} ` : "";
20186
- return action.amend ? `workit: raw ${quote("git commit --amend")} is recorded for this session; for new commits prefer ${quote(`${prefix}workit git commit -m '<msg>'`)} (adds the Workit-Session trailer and checks branch and commit policy).` : `workit: prefer ${quote(`${prefix}workit git commit -m '<msg>' [--all | -- <paths>]`)}: it adds the Workit-Session trailer and checks branch and commit policy.`;
18568
+ const workit = host === "cursor" && session ? `workit --session ${session}` : "workit";
18569
+ return action.amend ? `workit: raw ${quote("git commit --amend")} is recorded for this session; for new commits prefer ${quote(`${workit} git commit -m '<msg>'`)} (adds the Workit-Session trailer and checks branch and commit policy).` : `workit: prefer ${quote(`${workit} git commit -m '<msg>' [--all | -- <paths>]`)}: it adds the Workit-Session trailer and checks branch and commit policy.`;
20187
18570
  }
20188
18571
  case "push":
20189
18572
  return action.blindForce ? `workit: ${quote("git push --force")} overwrites without a lease; use ${quote("workit git push --force-with-lease")}.` : `workit: prefer ${quote("workit git push")}: it refuses protected branches and verifies the remote tip.`;
@@ -20584,7 +18967,7 @@ var shellPolicy = (cwd, command, dialect = "posix") => {
20584
18967
  import fs18 from "node:fs";
20585
18968
  import os6 from "node:os";
20586
18969
  import path23 from "node:path";
20587
- var EMPTY = () => ({ deny: [], allow: [] });
18970
+ var EMPTY2 = () => ({ deny: [], allow: [] });
20588
18971
  var readText2 = (file) => {
20589
18972
  try {
20590
18973
  return fs18.readFileSync(file, "utf8");
@@ -20661,7 +19044,7 @@ var bashPattern = (entry) => {
20661
19044
  return match ? match[1] ?? "" : null;
20662
19045
  };
20663
19046
  function claudeRules(cwd, env = process.env) {
20664
- const rules = EMPTY();
19047
+ const rules = EMPTY2();
20665
19048
  try {
20666
19049
  for (const file of claudeSettingsFiles(cwd, env)) {
20667
19050
  const text = readText2(file);
@@ -20741,7 +19124,7 @@ var opencodeConfig = (value, rules) => {
20741
19124
  return Object.values(value.agent).every((agent) => isRecord4(agent) && opencodePermission(agent.permission, rules));
20742
19125
  };
20743
19126
  function opencodeRules(cwd, env = process.env) {
20744
- const rules = EMPTY();
19127
+ const rules = EMPTY2();
20745
19128
  try {
20746
19129
  const config = env.XDG_CONFIG_HOME || path23.join(homeOf(env), ".config");
20747
19130
  const files = [
@@ -20788,7 +19171,7 @@ var codexRule = (body) => {
20788
19171
  return { pattern: words.join(" "), decision };
20789
19172
  };
20790
19173
  function codexRules(cwd, env = process.env) {
20791
- const rules = EMPTY();
19174
+ const rules = EMPTY2();
20792
19175
  try {
20793
19176
  const home = env.CODEX_HOME || path23.join(homeOf(env), ".codex");
20794
19177
  const top = gitTop(cwd) ?? cwd;
@@ -20817,7 +19200,7 @@ function codexRules(cwd, env = process.env) {
20817
19200
  return rules;
20818
19201
  }
20819
19202
  function cursorRules(cwd, env = process.env) {
20820
- const rules = EMPTY();
19203
+ const rules = EMPTY2();
20821
19204
  try {
20822
19205
  const top = gitTop(cwd) ?? cwd;
20823
19206
  for (const file of [
@@ -22145,25 +20528,29 @@ var redChecks = (rows, pr, head, endpoint) => {
22145
20528
  reason: `PR #${pr}'s checks were last seen ${state} at ${short(head)}, and this workspace's endpoint is \`${endpoint}\`: run \`workit ci wait --pr ${pr}\`${state === "failing" ? " after fixing the failures `workit pr status` lists (then push)" : ""}.`
22146
20529
  };
22147
20530
  };
22148
- var highRisk = (cwd) => {
20531
+ var taskJudgment = (cwd) => {
22149
20532
  try {
22150
20533
  const store = new TaskStore(cwd);
22151
20534
  const listed = store.listTaskIndex();
22152
20535
  const key = store.currentKey();
22153
20536
  if (!listed.ok || !key.ok)
22154
- return false;
20537
+ return null;
22155
20538
  const entry = listed.data.filter((item) => item.key === key.data.key && item.status !== "closed").toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt))[0];
22156
20539
  const task = entry ? store.readTask(entry.id) : null;
22157
- return task?.ok === true && latestJudgment(task.data)?.riskTier === "high";
20540
+ return task?.ok === true ? latestJudgment(task.data) : null;
22158
20541
  } catch {
22159
- return false;
20542
+ return null;
22160
20543
  }
22161
20544
  };
22162
20545
  var unverified = (cwd, branch, all, descriptor, verification) => {
22163
20546
  const check = checkVerdicts(cwd, branch, all);
22164
20547
  if (check.accepted.accepted || check.accepted.reasons.includes("failing_verdict"))
22165
20548
  return null;
22166
- const independent = verification === "independent" || highRisk(cwd);
20549
+ const judgment = taskJudgment(cwd);
20550
+ const high = judgment?.riskTier === "high";
20551
+ if (judgment && !judgment.behaviorChange && !high)
20552
+ return null;
20553
+ const independent = verification === "independent" || high;
22167
20554
  if (!independent && check.review === "self-reviewed")
22168
20555
  return null;
22169
20556
  const has = check.review === "self-reviewed" ? "only a self verdict" : "no current verdict";
@@ -22234,7 +20621,7 @@ function stopDecision(input, descriptor) {
22234
20621
  if (file && marker) {
22235
20622
  if (marker.stops.includes(key))
22236
20623
  return NONE4;
22237
- writeSessionMarker(file, { ...marker, stops: [...marker.stops, key] });
20624
+ updateSessionMarker(file, (fresh) => ({ ...fresh, stops: [...fresh.stops, key] }));
22238
20625
  }
22239
20626
  return {
22240
20627
  kind: "continue",
@@ -23831,7 +22218,7 @@ var cursorAdapter = {
23831
22218
  };
23832
22219
  },
23833
22220
  render: render3,
23834
- addendum: (input) => input.session.id ? `<workit-session>Cursor puts no session id in the shell: prefix workit commands that record authorship with WORKIT_SESSION_ID=${input.session.id} (e.g. \`WORKIT_SESSION_ID=${input.session.id} workit git commit -m …\`). A verifier uses its own id, never this one.</workit-session>` : null
22221
+ addendum: (input) => input.session.id ? `<workit-session>Cursor puts no session id in the shell: start workit commands that record authorship with the global flag \`--session ${input.session.id}\` (e.g. \`workit --session ${input.session.id} git commit -m …\`; a leading env assignment can miss the \`Shell(workit)\` allowlist). A verifier uses its own id, never this one.</workit-session>` : null
23835
22222
  };
23836
22223
 
23837
22224
  // packages/workit-core/src/hooks/run.ts