@go-labs-sg/event-tech 1.24.0 → 1.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../node_modules/.bun/dotenv@18.0.10/node_modules/dotenv/dist/index.cjs", "../../../../node_modules/.bun/process-nextick-args@2.0.1/node_modules/process-nextick-args/index.js", "../../../../node_modules/.bun/isarray@1.0.0/node_modules/isarray/index.js", "../../../../node_modules/.bun/safe-buffer@5.1.2/node_modules/safe-buffer/index.js", "../../../../node_modules/.bun/core-util-is@1.0.3/node_modules/core-util-is/lib/util.js", "../../../../node_modules/.bun/inherits@2.0.4/node_modules/inherits/inherits_browser.js", "../../../../node_modules/.bun/inherits@2.0.4/node_modules/inherits/inherits.js", "../../../../node_modules/.bun/readable-stream@2.3.8/node_modules/readable-stream/lib/internal/streams/BufferList.js", "../../../../node_modules/.bun/readable-stream@2.3.8/node_modules/readable-stream/lib/internal/streams/destroy.js", "../../../../node_modules/.bun/util-deprecate@1.0.2/node_modules/util-deprecate/node.js", "../../../../node_modules/.bun/readable-stream@2.3.8/node_modules/readable-stream/lib/_stream_writable.js", "../../../../node_modules/.bun/readable-stream@2.3.8/node_modules/readable-stream/lib/_stream_duplex.js", "../../../../node_modules/.bun/string_decoder@1.1.1/node_modules/string_decoder/lib/string_decoder.js", "../../../../node_modules/.bun/readable-stream@2.3.8/node_modules/readable-stream/lib/_stream_readable.js", "../../../../node_modules/.bun/readable-stream@2.3.8/node_modules/readable-stream/lib/_stream_transform.js", "../../../../node_modules/.bun/readable-stream@2.3.8/node_modules/readable-stream/lib/_stream_passthrough.js", "../../../../node_modules/.bun/readable-stream@2.3.8/node_modules/readable-stream/readable.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/support.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/base64.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/nodejsUtils.js", "../../../../node_modules/.bun/immediate@3.0.6/node_modules/immediate/lib/index.js", "../../../../node_modules/.bun/lie@3.3.0/node_modules/lie/lib/index.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/external.js", "../../../../node_modules/.bun/setimmediate@1.0.5/node_modules/setimmediate/setImmediate.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/utils.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/stream/GenericWorker.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/utf8.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/stream/ConvertWorker.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/nodejs/NodejsStreamOutputAdapter.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/stream/StreamHelper.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/defaults.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/stream/DataWorker.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/crc32.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/stream/Crc32Probe.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/stream/DataLengthProbe.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/compressedObject.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/zipObject.js", "../../../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/utils/common.js", "../../../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/trees.js", "../../../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/adler32.js", "../../../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/crc32.js", "../../../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/messages.js", "../../../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/deflate.js", "../../../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/utils/strings.js", "../../../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/zstream.js", "../../../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/deflate.js", "../../../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/inffast.js", "../../../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/inftrees.js", "../../../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/inflate.js", "../../../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/constants.js", "../../../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/zlib/gzheader.js", "../../../../node_modules/.bun/pako@1.0.11/node_modules/pako/lib/inflate.js", "../../../../node_modules/.bun/pako@1.0.11/node_modules/pako/index.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/flate.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/compressions.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/signature.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/generate/ZipFileWorker.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/generate/index.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/nodejs/NodejsStreamInputAdapter.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/object.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/reader/DataReader.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/reader/ArrayReader.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/reader/StringReader.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/reader/Uint8ArrayReader.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/reader/NodeBufferReader.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/reader/readerFor.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/zipEntry.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/zipEntries.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/load.js", "../../../../node_modules/.bun/jszip@3.10.2/node_modules/jszip/lib/index.js", "../../../../node_modules/.bun/papaparse@5.7.1/node_modules/papaparse/papaparse.js", "../src/load-env.ts", "../../../cli-auth/src/client/credential-store.ts", "../../../cli-auth/src/protocol/constants.ts", "../../../cli-auth/src/protocol/crypto.ts", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/util.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/core.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/errors.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/parse.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/regexes.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/checks.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/doc.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/versions.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/schemas.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/memoizer.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/locales/en.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/registries.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/api.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/to-json-schema.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/json-schema-processors.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/classic/errors.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/classic/parse.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/classic/schemas.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/classic/coerce.js", "../../../cli-auth/src/protocol/schemas.ts", "../../../cli-auth/src/client/secret-backend.ts", "../../../cli-auth/src/client/runtime.ts", "../../../cli-auth/src/client/storage-error.ts", "../../../cli-auth/src/client/login.ts", "../src/cli.ts", "../../db/src/generated/prisma/enums.ts", "../../validators/src/event-type.schema.ts", "../../../../node_modules/.bun/@trpc+server@11.28.3+431a08decb845963/node_modules/@trpc/server/dist/observable-CodTG6Sf.mjs", "../../../../node_modules/.bun/@trpc+server@11.28.3+431a08decb845963/node_modules/@trpc/server/dist/observable-BjUZYMQq.mjs", "../../../../node_modules/.bun/@trpc+client@11.28.3+82479501839ae062/node_modules/@trpc/client/dist/splitLink-PFsRy7Mf.mjs", "../../../../node_modules/.bun/@trpc+client@11.28.3+82479501839ae062/node_modules/@trpc/client/dist/objectSpread2-pyA4QVO4.mjs", "../../../../node_modules/.bun/@trpc+server@11.28.3+431a08decb845963/node_modules/@trpc/server/dist/codes-BCsCCyMj.mjs", "../../../../node_modules/.bun/@trpc+server@11.28.3+431a08decb845963/node_modules/@trpc/server/dist/getErrorShape-CVrl8_-w.mjs", "../../../../node_modules/.bun/@trpc+server@11.28.3+431a08decb845963/node_modules/@trpc/server/dist/asyncGeneratorDelegate-BRQGtkYG.mjs", "../../../../node_modules/.bun/@trpc+client@11.28.3+82479501839ae062/node_modules/@trpc/client/dist/TRPCClientError-DE6-fd1n.mjs", "../../../../node_modules/.bun/@trpc+client@11.28.3+82479501839ae062/node_modules/@trpc/client/dist/unstable-internals.mjs", "../../../../node_modules/.bun/@trpc+client@11.28.3+82479501839ae062/node_modules/@trpc/client/dist/httpUtils-CtMuyl9j.mjs", "../../../../node_modules/.bun/@trpc+client@11.28.3+82479501839ae062/node_modules/@trpc/client/dist/httpBatchLink-BkVNtNND.mjs", "../../../../node_modules/.bun/@trpc+client@11.28.3+82479501839ae062/node_modules/@trpc/client/dist/wsLink-BiIe_j6D.mjs", "../../../../node_modules/.bun/@trpc+client@11.28.3+82479501839ae062/node_modules/@trpc/client/dist/index.mjs", "../src/api-client.ts", "../src/config.ts", "../src/arguments.ts", "../src/runtime/index.ts", "../src/commands/index.ts", "../src/commands/lucky-draw-setup.ts", "../../db/src/lucky-draw-config-json.ts", "../../validators/src/lucky-draw/lucky-draw-config.schema.ts", "../../validators/src/lucky-draw/lucky-draw-config-input.schema.ts", "../../validators/src/lucky-draw/lucky-draw-prize-input.schema.ts", "../src/commands/passport.ts", "../../utils/src/lib/spreadsheet-table.ts", "../../validators/src/event-passport/passport-input.schema.ts", "../../validators/src/event-passport/passport-roster.schema.ts", "../../validators/src/event-passport/passport-station-access.schema.ts", "../src/commands/passport-media.ts", "../../utils/src/lib/event-s3-upload.ts", "../../utils/src/lib/event-theme.ts", "../../utils/src/lib/passport-skin.ts", "../../validators/src/photo-wall-screen.schema.ts", "../../validators/src/photo-wall-submission-settings.schema.ts", "../../validators/src/event-appearance.schema.ts", "../src/commands/staff-redemption.ts", "../../validators/src/staff-redemption/staff-redemption-input.schema.ts", "../../validators/src/staff-redemption/staff-redemption-roster.schema.ts", "../src/registry/run-registry-command.ts", "../src/index.ts"],
4
+ "sourcesContent": ["var j=(e,n)=>()=>{try{return n||e((n={exports:{}}).exports,n),n.exports}catch(t){throw n=0,t}};var R=j((Z,N)=>{function T(e){return typeof e==\"string\"?![\"false\",\"0\",\"no\",\"off\",\"\"].includes(e.toLowerCase()):!!e}function U(e=process.env){let n={};for(let t of[\"ENCODING\",\"PATH\",\"QUIET\",\"DEBUG\",\"OVERRIDE\",\"FAST\"]){let r=e[`DOTENV_${t}`]!=null?e[`DOTENV_${t}`]:e[`DOTENV_CONFIG_${t}`];r!=null&&(n[t.toLowerCase()]=t===\"ENCODING\"||t===\"PATH\"?r:T(r))}return n}N.exports={parseBoolean:T,optionsFromEnv:U}});var P=j((ee,b)=>{var F=require(\"fs\"),_=require(\"path\"),B=require(\"os\"),{URL:L,fileURLToPath:Q}=require(\"url\"),{parseBoolean:$,optionsFromEnv:I}=R(),G=/(?:^|^)\\s*(?:export\\s+)?([\\w.-]+)(?:\\s*=\\s*?|:\\s+?)(\\s*'(?:\\\\'|[^'])*'|\\s*\"(?:\\\\\"|[^\"])*\"|\\s*`(?:\\\\`|[^`])*`|[^#\\r\\n]+)?\\s*(?:#.*)?(?:$|$)/mg,y=new Uint8Array(256);for(let e=48;e<=57;e++)y[e]=1;for(let e=65;e<=90;e++)y[e]=1;for(let e=97;e<=122;e++)y[e]=1;y[45]=1;y[46]=1;y[95]=1;function H(e){let n={},t=e.toString();t=t.replace(/\\r\\n?/mg,`\n`);let r;for(;(r=G.exec(t))!=null;){let o=r[1],i=r[2]||\"\";i=i.trim();let c=i[0];i=i.replace(/^(['\"`])([\\s\\S]*)\\1$/mg,\"$2\"),c==='\"'&&(i=i.replace(/\\\\n/g,`\n`),i=i.replace(/\\\\r/g,\"\\r\")),n[o]=i}return n}function g(e){return e<=32?e===32||e>=9&&e<=13:e>=160&&(e===160||e===5760||e>=8192&&e<=8202||e===8232||e===8233||e===8239||e===8287||e===12288||e===65279)}function O(e){return e===10||e===8232||e===8233}function V(e){let n={},t=typeof e==\"string\"?e:e.toString();t.indexOf(\"\\r\")!==-1&&(t=t.replace(/\\r\\n?/g,`\n`));let r=t.length,o=0;for(;o<r;){let i=t.charCodeAt(o);for(;o<r&&g(i);)o++,i=t.charCodeAt(o);if(o>=r)break;if(i===35){for(;o<r&&!O(t.charCodeAt(o));)o++;continue}let c=-1;if(i===101&&o+6<r&&t.charCodeAt(o+1)===120&&t.charCodeAt(o+2)===112&&t.charCodeAt(o+3)===111&&t.charCodeAt(o+4)===114&&t.charCodeAt(o+5)===116){let u=t.charCodeAt(o+6);if(g(u)){let s=o+7;for(;s<r&&g(t.charCodeAt(s));)s++;y[t.charCodeAt(s)]&&(c=o+6,o=s)}else i=t.charCodeAt(o)}let E=o,p=0;for(;o<r&&(p=t.charCodeAt(o),y[p]);)o++;if(o===E){for(;o<r&&!O(t.charCodeAt(o));)o++;continue}let k=t.slice(E,o),D=o;if(o>=r&&(p=0),g(p))do o++,p=o<r?t.charCodeAt(o):0;while(g(p));if(p===61)o++;else if(p===58&&o===D&&o+1<r&&g(t.charCodeAt(o+1)))o+=2;else{for(o=c===-1?D:c;o<r&&!O(t.charCodeAt(o));)o++;continue}let d=o,l=o;for(;l<r&&g(t.charCodeAt(l));)l++;let C=t.charCodeAt(l),a,q=!1;if(C===39||C===34||C===96){let u=t[l],s=t.indexOf(u,l+1),f=-1,h=-1;for(;s!==-1;){let x=t.charCodeAt(s-1)===92,w=s+1;for(;w<r&&!O(t.charCodeAt(w))&&g(t.charCodeAt(w));)w++;if((w===r||O(t.charCodeAt(w))||t.charCodeAt(w)===35)&&(f=s,h=w),!x)break;s=t.indexOf(u,s+1)}if(f!==-1){if(a=t.slice(l+1,f),o=h,t.charCodeAt(o)===35)for(;o<r&&!O(t.charCodeAt(o));)o++;q=!0}}if(!q){let u=t.indexOf(`\n`,d);u===-1&&(u=r);let s;if(r<4096)s=t.indexOf(\"#\",d),(s===-1||s>u)&&(s=u);else for(s=d;s<u&&t.charCodeAt(s)!==35;)s++;let f=d,h=s;for(;f<h&&g(t.charCodeAt(f));)f++;for(;h>f&&g(t.charCodeAt(h-1));)h--;let x=t.charCodeAt(f);if(a=t.slice(f,h),a.includes(\"\\u2028\")||a.includes(\"\\u2029\")?a=a.replace(/^(['\"`])([\\s\\S]*)\\1$/mg,\"$2\"):h-f>=2&&(x===39||x===34||x===96)&&t.charCodeAt(h-1)===x&&(a=t.slice(f+1,h-1)),o=s,s<u)for(;o<r&&!O(t.charCodeAt(o));)o++}C===34&&(q||l<o)&&a.indexOf(\"\\\\\")!==-1&&(a=a.replace(/\\\\n/g,`\n`).replace(/\\\\r/g,\"\\r\")),n[k]=a}return n}function J(e,n){return n&&$(n.fast)?V(e):H(e)}function v(e){console.log(`\\u2506 ${e}`)}function W(e){console.error(`\\u25C7 ${e}`)}function S(e){return e[0]===\"~\"?_.join(B.homedir(),e.slice(1)):e}function K(e={}){let n={...e};for(let t of Object.keys(n))n[t]===void 0&&delete n[t];return{...I(),...n}}function M(e){e=K(e);let n=_.resolve(process.cwd(),\".env\"),t=\"utf8\",r=process.env;e&&e.processEnv!=null&&(r=e.processEnv);let o=$(e&&e.debug);e&&e.encoding?t=e.encoding:o&&v(\"no encoding is specified (UTF-8 is used by default)\");let i=[n];if(e&&e.path)if(!Array.isArray(e.path))i=[S(e.path)];else{i=[];for(let d of e.path)i.push(S(d))}let c,E={},p={fast:e.fast};for(let d of i)try{let l=A.parse(F.readFileSync(d,{encoding:t}),p);A.populate(E,l,e)}catch(l){o&&v(`failed to load ${d} ${l.message}`),c=l}let k=A.populate(r,E,e),D=$(Object.prototype.hasOwnProperty.call(e,\"quiet\")?e.quiet:I(r).quiet);if(o||!D){let d=Object.keys(k).length,l=[];for(let C of i)try{let a=_.relative(process.cwd(),C instanceof L?Q(C):C);l.push(a)}catch(a){o&&v(`failed to load ${C} ${a.message}`),c=a}W(`injected env (${d}) from ${l.join(\",\")}`)}return c?{parsed:E,error:c}:{parsed:E}}function Y(e){return A.configDotenv(e)}function z(e,n,t={}){let r=$(t&&t.debug),o=$(t&&t.override),i={};if(e===null||typeof e!=\"object\"||n===null||typeof n!=\"object\"){let c=new Error(\"OBJECT_REQUIRED: Please check the processEnv argument being passed to populate\");throw c.code=\"OBJECT_REQUIRED\",c}for(let c of Object.keys(n))Object.prototype.hasOwnProperty.call(e,c)?(o===!0&&(e[c]=n[c],i[c]=n[c]),r&&v(o===!0?`\"${c}\" is already defined and WAS overwritten`:`\"${c}\" is already defined and was NOT overwritten`)):(e[c]=n[c],i[c]=n[c]);return i}var A={configDotenv:M,config:Y,parse:J,populate:z};b.exports.configDotenv=A.configDotenv;b.exports.config=A.config;b.exports.parse=A.parse;b.exports.populate=A.populate;b.exports=A});var m=P();module.exports=m;module.exports.config=m.config;module.exports.configDotenv=m.configDotenv;module.exports.parse=m.parse;module.exports.populate=m.populate;\n", "'use strict';\n\nif (typeof process === 'undefined' ||\n !process.version ||\n process.version.indexOf('v0.') === 0 ||\n process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {\n module.exports = { nextTick: nextTick };\n} else {\n module.exports = process\n}\n\nfunction nextTick(fn, arg1, arg2, arg3) {\n if (typeof fn !== 'function') {\n throw new TypeError('\"callback\" argument must be a function');\n }\n var len = arguments.length;\n var args, i;\n switch (len) {\n case 0:\n case 1:\n return process.nextTick(fn);\n case 2:\n return process.nextTick(function afterTickOne() {\n fn.call(null, arg1);\n });\n case 3:\n return process.nextTick(function afterTickTwo() {\n fn.call(null, arg1, arg2);\n });\n case 4:\n return process.nextTick(function afterTickThree() {\n fn.call(null, arg1, arg2, arg3);\n });\n default:\n args = new Array(len - 1);\n i = 0;\n while (i < args.length) {\n args[i++] = arguments[i];\n }\n return process.nextTick(function afterTick() {\n fn.apply(null, args);\n });\n }\n}\n\n", "var toString = {}.toString;\n\nmodule.exports = Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n", "/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// NOTE: These type checking functions intentionally don't use `instanceof`\n// because it is fragile and can be easily faked with `Object.create()`.\n\nfunction isArray(arg) {\n if (Array.isArray) {\n return Array.isArray(arg);\n }\n return objectToString(arg) === '[object Array]';\n}\nexports.isArray = isArray;\n\nfunction isBoolean(arg) {\n return typeof arg === 'boolean';\n}\nexports.isBoolean = isBoolean;\n\nfunction isNull(arg) {\n return arg === null;\n}\nexports.isNull = isNull;\n\nfunction isNullOrUndefined(arg) {\n return arg == null;\n}\nexports.isNullOrUndefined = isNullOrUndefined;\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\nexports.isNumber = isNumber;\n\nfunction isString(arg) {\n return typeof arg === 'string';\n}\nexports.isString = isString;\n\nfunction isSymbol(arg) {\n return typeof arg === 'symbol';\n}\nexports.isSymbol = isSymbol;\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\nexports.isUndefined = isUndefined;\n\nfunction isRegExp(re) {\n return objectToString(re) === '[object RegExp]';\n}\nexports.isRegExp = isRegExp;\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\nexports.isObject = isObject;\n\nfunction isDate(d) {\n return objectToString(d) === '[object Date]';\n}\nexports.isDate = isDate;\n\nfunction isError(e) {\n return (objectToString(e) === '[object Error]' || e instanceof Error);\n}\nexports.isError = isError;\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\nexports.isFunction = isFunction;\n\nfunction isPrimitive(arg) {\n return arg === null ||\n typeof arg === 'boolean' ||\n typeof arg === 'number' ||\n typeof arg === 'string' ||\n typeof arg === 'symbol' || // ES6 symbol\n typeof arg === 'undefined';\n}\nexports.isPrimitive = isPrimitive;\n\nexports.isBuffer = require('buffer').Buffer.isBuffer;\n\nfunction objectToString(o) {\n return Object.prototype.toString.call(o);\n}\n", "if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n })\n }\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n }\n}\n", "try {\n var util = require('util');\n /* istanbul ignore next */\n if (typeof util.inherits !== 'function') throw '';\n module.exports = util.inherits;\n} catch (e) {\n /* istanbul ignore next */\n module.exports = require('./inherits_browser.js');\n}\n", "'use strict';\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar Buffer = require('safe-buffer').Buffer;\nvar util = require('util');\n\nfunction copyBuffer(src, target, offset) {\n src.copy(target, offset);\n}\n\nmodule.exports = function () {\n function BufferList() {\n _classCallCheck(this, BufferList);\n\n this.head = null;\n this.tail = null;\n this.length = 0;\n }\n\n BufferList.prototype.push = function push(v) {\n var entry = { data: v, next: null };\n if (this.length > 0) this.tail.next = entry;else this.head = entry;\n this.tail = entry;\n ++this.length;\n };\n\n BufferList.prototype.unshift = function unshift(v) {\n var entry = { data: v, next: this.head };\n if (this.length === 0) this.tail = entry;\n this.head = entry;\n ++this.length;\n };\n\n BufferList.prototype.shift = function shift() {\n if (this.length === 0) return;\n var ret = this.head.data;\n if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;\n --this.length;\n return ret;\n };\n\n BufferList.prototype.clear = function clear() {\n this.head = this.tail = null;\n this.length = 0;\n };\n\n BufferList.prototype.join = function join(s) {\n if (this.length === 0) return '';\n var p = this.head;\n var ret = '' + p.data;\n while (p = p.next) {\n ret += s + p.data;\n }return ret;\n };\n\n BufferList.prototype.concat = function concat(n) {\n if (this.length === 0) return Buffer.alloc(0);\n var ret = Buffer.allocUnsafe(n >>> 0);\n var p = this.head;\n var i = 0;\n while (p) {\n copyBuffer(p.data, ret, i);\n i += p.data.length;\n p = p.next;\n }\n return ret;\n };\n\n return BufferList;\n}();\n\nif (util && util.inspect && util.inspect.custom) {\n module.exports.prototype[util.inspect.custom] = function () {\n var obj = util.inspect({ length: this.length });\n return this.constructor.name + ' ' + obj;\n };\n}", "'use strict';\n\n/*<replacement>*/\n\nvar pna = require('process-nextick-args');\n/*</replacement>*/\n\n// undocumented cb() API, needed for core, not for public API\nfunction destroy(err, cb) {\n var _this = this;\n\n var readableDestroyed = this._readableState && this._readableState.destroyed;\n var writableDestroyed = this._writableState && this._writableState.destroyed;\n\n if (readableDestroyed || writableDestroyed) {\n if (cb) {\n cb(err);\n } else if (err) {\n if (!this._writableState) {\n pna.nextTick(emitErrorNT, this, err);\n } else if (!this._writableState.errorEmitted) {\n this._writableState.errorEmitted = true;\n pna.nextTick(emitErrorNT, this, err);\n }\n }\n\n return this;\n }\n\n // we set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n\n if (this._readableState) {\n this._readableState.destroyed = true;\n }\n\n // if this is a duplex stream mark the writable part as destroyed as well\n if (this._writableState) {\n this._writableState.destroyed = true;\n }\n\n this._destroy(err || null, function (err) {\n if (!cb && err) {\n if (!_this._writableState) {\n pna.nextTick(emitErrorNT, _this, err);\n } else if (!_this._writableState.errorEmitted) {\n _this._writableState.errorEmitted = true;\n pna.nextTick(emitErrorNT, _this, err);\n }\n } else if (cb) {\n cb(err);\n }\n });\n\n return this;\n}\n\nfunction undestroy() {\n if (this._readableState) {\n this._readableState.destroyed = false;\n this._readableState.reading = false;\n this._readableState.ended = false;\n this._readableState.endEmitted = false;\n }\n\n if (this._writableState) {\n this._writableState.destroyed = false;\n this._writableState.ended = false;\n this._writableState.ending = false;\n this._writableState.finalCalled = false;\n this._writableState.prefinished = false;\n this._writableState.finished = false;\n this._writableState.errorEmitted = false;\n }\n}\n\nfunction emitErrorNT(self, err) {\n self.emit('error', err);\n}\n\nmodule.exports = {\n destroy: destroy,\n undestroy: undestroy\n};", "\n/**\n * For Node.js, simply re-export the core `util.deprecate` function.\n */\n\nmodule.exports = require('util').deprecate;\n", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n\n'use strict';\n\n/*<replacement>*/\n\nvar pna = require('process-nextick-args');\n/*</replacement>*/\n\nmodule.exports = Writable;\n\n/* <replacement> */\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n}\n\n// It seems a linked list but it is not\n// there will be only 2 of these for each stream\nfunction CorkedRequest(state) {\n var _this = this;\n\n this.next = null;\n this.entry = null;\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* </replacement> */\n\n/*<replacement>*/\nvar asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;\n/*</replacement>*/\n\n/*<replacement>*/\nvar Duplex;\n/*</replacement>*/\n\nWritable.WritableState = WritableState;\n\n/*<replacement>*/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/*</replacement>*/\n\n/*<replacement>*/\nvar internalUtil = {\n deprecate: require('util-deprecate')\n};\n/*</replacement>*/\n\n/*<replacement>*/\nvar Stream = require('./internal/streams/stream');\n/*</replacement>*/\n\n/*<replacement>*/\n\nvar Buffer = require('safe-buffer').Buffer;\nvar OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\n/*</replacement>*/\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nutil.inherits(Writable, Stream);\n\nfunction nop() {}\n\nfunction WritableState(options, stream) {\n Duplex = Duplex || require('./_stream_duplex');\n\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n var isDuplex = stream instanceof Duplex;\n\n // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n this.objectMode = !!options.objectMode;\n\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;\n\n // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n var hwm = options.highWaterMark;\n var writableHwm = options.writableHighWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n\n if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;\n\n // cast to ints.\n this.highWaterMark = Math.floor(this.highWaterMark);\n\n // if _final has been called\n this.finalCalled = false;\n\n // drain event flag.\n this.needDrain = false;\n // at the start of calling end()\n this.ending = false;\n // when end() has been called, and returned\n this.ended = false;\n // when 'finish' is emitted\n this.finished = false;\n\n // has it been destroyed\n this.destroyed = false;\n\n // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n this.length = 0;\n\n // a flag to see when we're in the middle of a write.\n this.writing = false;\n\n // when true all writes will be buffered until .uncork() call\n this.corked = 0;\n\n // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n this.sync = true;\n\n // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n this.bufferProcessing = false;\n\n // the callback that's passed to _write(chunk,cb)\n this.onwrite = function (er) {\n onwrite(stream, er);\n };\n\n // the callback that the user supplies to write(chunk,encoding,cb)\n this.writecb = null;\n\n // the amount that is being written when _write is called.\n this.writelen = 0;\n\n this.bufferedRequest = null;\n this.lastBufferedRequest = null;\n\n // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n this.pendingcb = 0;\n\n // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n this.prefinished = false;\n\n // True if the error was already emitted and should not be thrown again\n this.errorEmitted = false;\n\n // count buffered requests\n this.bufferedRequestCount = 0;\n\n // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n this.corkedRequestsFree = new CorkedRequest(this);\n}\n\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n while (current) {\n out.push(current);\n current = current.next;\n }\n return out;\n};\n\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function () {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})();\n\n// Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\nvar realHasInstance;\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function (object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function (object) {\n return object instanceof this;\n };\n}\n\nfunction Writable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n\n // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {\n return new Writable(options);\n }\n\n this._writableState = new WritableState(options, this);\n\n // legacy.\n this.writable = true;\n\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n\n if (typeof options.writev === 'function') this._writev = options.writev;\n\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n\n if (typeof options.final === 'function') this._final = options.final;\n }\n\n Stream.call(this);\n}\n\n// Otherwise people can pipe Writable streams, which is just wrong.\nWritable.prototype.pipe = function () {\n this.emit('error', new Error('Cannot pipe, not readable'));\n};\n\nfunction writeAfterEnd(stream, cb) {\n var er = new Error('write after end');\n // TODO: defer error events consistently everywhere, not just the cb\n stream.emit('error', er);\n pna.nextTick(cb, er);\n}\n\n// Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\nfunction validChunk(stream, state, chunk, cb) {\n var valid = true;\n var er = false;\n\n if (chunk === null) {\n er = new TypeError('May not write null values to stream');\n } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n if (er) {\n stream.emit('error', er);\n pna.nextTick(cb, er);\n valid = false;\n }\n return valid;\n}\n\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n\n if (typeof cb !== 'function') cb = nop;\n\n if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n\n return ret;\n};\n\nWritable.prototype.cork = function () {\n var state = this._writableState;\n\n state.corked++;\n};\n\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n\n if (state.corked) {\n state.corked--;\n\n if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\n\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n return chunk;\n}\n\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._writableState.highWaterMark;\n }\n});\n\n// if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n var len = state.objectMode ? 1 : chunk.length;\n\n state.length += len;\n\n var ret = state.length < state.highWaterMark;\n // we must ensure that previous needDrain will not be reset to false.\n if (!ret) state.needDrain = true;\n\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n\n return ret;\n}\n\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n pna.nextTick(cb, er);\n // this can emit finish, and it will always happen\n // after error\n pna.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n // this can emit finish, but finish must\n // always follow error\n finishMaybe(stream, state);\n }\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n\n onwriteStateUpdate(state);\n\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state);\n\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n\n if (sync) {\n /*<replacement>*/\n asyncWrite(afterWrite, stream, state, finished, cb);\n /*</replacement>*/\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n}\n\n// Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n}\n\n// if there's something in the buffer waiting, then process it\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n\n var count = 0;\n var allBuffers = true;\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n buffer.allBuffers = allBuffers;\n\n doWrite(stream, state, true, state.length, buffer, '', holder.finish);\n\n // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n state.pendingcb++;\n state.lastBufferedRequest = null;\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--;\n // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n if (state.writing) {\n break;\n }\n }\n\n if (entry === null) state.lastBufferedRequest = null;\n }\n\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\n\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new Error('_write() is not implemented'));\n};\n\nWritable.prototype._writev = null;\n\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);\n\n // .end() fully uncorks\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n }\n\n // ignore unnecessary end() calls.\n if (!state.ending) endWritable(this, state, cb);\n};\n\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n if (err) {\n stream.emit('error', err);\n }\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function') {\n state.pendingcb++;\n state.finalCalled = true;\n pna.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n if (need) {\n prefinish(stream, state);\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n }\n }\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n if (cb) {\n if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);\n }\n state.ended = true;\n stream.writable = false;\n}\n\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n }\n\n // reuse the free corkReq.\n state.corkedRequestsFree.next = corkReq;\n}\n\nObject.defineProperty(Writable.prototype, 'destroyed', {\n get: function () {\n if (this._writableState === undefined) {\n return false;\n }\n return this._writableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._writableState.destroyed = value;\n }\n});\n\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\nWritable.prototype._destroy = function (err, cb) {\n this.end();\n cb(err);\n};", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n\n'use strict';\n\n/*<replacement>*/\n\nvar pna = require('process-nextick-args');\n/*</replacement>*/\n\n/*<replacement>*/\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n for (var key in obj) {\n keys.push(key);\n }return keys;\n};\n/*</replacement>*/\n\nmodule.exports = Duplex;\n\n/*<replacement>*/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/*</replacement>*/\n\nvar Readable = require('./_stream_readable');\nvar Writable = require('./_stream_writable');\n\nutil.inherits(Duplex, Readable);\n\n{\n // avoid scope creep, the keys array can then be collected\n var keys = objectKeys(Writable.prototype);\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n\n Readable.call(this, options);\n Writable.call(this, options);\n\n if (options && options.readable === false) this.readable = false;\n\n if (options && options.writable === false) this.writable = false;\n\n this.allowHalfOpen = true;\n if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;\n\n this.once('end', onend);\n}\n\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._writableState.highWaterMark;\n }\n});\n\n// the no-half-open enforcer\nfunction onend() {\n // if we allow half-open state, or if the writable side ended,\n // then we're ok.\n if (this.allowHalfOpen || this._writableState.ended) return;\n\n // no more data can be written.\n // But allow more writes to happen in this tick.\n pna.nextTick(onEndNT, this);\n}\n\nfunction onEndNT(self) {\n self.end();\n}\n\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n get: function () {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});\n\nDuplex.prototype._destroy = function (err, cb) {\n this.push(null);\n this.end();\n\n pna.nextTick(cb, err);\n};", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/*<replacement>*/\n\nvar Buffer = require('safe-buffer').Buffer;\n/*</replacement>*/\n\nvar isEncoding = Buffer.isEncoding || function (encoding) {\n encoding = '' + encoding;\n switch (encoding && encoding.toLowerCase()) {\n case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':\n return true;\n default:\n return false;\n }\n};\n\nfunction _normalizeEncoding(enc) {\n if (!enc) return 'utf8';\n var retried;\n while (true) {\n switch (enc) {\n case 'utf8':\n case 'utf-8':\n return 'utf8';\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return 'utf16le';\n case 'latin1':\n case 'binary':\n return 'latin1';\n case 'base64':\n case 'ascii':\n case 'hex':\n return enc;\n default:\n if (retried) return; // undefined\n enc = ('' + enc).toLowerCase();\n retried = true;\n }\n }\n};\n\n// Do not cache `Buffer.isEncoding` when checking encoding names as some\n// modules monkey-patch it to support additional encodings\nfunction normalizeEncoding(enc) {\n var nenc = _normalizeEncoding(enc);\n if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);\n return nenc || enc;\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters.\nexports.StringDecoder = StringDecoder;\nfunction StringDecoder(encoding) {\n this.encoding = normalizeEncoding(encoding);\n var nb;\n switch (this.encoding) {\n case 'utf16le':\n this.text = utf16Text;\n this.end = utf16End;\n nb = 4;\n break;\n case 'utf8':\n this.fillLast = utf8FillLast;\n nb = 4;\n break;\n case 'base64':\n this.text = base64Text;\n this.end = base64End;\n nb = 3;\n break;\n default:\n this.write = simpleWrite;\n this.end = simpleEnd;\n return;\n }\n this.lastNeed = 0;\n this.lastTotal = 0;\n this.lastChar = Buffer.allocUnsafe(nb);\n}\n\nStringDecoder.prototype.write = function (buf) {\n if (buf.length === 0) return '';\n var r;\n var i;\n if (this.lastNeed) {\n r = this.fillLast(buf);\n if (r === undefined) return '';\n i = this.lastNeed;\n this.lastNeed = 0;\n } else {\n i = 0;\n }\n if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);\n return r || '';\n};\n\nStringDecoder.prototype.end = utf8End;\n\n// Returns only complete characters in a Buffer\nStringDecoder.prototype.text = utf8Text;\n\n// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer\nStringDecoder.prototype.fillLast = function (buf) {\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);\n this.lastNeed -= buf.length;\n};\n\n// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a\n// continuation byte. If an invalid byte is detected, -2 is returned.\nfunction utf8CheckByte(byte) {\n if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;\n return byte >> 6 === 0x02 ? -1 : -2;\n}\n\n// Checks at most 3 bytes at the end of a Buffer in order to detect an\n// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)\n// needed to complete the UTF-8 character (if applicable) are returned.\nfunction utf8CheckIncomplete(self, buf, i) {\n var j = buf.length - 1;\n if (j < i) return 0;\n var nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 1;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 2;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) {\n if (nb === 2) nb = 0;else self.lastNeed = nb - 3;\n }\n return nb;\n }\n return 0;\n}\n\n// Validates as many continuation bytes for a multi-byte UTF-8 character as\n// needed or are available. If we see a non-continuation byte where we expect\n// one, we \"replace\" the validated continuation bytes we've seen so far with\n// a single UTF-8 replacement character ('\\ufffd'), to match v8's UTF-8 decoding\n// behavior. The continuation byte check is included three times in the case\n// where all of the continuation bytes for a character exist in the same buffer.\n// It is also done this way as a slight performance increase instead of using a\n// loop.\nfunction utf8CheckExtraBytes(self, buf, p) {\n if ((buf[0] & 0xC0) !== 0x80) {\n self.lastNeed = 0;\n return '\\ufffd';\n }\n if (self.lastNeed > 1 && buf.length > 1) {\n if ((buf[1] & 0xC0) !== 0x80) {\n self.lastNeed = 1;\n return '\\ufffd';\n }\n if (self.lastNeed > 2 && buf.length > 2) {\n if ((buf[2] & 0xC0) !== 0x80) {\n self.lastNeed = 2;\n return '\\ufffd';\n }\n }\n }\n}\n\n// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.\nfunction utf8FillLast(buf) {\n var p = this.lastTotal - this.lastNeed;\n var r = utf8CheckExtraBytes(this, buf, p);\n if (r !== undefined) return r;\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, p, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, p, 0, buf.length);\n this.lastNeed -= buf.length;\n}\n\n// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a\n// partial character, the character's bytes are buffered until the required\n// number of bytes are available.\nfunction utf8Text(buf, i) {\n var total = utf8CheckIncomplete(this, buf, i);\n if (!this.lastNeed) return buf.toString('utf8', i);\n this.lastTotal = total;\n var end = buf.length - (total - this.lastNeed);\n buf.copy(this.lastChar, 0, end);\n return buf.toString('utf8', i, end);\n}\n\n// For UTF-8, a replacement character is added when ending on a partial\n// character.\nfunction utf8End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + '\\ufffd';\n return r;\n}\n\n// UTF-16LE typically needs two bytes per character, but even if we have an even\n// number of bytes available, we need to check if we end on a leading/high\n// surrogate. In that case, we need to wait for the next two bytes in order to\n// decode the last character properly.\nfunction utf16Text(buf, i) {\n if ((buf.length - i) % 2 === 0) {\n var r = buf.toString('utf16le', i);\n if (r) {\n var c = r.charCodeAt(r.length - 1);\n if (c >= 0xD800 && c <= 0xDBFF) {\n this.lastNeed = 2;\n this.lastTotal = 4;\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n return r.slice(0, -1);\n }\n }\n return r;\n }\n this.lastNeed = 1;\n this.lastTotal = 2;\n this.lastChar[0] = buf[buf.length - 1];\n return buf.toString('utf16le', i, buf.length - 1);\n}\n\n// For UTF-16LE we do not explicitly append special replacement characters if we\n// end on a partial character, we simply let v8 handle that.\nfunction utf16End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) {\n var end = this.lastTotal - this.lastNeed;\n return r + this.lastChar.toString('utf16le', 0, end);\n }\n return r;\n}\n\nfunction base64Text(buf, i) {\n var n = (buf.length - i) % 3;\n if (n === 0) return buf.toString('base64', i);\n this.lastNeed = 3 - n;\n this.lastTotal = 3;\n if (n === 1) {\n this.lastChar[0] = buf[buf.length - 1];\n } else {\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n }\n return buf.toString('base64', i, buf.length - n);\n}\n\nfunction base64End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);\n return r;\n}\n\n// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)\nfunction simpleWrite(buf) {\n return buf.toString(this.encoding);\n}\n\nfunction simpleEnd(buf) {\n return buf && buf.length ? this.write(buf) : '';\n}", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/*<replacement>*/\n\nvar pna = require('process-nextick-args');\n/*</replacement>*/\n\nmodule.exports = Readable;\n\n/*<replacement>*/\nvar isArray = require('isarray');\n/*</replacement>*/\n\n/*<replacement>*/\nvar Duplex;\n/*</replacement>*/\n\nReadable.ReadableState = ReadableState;\n\n/*<replacement>*/\nvar EE = require('events').EventEmitter;\n\nvar EElistenerCount = function (emitter, type) {\n return emitter.listeners(type).length;\n};\n/*</replacement>*/\n\n/*<replacement>*/\nvar Stream = require('./internal/streams/stream');\n/*</replacement>*/\n\n/*<replacement>*/\n\nvar Buffer = require('safe-buffer').Buffer;\nvar OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\n/*</replacement>*/\n\n/*<replacement>*/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/*</replacement>*/\n\n/*<replacement>*/\nvar debugUtil = require('util');\nvar debug = void 0;\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function () {};\n}\n/*</replacement>*/\n\nvar BufferList = require('./internal/streams/BufferList');\nvar destroyImpl = require('./internal/streams/destroy');\nvar StringDecoder;\n\nutil.inherits(Readable, Stream);\n\nvar kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];\n\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);\n\n // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];\n}\n\nfunction ReadableState(options, stream) {\n Duplex = Duplex || require('./_stream_duplex');\n\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n var isDuplex = stream instanceof Duplex;\n\n // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n this.objectMode = !!options.objectMode;\n\n if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;\n\n // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n var hwm = options.highWaterMark;\n var readableHwm = options.readableHighWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n\n if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;\n\n // cast to ints.\n this.highWaterMark = Math.floor(this.highWaterMark);\n\n // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false;\n\n // a flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n this.sync = true;\n\n // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n\n // has it been destroyed\n this.destroyed = false;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // the number of writers that are awaiting a drain event in .pipe()s\n this.awaitDrain = 0;\n\n // if true, a maybeReadMore has been scheduled\n this.readingMore = false;\n\n this.decoder = null;\n this.encoding = null;\n if (options.encoding) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nfunction Readable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n\n if (!(this instanceof Readable)) return new Readable(options);\n\n this._readableState = new ReadableState(options, this);\n\n // legacy\n this.readable = true;\n\n if (options) {\n if (typeof options.read === 'function') this._read = options.read;\n\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n }\n\n Stream.call(this);\n}\n\nObject.defineProperty(Readable.prototype, 'destroyed', {\n get: function () {\n if (this._readableState === undefined) {\n return false;\n }\n return this._readableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._readableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n }\n});\n\nReadable.prototype.destroy = destroyImpl.destroy;\nReadable.prototype._undestroy = destroyImpl.undestroy;\nReadable.prototype._destroy = function (err, cb) {\n this.push(null);\n cb(err);\n};\n\n// Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n var skipChunkCheck;\n\n if (!state.objectMode) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n skipChunkCheck = true;\n }\n } else {\n skipChunkCheck = true;\n }\n\n return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);\n};\n\n// Unshift should *always* be something directly out of read()\nReadable.prototype.unshift = function (chunk) {\n return readableAddChunk(this, chunk, null, true, false);\n};\n\nfunction readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {\n var state = stream._readableState;\n if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else {\n var er;\n if (!skipChunkCheck) er = chunkInvalid(state, chunk);\n if (er) {\n stream.emit('error', er);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (addToFront) {\n if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);\n } else if (state.ended) {\n stream.emit('error', new Error('stream.push() after EOF'));\n } else {\n state.reading = false;\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk);\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);\n } else {\n addChunk(stream, state, chunk, false);\n }\n }\n } else if (!addToFront) {\n state.reading = false;\n }\n }\n\n return needMoreData(state);\n}\n\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync) {\n stream.emit('data', chunk);\n stream.read(0);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n\n if (state.needReadable) emitReadable(stream);\n }\n maybeReadMore(stream, state);\n}\n\nfunction chunkInvalid(state, chunk) {\n var er;\n if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n return er;\n}\n\n// if it's past the high water mark, we can push in some more.\n// Also, if we have no data yet, we can stand some\n// more bytes. This is to work around cases where hwm=0,\n// such as the repl. Also, if the push() triggered a\n// readable event, and the user called read(largeNumber) such that\n// needReadable was set, then we ought to push more, so that another\n// 'readable' event will be triggered.\nfunction needMoreData(state) {\n return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);\n}\n\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n};\n\n// backwards compatibility.\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this._readableState.decoder = new StringDecoder(enc);\n this._readableState.encoding = enc;\n return this;\n};\n\n// Don't raise the hwm > 8MB\nvar MAX_HWM = 0x800000;\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n return n;\n}\n\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n }\n // If we're asking for more than the current hwm, then raise the hwm.\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n;\n // Don't have enough\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n return state.length;\n}\n\n// you can override either this method, or the async _read(n) below.\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n\n if (n !== 0) state.emittedReadable = false;\n\n // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n\n n = howMuchToRead(n, state);\n\n // if we've ended, and we're now clear, then finish it up.\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n }\n\n // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n\n // if we need a readable event, then we need to do some reading.\n var doRead = state.needReadable;\n debug('need readable', doRead);\n\n // if we currently have less than the highWaterMark, then also read some\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n }\n\n // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true;\n // if the length is currently zero, then we *need* a readable event.\n if (state.length === 0) state.needReadable = true;\n // call internal read method\n this._read(state.highWaterMark);\n state.sync = false;\n // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n\n if (ret === null) {\n state.needReadable = true;\n n = 0;\n } else {\n state.length -= n;\n }\n\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true;\n\n // If we tried to read() past the EOF, then emit end on the next tick.\n if (nOrig !== n && state.ended) endReadable(this);\n }\n\n if (ret !== null) this.emit('data', ret);\n\n return ret;\n};\n\nfunction onEofChunk(stream, state) {\n if (state.ended) return;\n if (state.decoder) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n state.ended = true;\n\n // emit 'readable' now to make sure it gets picked up.\n emitReadable(stream);\n}\n\n// Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\nfunction emitReadable(stream) {\n var state = stream._readableState;\n state.needReadable = false;\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);\n }\n}\n\nfunction emitReadable_(stream) {\n debug('emit readable');\n stream.emit('readable');\n flow(stream);\n}\n\n// at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n pna.nextTick(maybeReadMore_, stream, state);\n }\n}\n\nfunction maybeReadMore_(stream, state) {\n var len = state.length;\n while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length)\n // didn't get any data, stop spinning.\n break;else len = state.length;\n }\n state.readingMore = false;\n}\n\n// abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\nReadable.prototype._read = function (n) {\n this.emit('error', new Error('_read() is not implemented'));\n};\n\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n default:\n state.pipes.push(dest);\n break;\n }\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n\n var endFn = doEnd ? onend : unpipe;\n if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);\n\n dest.on('unpipe', onunpipe);\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe');\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true;\n cleanup();\n }\n }\n }\n\n function onend() {\n debug('onend');\n dest.end();\n }\n\n // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n\n var cleanedUp = false;\n function cleanup() {\n debug('cleanup');\n // cleanup event handlers once the pipe is broken\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', unpipe);\n src.removeListener('data', ondata);\n\n cleanedUp = true;\n\n // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n\n // If the user pushes more data while we're writing to dest then we'll end up\n // in ondata again. However, we only want to increase awaitDrain once because\n // dest will only emit one 'drain' event for the multiple writes.\n // => Introduce a guard on increasing awaitDrain.\n var increasedAwaitDrain = false;\n src.on('data', ondata);\n function ondata(chunk) {\n debug('ondata');\n increasedAwaitDrain = false;\n var ret = dest.write(chunk);\n if (false === ret && !increasedAwaitDrain) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', state.awaitDrain);\n state.awaitDrain++;\n increasedAwaitDrain = true;\n }\n src.pause();\n }\n }\n\n // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);\n }\n\n // Make sure our error handler is attached before userland ones.\n prependListener(dest, 'error', onerror);\n\n // Both close and finish should trigger unpipe, but only once.\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n dest.once('close', onclose);\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n dest.once('finish', onfinish);\n\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n }\n\n // tell the dest that it's being piped to\n dest.emit('pipe', src);\n\n // start the flow if it hasn't been started already.\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n\n return dest;\n};\n\nfunction pipeOnDrain(src) {\n return function () {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\n\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n var unpipeInfo = { hasUnpiped: false };\n\n // if we're not piping anywhere, then do nothing.\n if (state.pipesCount === 0) return this;\n\n // just one destination. most common case.\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n\n if (!dest) dest = state.pipes;\n\n // got a match.\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this, unpipeInfo);\n return this;\n }\n\n // slow case. multiple pipe destinations.\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n\n for (var i = 0; i < len; i++) {\n dests[i].emit('unpipe', this, { hasUnpiped: false });\n }return this;\n }\n\n // try to find the right one.\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n\n dest.emit('unpipe', this, unpipeInfo);\n\n return this;\n};\n\n// set up data events if they are asked for\n// Ensure readable listeners eventually get something\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n\n if (ev === 'data') {\n // Start flowing on next tick if stream isn't explicitly paused\n if (this._readableState.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n var state = this._readableState;\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.emittedReadable = false;\n if (!state.reading) {\n pna.nextTick(nReadingNextTick, this);\n } else if (state.length) {\n emitReadable(this);\n }\n }\n }\n\n return res;\n};\nReadable.prototype.addListener = Readable.prototype.on;\n\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n}\n\n// pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\nReadable.prototype.resume = function () {\n var state = this._readableState;\n if (!state.flowing) {\n debug('resume');\n state.flowing = true;\n resume(this, state);\n }\n return this;\n};\n\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n pna.nextTick(resume_, stream, state);\n }\n}\n\nfunction resume_(stream, state) {\n if (!state.reading) {\n debug('resume read 0');\n stream.read(0);\n }\n\n state.resumeScheduled = false;\n state.awaitDrain = 0;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\n\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n if (false !== this._readableState.flowing) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n return this;\n};\n\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n while (state.flowing && stream.read() !== null) {}\n}\n\n// wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\nReadable.prototype.wrap = function (stream) {\n var _this = this;\n\n var state = this._readableState;\n var paused = false;\n\n stream.on('end', function () {\n debug('wrapped end');\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) _this.push(chunk);\n }\n\n _this.push(null);\n });\n\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk);\n\n // don't skip over falsy values in objectMode\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n\n var ret = _this.push(chunk);\n if (!ret) {\n paused = true;\n stream.pause();\n }\n });\n\n // proxy all the other methods.\n // important when wrapping filters and duplexes.\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function (method) {\n return function () {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n }\n\n // proxy certain important events.\n for (var n = 0; n < kProxyEvents.length; n++) {\n stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));\n }\n\n // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n this._read = function (n) {\n debug('wrapped _read', n);\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n\n return this;\n};\n\nObject.defineProperty(Readable.prototype, 'readableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._readableState.highWaterMark;\n }\n});\n\n// exposed for testing purposes only.\nReadable._fromList = fromList;\n\n// Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);\n state.buffer.clear();\n } else {\n // read part of list\n ret = fromListPartial(n, state.buffer, state.decoder);\n }\n\n return ret;\n}\n\n// Extracts only enough buffered data to satisfy the amount requested.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromListPartial(n, list, hasStrings) {\n var ret;\n if (n < list.head.data.length) {\n // slice is the same for buffers and strings\n ret = list.head.data.slice(0, n);\n list.head.data = list.head.data.slice(n);\n } else if (n === list.head.data.length) {\n // first chunk is a perfect match\n ret = list.shift();\n } else {\n // result spans more than one buffer\n ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);\n }\n return ret;\n}\n\n// Copies a specified amount of characters from the list of buffered data\n// chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBufferString(n, list) {\n var p = list.head;\n var c = 1;\n var ret = p.data;\n n -= ret.length;\n while (p = p.next) {\n var str = p.data;\n var nb = n > str.length ? str.length : n;\n if (nb === str.length) ret += str;else ret += str.slice(0, n);\n n -= nb;\n if (n === 0) {\n if (nb === str.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = str.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\n\n// Copies a specified amount of bytes from the list of buffered data chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\n\nfunction endReadable(stream) {\n var state = stream._readableState;\n\n // If we get here before consuming all the bytes, then that is a\n // bug in node. Should never happen.\n if (state.length > 0) throw new Error('\"endReadable()\" called on non-empty stream');\n\n if (!state.endEmitted) {\n state.ended = true;\n pna.nextTick(endReadableNT, state, stream);\n }\n}\n\nfunction endReadableNT(state, stream) {\n // Check that we didn't get one last unshift.\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n }\n}\n\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n return -1;\n}", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n\n'use strict';\n\nmodule.exports = Transform;\n\nvar Duplex = require('./_stream_duplex');\n\n/*<replacement>*/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/*</replacement>*/\n\nutil.inherits(Transform, Duplex);\n\nfunction afterTransform(er, data) {\n var ts = this._transformState;\n ts.transforming = false;\n\n var cb = ts.writecb;\n\n if (!cb) {\n return this.emit('error', new Error('write callback called multiple times'));\n }\n\n ts.writechunk = null;\n ts.writecb = null;\n\n if (data != null) // single equals check for both `null` and `undefined`\n this.push(data);\n\n cb(er);\n\n var rs = this._readableState;\n rs.reading = false;\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n this._read(rs.highWaterMark);\n }\n}\n\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options);\n\n Duplex.call(this, options);\n\n this._transformState = {\n afterTransform: afterTransform.bind(this),\n needTransform: false,\n transforming: false,\n writecb: null,\n writechunk: null,\n writeencoding: null\n };\n\n // start out asking for a readable event once data is transformed.\n this._readableState.needReadable = true;\n\n // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n this._readableState.sync = false;\n\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform;\n\n if (typeof options.flush === 'function') this._flush = options.flush;\n }\n\n // When the writable side finishes, then flush out anything remaining.\n this.on('prefinish', prefinish);\n}\n\nfunction prefinish() {\n var _this = this;\n\n if (typeof this._flush === 'function') {\n this._flush(function (er, data) {\n done(_this, er, data);\n });\n } else {\n done(this, null, null);\n }\n}\n\nTransform.prototype.push = function (chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n};\n\n// This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\nTransform.prototype._transform = function (chunk, encoding, cb) {\n throw new Error('_transform() is not implemented');\n};\n\nTransform.prototype._write = function (chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n }\n};\n\n// Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\nTransform.prototype._read = function (n) {\n var ts = this._transformState;\n\n if (ts.writechunk !== null && ts.writecb && !ts.transforming) {\n ts.transforming = true;\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\n\nTransform.prototype._destroy = function (err, cb) {\n var _this2 = this;\n\n Duplex.prototype._destroy.call(this, err, function (err2) {\n cb(err2);\n _this2.emit('close');\n });\n};\n\nfunction done(stream, er, data) {\n if (er) return stream.emit('error', er);\n\n if (data != null) // single equals check for both `null` and `undefined`\n stream.push(data);\n\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');\n\n if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');\n\n return stream.push(null);\n}", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n\n'use strict';\n\nmodule.exports = PassThrough;\n\nvar Transform = require('./_stream_transform');\n\n/*<replacement>*/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/*</replacement>*/\n\nutil.inherits(PassThrough, Transform);\n\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough)) return new PassThrough(options);\n\n Transform.call(this, options);\n}\n\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n cb(null, chunk);\n};", "var Stream = require('stream');\nif (process.env.READABLE_STREAM === 'disable' && Stream) {\n module.exports = Stream;\n exports = module.exports = Stream.Readable;\n exports.Readable = Stream.Readable;\n exports.Writable = Stream.Writable;\n exports.Duplex = Stream.Duplex;\n exports.Transform = Stream.Transform;\n exports.PassThrough = Stream.PassThrough;\n exports.Stream = Stream;\n} else {\n exports = module.exports = require('./lib/_stream_readable.js');\n exports.Stream = Stream || exports;\n exports.Readable = exports;\n exports.Writable = require('./lib/_stream_writable.js');\n exports.Duplex = require('./lib/_stream_duplex.js');\n exports.Transform = require('./lib/_stream_transform.js');\n exports.PassThrough = require('./lib/_stream_passthrough.js');\n}\n", "\"use strict\";\n\nexports.base64 = true;\nexports.array = true;\nexports.string = true;\nexports.arraybuffer = typeof ArrayBuffer !== \"undefined\" && typeof Uint8Array !== \"undefined\";\nexports.nodebuffer = typeof Buffer !== \"undefined\";\n// contains true if JSZip can read/generate Uint8Array, false otherwise.\nexports.uint8array = typeof Uint8Array !== \"undefined\";\n\nif (typeof ArrayBuffer === \"undefined\") {\n exports.blob = false;\n}\nelse {\n var buffer = new ArrayBuffer(0);\n try {\n exports.blob = new Blob([buffer], {\n type: \"application/zip\"\n }).size === 0;\n }\n catch (e) {\n try {\n var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder;\n var builder = new Builder();\n builder.append(buffer);\n exports.blob = builder.getBlob(\"application/zip\").size === 0;\n }\n catch (e) {\n exports.blob = false;\n }\n }\n}\n\ntry {\n exports.nodestream = !!require(\"readable-stream\").Readable;\n} catch(e) {\n exports.nodestream = false;\n}\n", "\"use strict\";\nvar utils = require(\"./utils\");\nvar support = require(\"./support\");\n// private property\nvar _keyStr = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\n\n\n// public method for encoding\nexports.encode = function(input) {\n var output = [];\n var chr1, chr2, chr3, enc1, enc2, enc3, enc4;\n var i = 0, len = input.length, remainingBytes = len;\n\n var isArray = utils.getTypeOf(input) !== \"string\";\n while (i < input.length) {\n remainingBytes = len - i;\n\n if (!isArray) {\n chr1 = input.charCodeAt(i++);\n chr2 = i < len ? input.charCodeAt(i++) : 0;\n chr3 = i < len ? input.charCodeAt(i++) : 0;\n } else {\n chr1 = input[i++];\n chr2 = i < len ? input[i++] : 0;\n chr3 = i < len ? input[i++] : 0;\n }\n\n enc1 = chr1 >> 2;\n enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);\n enc3 = remainingBytes > 1 ? (((chr2 & 15) << 2) | (chr3 >> 6)) : 64;\n enc4 = remainingBytes > 2 ? (chr3 & 63) : 64;\n\n output.push(_keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4));\n\n }\n\n return output.join(\"\");\n};\n\n// public method for decoding\nexports.decode = function(input) {\n var chr1, chr2, chr3;\n var enc1, enc2, enc3, enc4;\n var i = 0, resultIndex = 0;\n\n var dataUrlPrefix = \"data:\";\n\n if (input.substr(0, dataUrlPrefix.length) === dataUrlPrefix) {\n // This is a common error: people give a data url\n // (data:image/png;base64,iVBOR...) with a {base64: true} and\n // wonders why things don't work.\n // We can detect that the string input looks like a data url but we\n // *can't* be sure it is one: removing everything up to the comma would\n // be too dangerous.\n throw new Error(\"Invalid base64 input, it looks like a data url.\");\n }\n\n input = input.replace(/[^A-Za-z0-9+/=]/g, \"\");\n\n var totalLength = input.length * 3 / 4;\n if(input.charAt(input.length - 1) === _keyStr.charAt(64)) {\n totalLength--;\n }\n if(input.charAt(input.length - 2) === _keyStr.charAt(64)) {\n totalLength--;\n }\n if (totalLength % 1 !== 0) {\n // totalLength is not an integer, the length does not match a valid\n // base64 content. That can happen if:\n // - the input is not a base64 content\n // - the input is *almost* a base64 content, with a extra chars at the\n // beginning or at the end\n // - the input uses a base64 variant (base64url for example)\n throw new Error(\"Invalid base64 input, bad content length.\");\n }\n var output;\n if (support.uint8array) {\n output = new Uint8Array(totalLength|0);\n } else {\n output = new Array(totalLength|0);\n }\n\n while (i < input.length) {\n\n enc1 = _keyStr.indexOf(input.charAt(i++));\n enc2 = _keyStr.indexOf(input.charAt(i++));\n enc3 = _keyStr.indexOf(input.charAt(i++));\n enc4 = _keyStr.indexOf(input.charAt(i++));\n\n chr1 = (enc1 << 2) | (enc2 >> 4);\n chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);\n chr3 = ((enc3 & 3) << 6) | enc4;\n\n output[resultIndex++] = chr1;\n\n if (enc3 !== 64) {\n output[resultIndex++] = chr2;\n }\n if (enc4 !== 64) {\n output[resultIndex++] = chr3;\n }\n\n }\n\n return output;\n};\n", "\"use strict\";\n\nmodule.exports = {\n /**\n * True if this is running in Nodejs, will be undefined in a browser.\n * In a browser, browserify won't include this file and the whole module\n * will be resolved an empty object.\n */\n isNode : typeof Buffer !== \"undefined\",\n /**\n * Create a new nodejs Buffer from an existing content.\n * @param {Object} data the data to pass to the constructor.\n * @param {String} encoding the encoding to use.\n * @return {Buffer} a new Buffer.\n */\n newBufferFrom: function(data, encoding) {\n if (Buffer.from && Buffer.from !== Uint8Array.from) {\n return Buffer.from(data, encoding);\n } else {\n if (typeof data === \"number\") {\n // Safeguard for old Node.js versions. On newer versions,\n // Buffer.from(number) / Buffer(number, encoding) already throw.\n throw new Error(\"The \\\"data\\\" argument must not be a number\");\n }\n return new Buffer(data, encoding);\n }\n },\n /**\n * Create a new nodejs Buffer with the specified size.\n * @param {Integer} size the size of the buffer.\n * @return {Buffer} a new Buffer.\n */\n allocBuffer: function (size) {\n if (Buffer.alloc) {\n return Buffer.alloc(size);\n } else {\n var buf = new Buffer(size);\n buf.fill(0);\n return buf;\n }\n },\n /**\n * Find out if an object is a Buffer.\n * @param {Object} b the object to test.\n * @return {Boolean} true if the object is a Buffer, false otherwise.\n */\n isBuffer : function(b){\n return Buffer.isBuffer(b);\n },\n\n isStream : function (obj) {\n return obj &&\n typeof obj.on === \"function\" &&\n typeof obj.pause === \"function\" &&\n typeof obj.resume === \"function\";\n }\n};\n", "'use strict';\nvar Mutation = global.MutationObserver || global.WebKitMutationObserver;\n\nvar scheduleDrain;\n\nif (process.browser) {\n if (Mutation) {\n var called = 0;\n var observer = new Mutation(nextTick);\n var element = global.document.createTextNode('');\n observer.observe(element, {\n characterData: true\n });\n scheduleDrain = function () {\n element.data = (called = ++called % 2);\n };\n } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {\n var channel = new global.MessageChannel();\n channel.port1.onmessage = nextTick;\n scheduleDrain = function () {\n channel.port2.postMessage(0);\n };\n } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {\n scheduleDrain = function () {\n\n // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted\n // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.\n var scriptEl = global.document.createElement('script');\n scriptEl.onreadystatechange = function () {\n nextTick();\n\n scriptEl.onreadystatechange = null;\n scriptEl.parentNode.removeChild(scriptEl);\n scriptEl = null;\n };\n global.document.documentElement.appendChild(scriptEl);\n };\n } else {\n scheduleDrain = function () {\n setTimeout(nextTick, 0);\n };\n }\n} else {\n scheduleDrain = function () {\n process.nextTick(nextTick);\n };\n}\n\nvar draining;\nvar queue = [];\n//named nextTick for less confusing stack traces\nfunction nextTick() {\n draining = true;\n var i, oldQueue;\n var len = queue.length;\n while (len) {\n oldQueue = queue;\n queue = [];\n i = -1;\n while (++i < len) {\n oldQueue[i]();\n }\n len = queue.length;\n }\n draining = false;\n}\n\nmodule.exports = immediate;\nfunction immediate(task) {\n if (queue.push(task) === 1 && !draining) {\n scheduleDrain();\n }\n}\n", "'use strict';\nvar immediate = require('immediate');\n\n/* istanbul ignore next */\nfunction INTERNAL() {}\n\nvar handlers = {};\n\nvar REJECTED = ['REJECTED'];\nvar FULFILLED = ['FULFILLED'];\nvar PENDING = ['PENDING'];\n/* istanbul ignore else */\nif (!process.browser) {\n // in which we actually take advantage of JS scoping\n var UNHANDLED = ['UNHANDLED'];\n}\n\nmodule.exports = Promise;\n\nfunction Promise(resolver) {\n if (typeof resolver !== 'function') {\n throw new TypeError('resolver must be a function');\n }\n this.state = PENDING;\n this.queue = [];\n this.outcome = void 0;\n /* istanbul ignore else */\n if (!process.browser) {\n this.handled = UNHANDLED;\n }\n if (resolver !== INTERNAL) {\n safelyResolveThenable(this, resolver);\n }\n}\n\nPromise.prototype.finally = function (callback) {\n if (typeof callback !== 'function') {\n return this;\n }\n var p = this.constructor;\n return this.then(resolve, reject);\n\n function resolve(value) {\n function yes () {\n return value;\n }\n return p.resolve(callback()).then(yes);\n }\n function reject(reason) {\n function no () {\n throw reason;\n }\n return p.resolve(callback()).then(no);\n }\n};\nPromise.prototype.catch = function (onRejected) {\n return this.then(null, onRejected);\n};\nPromise.prototype.then = function (onFulfilled, onRejected) {\n if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||\n typeof onRejected !== 'function' && this.state === REJECTED) {\n return this;\n }\n var promise = new this.constructor(INTERNAL);\n /* istanbul ignore else */\n if (!process.browser) {\n if (this.handled === UNHANDLED) {\n this.handled = null;\n }\n }\n if (this.state !== PENDING) {\n var resolver = this.state === FULFILLED ? onFulfilled : onRejected;\n unwrap(promise, resolver, this.outcome);\n } else {\n this.queue.push(new QueueItem(promise, onFulfilled, onRejected));\n }\n\n return promise;\n};\nfunction QueueItem(promise, onFulfilled, onRejected) {\n this.promise = promise;\n if (typeof onFulfilled === 'function') {\n this.onFulfilled = onFulfilled;\n this.callFulfilled = this.otherCallFulfilled;\n }\n if (typeof onRejected === 'function') {\n this.onRejected = onRejected;\n this.callRejected = this.otherCallRejected;\n }\n}\nQueueItem.prototype.callFulfilled = function (value) {\n handlers.resolve(this.promise, value);\n};\nQueueItem.prototype.otherCallFulfilled = function (value) {\n unwrap(this.promise, this.onFulfilled, value);\n};\nQueueItem.prototype.callRejected = function (value) {\n handlers.reject(this.promise, value);\n};\nQueueItem.prototype.otherCallRejected = function (value) {\n unwrap(this.promise, this.onRejected, value);\n};\n\nfunction unwrap(promise, func, value) {\n immediate(function () {\n var returnValue;\n try {\n returnValue = func(value);\n } catch (e) {\n return handlers.reject(promise, e);\n }\n if (returnValue === promise) {\n handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));\n } else {\n handlers.resolve(promise, returnValue);\n }\n });\n}\n\nhandlers.resolve = function (self, value) {\n var result = tryCatch(getThen, value);\n if (result.status === 'error') {\n return handlers.reject(self, result.value);\n }\n var thenable = result.value;\n\n if (thenable) {\n safelyResolveThenable(self, thenable);\n } else {\n self.state = FULFILLED;\n self.outcome = value;\n var i = -1;\n var len = self.queue.length;\n while (++i < len) {\n self.queue[i].callFulfilled(value);\n }\n }\n return self;\n};\nhandlers.reject = function (self, error) {\n self.state = REJECTED;\n self.outcome = error;\n /* istanbul ignore else */\n if (!process.browser) {\n if (self.handled === UNHANDLED) {\n immediate(function () {\n if (self.handled === UNHANDLED) {\n process.emit('unhandledRejection', error, self);\n }\n });\n }\n }\n var i = -1;\n var len = self.queue.length;\n while (++i < len) {\n self.queue[i].callRejected(error);\n }\n return self;\n};\n\nfunction getThen(obj) {\n // Make sure we only access the accessor once as required by the spec\n var then = obj && obj.then;\n if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') {\n return function appyThen() {\n then.apply(obj, arguments);\n };\n }\n}\n\nfunction safelyResolveThenable(self, thenable) {\n // Either fulfill, reject or reject with error\n var called = false;\n function onError(value) {\n if (called) {\n return;\n }\n called = true;\n handlers.reject(self, value);\n }\n\n function onSuccess(value) {\n if (called) {\n return;\n }\n called = true;\n handlers.resolve(self, value);\n }\n\n function tryToUnwrap() {\n thenable(onSuccess, onError);\n }\n\n var result = tryCatch(tryToUnwrap);\n if (result.status === 'error') {\n onError(result.value);\n }\n}\n\nfunction tryCatch(func, value) {\n var out = {};\n try {\n out.value = func(value);\n out.status = 'success';\n } catch (e) {\n out.status = 'error';\n out.value = e;\n }\n return out;\n}\n\nPromise.resolve = resolve;\nfunction resolve(value) {\n if (value instanceof this) {\n return value;\n }\n return handlers.resolve(new this(INTERNAL), value);\n}\n\nPromise.reject = reject;\nfunction reject(reason) {\n var promise = new this(INTERNAL);\n return handlers.reject(promise, reason);\n}\n\nPromise.all = all;\nfunction all(iterable) {\n var self = this;\n if (Object.prototype.toString.call(iterable) !== '[object Array]') {\n return this.reject(new TypeError('must be an array'));\n }\n\n var len = iterable.length;\n var called = false;\n if (!len) {\n return this.resolve([]);\n }\n\n var values = new Array(len);\n var resolved = 0;\n var i = -1;\n var promise = new this(INTERNAL);\n\n while (++i < len) {\n allResolver(iterable[i], i);\n }\n return promise;\n function allResolver(value, i) {\n self.resolve(value).then(resolveFromAll, function (error) {\n if (!called) {\n called = true;\n handlers.reject(promise, error);\n }\n });\n function resolveFromAll(outValue) {\n values[i] = outValue;\n if (++resolved === len && !called) {\n called = true;\n handlers.resolve(promise, values);\n }\n }\n }\n}\n\nPromise.race = race;\nfunction race(iterable) {\n var self = this;\n if (Object.prototype.toString.call(iterable) !== '[object Array]') {\n return this.reject(new TypeError('must be an array'));\n }\n\n var len = iterable.length;\n var called = false;\n if (!len) {\n return this.resolve([]);\n }\n\n var i = -1;\n var promise = new this(INTERNAL);\n\n while (++i < len) {\n resolver(iterable[i]);\n }\n return promise;\n function resolver(value) {\n self.resolve(value).then(function (response) {\n if (!called) {\n called = true;\n handlers.resolve(promise, response);\n }\n }, function (error) {\n if (!called) {\n called = true;\n handlers.reject(promise, error);\n }\n });\n }\n}\n", "\"use strict\";\n\n// load the global object first:\n// - it should be better integrated in the system (unhandledRejection in node)\n// - the environment may have a custom Promise implementation (see zone.js)\nvar ES6Promise = null;\nif (typeof Promise !== \"undefined\") {\n ES6Promise = Promise;\n} else {\n ES6Promise = require(\"lie\");\n}\n\n/**\n * Let the user use/change some implementations.\n */\nmodule.exports = {\n Promise: ES6Promise\n};\n", "(function (global, undefined) {\n \"use strict\";\n\n if (global.setImmediate) {\n return;\n }\n\n var nextHandle = 1; // Spec says greater than zero\n var tasksByHandle = {};\n var currentlyRunningATask = false;\n var doc = global.document;\n var registerImmediate;\n\n function setImmediate(callback) {\n // Callback can either be a function or a string\n if (typeof callback !== \"function\") {\n callback = new Function(\"\" + callback);\n }\n // Copy function arguments\n var args = new Array(arguments.length - 1);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i + 1];\n }\n // Store and register the task\n var task = { callback: callback, args: args };\n tasksByHandle[nextHandle] = task;\n registerImmediate(nextHandle);\n return nextHandle++;\n }\n\n function clearImmediate(handle) {\n delete tasksByHandle[handle];\n }\n\n function run(task) {\n var callback = task.callback;\n var args = task.args;\n switch (args.length) {\n case 0:\n callback();\n break;\n case 1:\n callback(args[0]);\n break;\n case 2:\n callback(args[0], args[1]);\n break;\n case 3:\n callback(args[0], args[1], args[2]);\n break;\n default:\n callback.apply(undefined, args);\n break;\n }\n }\n\n function runIfPresent(handle) {\n // From the spec: \"Wait until any invocations of this algorithm started before this one have completed.\"\n // So if we're currently running a task, we'll need to delay this invocation.\n if (currentlyRunningATask) {\n // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a\n // \"too much recursion\" error.\n setTimeout(runIfPresent, 0, handle);\n } else {\n var task = tasksByHandle[handle];\n if (task) {\n currentlyRunningATask = true;\n try {\n run(task);\n } finally {\n clearImmediate(handle);\n currentlyRunningATask = false;\n }\n }\n }\n }\n\n function installNextTickImplementation() {\n registerImmediate = function(handle) {\n process.nextTick(function () { runIfPresent(handle); });\n };\n }\n\n function canUsePostMessage() {\n // The test against `importScripts` prevents this implementation from being installed inside a web worker,\n // where `global.postMessage` means something completely different and can't be used for this purpose.\n if (global.postMessage && !global.importScripts) {\n var postMessageIsAsynchronous = true;\n var oldOnMessage = global.onmessage;\n global.onmessage = function() {\n postMessageIsAsynchronous = false;\n };\n global.postMessage(\"\", \"*\");\n global.onmessage = oldOnMessage;\n return postMessageIsAsynchronous;\n }\n }\n\n function installPostMessageImplementation() {\n // Installs an event handler on `global` for the `message` event: see\n // * https://developer.mozilla.org/en/DOM/window.postMessage\n // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages\n\n var messagePrefix = \"setImmediate$\" + Math.random() + \"$\";\n var onGlobalMessage = function(event) {\n if (event.source === global &&\n typeof event.data === \"string\" &&\n event.data.indexOf(messagePrefix) === 0) {\n runIfPresent(+event.data.slice(messagePrefix.length));\n }\n };\n\n if (global.addEventListener) {\n global.addEventListener(\"message\", onGlobalMessage, false);\n } else {\n global.attachEvent(\"onmessage\", onGlobalMessage);\n }\n\n registerImmediate = function(handle) {\n global.postMessage(messagePrefix + handle, \"*\");\n };\n }\n\n function installMessageChannelImplementation() {\n var channel = new MessageChannel();\n channel.port1.onmessage = function(event) {\n var handle = event.data;\n runIfPresent(handle);\n };\n\n registerImmediate = function(handle) {\n channel.port2.postMessage(handle);\n };\n }\n\n function installReadyStateChangeImplementation() {\n var html = doc.documentElement;\n registerImmediate = function(handle) {\n // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted\n // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.\n var script = doc.createElement(\"script\");\n script.onreadystatechange = function () {\n runIfPresent(handle);\n script.onreadystatechange = null;\n html.removeChild(script);\n script = null;\n };\n html.appendChild(script);\n };\n }\n\n function installSetTimeoutImplementation() {\n registerImmediate = function(handle) {\n setTimeout(runIfPresent, 0, handle);\n };\n }\n\n // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.\n var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);\n attachTo = attachTo && attachTo.setTimeout ? attachTo : global;\n\n // Don't get fooled by e.g. browserify environments.\n if ({}.toString.call(global.process) === \"[object process]\") {\n // For Node.js before 0.9\n installNextTickImplementation();\n\n } else if (canUsePostMessage()) {\n // For non-IE10 modern browsers\n installPostMessageImplementation();\n\n } else if (global.MessageChannel) {\n // For web workers, where supported\n installMessageChannelImplementation();\n\n } else if (doc && \"onreadystatechange\" in doc.createElement(\"script\")) {\n // For IE 6–8\n installReadyStateChangeImplementation();\n\n } else {\n // For older browsers\n installSetTimeoutImplementation();\n }\n\n attachTo.setImmediate = setImmediate;\n attachTo.clearImmediate = clearImmediate;\n}(typeof self === \"undefined\" ? typeof global === \"undefined\" ? this : global : self));\n", "\"use strict\";\n\nvar support = require(\"./support\");\nvar base64 = require(\"./base64\");\nvar nodejsUtils = require(\"./nodejsUtils\");\nvar external = require(\"./external\");\nrequire(\"setimmediate\");\n\n\n/**\n * Convert a string that pass as a \"binary string\": it should represent a byte\n * array but may have > 255 char codes. Be sure to take only the first byte\n * and returns the byte array.\n * @param {String} str the string to transform.\n * @return {Array|Uint8Array} the string in a binary format.\n */\nfunction string2binary(str) {\n var result = null;\n if (support.uint8array) {\n result = new Uint8Array(str.length);\n } else {\n result = new Array(str.length);\n }\n return stringToArrayLike(str, result);\n}\n\n/**\n * Create a new blob with the given content and the given type.\n * @param {String|ArrayBuffer} part the content to put in the blob. DO NOT use\n * an Uint8Array because the stock browser of android 4 won't accept it (it\n * will be silently converted to a string, \"[object Uint8Array]\").\n *\n * Use only ONE part to build the blob to avoid a memory leak in IE11 / Edge:\n * when a large amount of Array is used to create the Blob, the amount of\n * memory consumed is nearly 100 times the original data amount.\n *\n * @param {String} type the mime type of the blob.\n * @return {Blob} the created blob.\n */\nexports.newBlob = function(part, type) {\n exports.checkSupport(\"blob\");\n\n try {\n // Blob constructor\n return new Blob([part], {\n type: type\n });\n }\n catch (e) {\n\n try {\n // deprecated, browser only, old way\n var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder;\n var builder = new Builder();\n builder.append(part);\n return builder.getBlob(type);\n }\n catch (e) {\n\n // well, fuck ?!\n throw new Error(\"Bug : can't construct the Blob.\");\n }\n }\n\n\n};\n/**\n * The identity function.\n * @param {Object} input the input.\n * @return {Object} the same input.\n */\nfunction identity(input) {\n return input;\n}\n\n/**\n * Fill in an array with a string.\n * @param {String} str the string to use.\n * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).\n * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.\n */\nfunction stringToArrayLike(str, array) {\n for (var i = 0; i < str.length; ++i) {\n array[i] = str.charCodeAt(i) & 0xFF;\n }\n return array;\n}\n\n/**\n * An helper for the function arrayLikeToString.\n * This contains static information and functions that\n * can be optimized by the browser JIT compiler.\n */\nvar arrayToStringHelper = {\n /**\n * Transform an array of int into a string, chunk by chunk.\n * See the performances notes on arrayLikeToString.\n * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.\n * @param {String} type the type of the array.\n * @param {Integer} chunk the chunk size.\n * @return {String} the resulting string.\n * @throws Error if the chunk is too big for the stack.\n */\n stringifyByChunk: function(array, type, chunk) {\n var result = [], k = 0, len = array.length;\n // shortcut\n if (len <= chunk) {\n return String.fromCharCode.apply(null, array);\n }\n while (k < len) {\n if (type === \"array\" || type === \"nodebuffer\") {\n result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));\n }\n else {\n result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));\n }\n k += chunk;\n }\n return result.join(\"\");\n },\n /**\n * Call String.fromCharCode on every item in the array.\n * This is the naive implementation, which generate A LOT of intermediate string.\n * This should be used when everything else fail.\n * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.\n * @return {String} the result.\n */\n stringifyByChar: function(array){\n var resultStr = \"\";\n for(var i = 0; i < array.length; i++) {\n resultStr += String.fromCharCode(array[i]);\n }\n return resultStr;\n },\n applyCanBeUsed : {\n /**\n * true if the browser accepts to use String.fromCharCode on Uint8Array\n */\n uint8array : (function () {\n try {\n return support.uint8array && String.fromCharCode.apply(null, new Uint8Array(1)).length === 1;\n } catch (e) {\n return false;\n }\n })(),\n /**\n * true if the browser accepts to use String.fromCharCode on nodejs Buffer.\n */\n nodebuffer : (function () {\n try {\n return support.nodebuffer && String.fromCharCode.apply(null, nodejsUtils.allocBuffer(1)).length === 1;\n } catch (e) {\n return false;\n }\n })()\n }\n};\n\n/**\n * Transform an array-like object to a string.\n * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.\n * @return {String} the result.\n */\nfunction arrayLikeToString(array) {\n // Performances notes :\n // --------------------\n // String.fromCharCode.apply(null, array) is the fastest, see\n // see http://jsperf.com/converting-a-uint8array-to-a-string/2\n // but the stack is limited (and we can get huge arrays !).\n //\n // result += String.fromCharCode(array[i]); generate too many strings !\n //\n // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2\n // TODO : we now have workers that split the work. Do we still need that ?\n var chunk = 65536,\n type = exports.getTypeOf(array),\n canUseApply = true;\n if (type === \"uint8array\") {\n canUseApply = arrayToStringHelper.applyCanBeUsed.uint8array;\n } else if (type === \"nodebuffer\") {\n canUseApply = arrayToStringHelper.applyCanBeUsed.nodebuffer;\n }\n\n if (canUseApply) {\n while (chunk > 1) {\n try {\n return arrayToStringHelper.stringifyByChunk(array, type, chunk);\n } catch (e) {\n chunk = Math.floor(chunk / 2);\n }\n }\n }\n\n // no apply or chunk error : slow and painful algorithm\n // default browser on android 4.*\n return arrayToStringHelper.stringifyByChar(array);\n}\n\nexports.applyFromCharCode = arrayLikeToString;\n\n\n/**\n * Copy the data from an array-like to an other array-like.\n * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.\n * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.\n * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.\n */\nfunction arrayLikeToArrayLike(arrayFrom, arrayTo) {\n for (var i = 0; i < arrayFrom.length; i++) {\n arrayTo[i] = arrayFrom[i];\n }\n return arrayTo;\n}\n\n// a matrix containing functions to transform everything into everything.\nvar transform = {};\n\n// string to ?\ntransform[\"string\"] = {\n \"string\": identity,\n \"array\": function(input) {\n return stringToArrayLike(input, new Array(input.length));\n },\n \"arraybuffer\": function(input) {\n return transform[\"string\"][\"uint8array\"](input).buffer;\n },\n \"uint8array\": function(input) {\n return stringToArrayLike(input, new Uint8Array(input.length));\n },\n \"nodebuffer\": function(input) {\n return stringToArrayLike(input, nodejsUtils.allocBuffer(input.length));\n }\n};\n\n// array to ?\ntransform[\"array\"] = {\n \"string\": arrayLikeToString,\n \"array\": identity,\n \"arraybuffer\": function(input) {\n return (new Uint8Array(input)).buffer;\n },\n \"uint8array\": function(input) {\n return new Uint8Array(input);\n },\n \"nodebuffer\": function(input) {\n return nodejsUtils.newBufferFrom(input);\n }\n};\n\n// arraybuffer to ?\ntransform[\"arraybuffer\"] = {\n \"string\": function(input) {\n return arrayLikeToString(new Uint8Array(input));\n },\n \"array\": function(input) {\n return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));\n },\n \"arraybuffer\": identity,\n \"uint8array\": function(input) {\n return new Uint8Array(input);\n },\n \"nodebuffer\": function(input) {\n return nodejsUtils.newBufferFrom(new Uint8Array(input));\n }\n};\n\n// uint8array to ?\ntransform[\"uint8array\"] = {\n \"string\": arrayLikeToString,\n \"array\": function(input) {\n return arrayLikeToArrayLike(input, new Array(input.length));\n },\n \"arraybuffer\": function(input) {\n return input.buffer;\n },\n \"uint8array\": identity,\n \"nodebuffer\": function(input) {\n return nodejsUtils.newBufferFrom(input);\n }\n};\n\n// nodebuffer to ?\ntransform[\"nodebuffer\"] = {\n \"string\": arrayLikeToString,\n \"array\": function(input) {\n return arrayLikeToArrayLike(input, new Array(input.length));\n },\n \"arraybuffer\": function(input) {\n return transform[\"nodebuffer\"][\"uint8array\"](input).buffer;\n },\n \"uint8array\": function(input) {\n return arrayLikeToArrayLike(input, new Uint8Array(input.length));\n },\n \"nodebuffer\": identity\n};\n\n/**\n * Transform an input into any type.\n * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.\n * If no output type is specified, the unmodified input will be returned.\n * @param {String} outputType the output type.\n * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.\n * @throws {Error} an Error if the browser doesn't support the requested output type.\n */\nexports.transformTo = function(outputType, input) {\n if (!input) {\n // undefined, null, etc\n // an empty string won't harm.\n input = \"\";\n }\n if (!outputType) {\n return input;\n }\n exports.checkSupport(outputType);\n var inputType = exports.getTypeOf(input);\n var result = transform[inputType][outputType](input);\n return result;\n};\n\n/**\n * Resolve all relative path components, \".\" and \"..\", in a path. If these relative components\n * traverse above the root then the resulting path will only contain the final path component.\n *\n * All empty components, e.g. \"//\", are removed.\n * @param {string} path A path with / or \\ separators\n * @returns {string} The path with all relative path components resolved.\n */\nexports.resolve = function(path) {\n var parts = path.split(\"/\");\n var result = [];\n for (var index = 0; index < parts.length; index++) {\n var part = parts[index];\n // Allow the first and last component to be empty for trailing slashes.\n if (part === \".\" || (part === \"\" && index !== 0 && index !== parts.length - 1)) {\n continue;\n } else if (part === \"..\") {\n result.pop();\n } else {\n result.push(part);\n }\n }\n return result.join(\"/\");\n};\n\n/**\n * Return the type of the input.\n * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.\n * @param {Object} input the input to identify.\n * @return {String} the (lowercase) type of the input.\n */\nexports.getTypeOf = function(input) {\n if (typeof input === \"string\") {\n return \"string\";\n }\n var proto = Object.prototype.toString.call(input);\n if (proto === \"[object Array]\") {\n return \"array\";\n }\n if (support.nodebuffer && nodejsUtils.isBuffer(input)) {\n return \"nodebuffer\";\n }\n if (support.uint8array && proto === \"[object Uint8Array]\") {\n return \"uint8array\";\n }\n if (support.arraybuffer && proto === \"[object ArrayBuffer]\") {\n return \"arraybuffer\";\n }\n};\n\n/**\n * Throw an exception if the type is not supported.\n * @param {String} type the type to check.\n * @throws {Error} an Error if the browser doesn't support the requested type.\n */\nexports.checkSupport = function(type) {\n var supported = support[type.toLowerCase()];\n if (!supported) {\n throw new Error(type + \" is not supported by this platform\");\n }\n};\n\nexports.MAX_VALUE_16BITS = 65535;\nexports.MAX_VALUE_32BITS = -1; // well, \"\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF\" is parsed as -1\n\n/**\n * Prettify a string read as binary.\n * @param {string} str the string to prettify.\n * @return {string} a pretty string.\n */\nexports.pretty = function(str) {\n var res = \"\",\n code, i;\n for (i = 0; i < (str || \"\").length; i++) {\n code = str.charCodeAt(i);\n res += \"\\\\x\" + (code < 16 ? \"0\" : \"\") + code.toString(16).toUpperCase();\n }\n return res;\n};\n\n/**\n * Defer the call of a function.\n * @param {Function} callback the function to call asynchronously.\n * @param {Array} args the arguments to give to the callback.\n */\nexports.delay = function(callback, args, self) {\n setImmediate(function () {\n callback.apply(self || null, args || []);\n });\n};\n\n/**\n * Extends a prototype with an other, without calling a constructor with\n * side effects. Inspired by nodejs' `utils.inherits`\n * @param {Function} ctor the constructor to augment\n * @param {Function} superCtor the parent constructor to use\n */\nexports.inherits = function (ctor, superCtor) {\n var Obj = function() {};\n Obj.prototype = superCtor.prototype;\n ctor.prototype = new Obj();\n};\n\n/**\n * Merge the objects passed as parameters into a new one.\n * @private\n * @param {...Object} var_args All objects to merge.\n * @return {Object} a new object with the data of the others.\n */\nexports.extend = function() {\n var result = {}, i, attr;\n for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers\n for (attr in arguments[i]) {\n if (Object.prototype.hasOwnProperty.call(arguments[i], attr) && typeof result[attr] === \"undefined\") {\n result[attr] = arguments[i][attr];\n }\n }\n }\n return result;\n};\n\n/**\n * Transform arbitrary content into a Promise.\n * @param {String} name a name for the content being processed.\n * @param {Object} inputData the content to process.\n * @param {Boolean} isBinary true if the content is not an unicode string\n * @param {Boolean} isOptimizedBinaryString true if the string content only has one byte per character.\n * @param {Boolean} isBase64 true if the string content is encoded with base64.\n * @return {Promise} a promise in a format usable by JSZip.\n */\nexports.prepareContent = function(name, inputData, isBinary, isOptimizedBinaryString, isBase64) {\n\n // if inputData is already a promise, this flatten it.\n var promise = external.Promise.resolve(inputData).then(function(data) {\n\n\n var isBlob = support.blob && (data instanceof Blob || [\"[object File]\", \"[object Blob]\"].indexOf(Object.prototype.toString.call(data)) !== -1);\n\n if (isBlob) {\n if (typeof Blob.prototype.arrayBuffer !== \"undefined\") {\n return data.arrayBuffer();\n } else if (typeof FileReader !== \"undefined\") {\n return new external.Promise(function (resolve, reject) {\n var reader = new FileReader();\n\n reader.onload = function(e) {\n resolve(e.target.result);\n };\n reader.onerror = function(e) {\n reject(e.target.error);\n };\n reader.readAsArrayBuffer(data);\n });\n } else {\n return external.Promise.reject(\n new Error(name + \" is a Blob, but we have no way of reading it.\")\n );\n }\n }\n\n return data;\n });\n\n return promise.then(function(data) {\n var dataType = exports.getTypeOf(data);\n\n if (!dataType) {\n return external.Promise.reject(\n new Error(\"Can't read the data of '\" + name + \"'. Is it \" +\n \"in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?\")\n );\n }\n // special case : it's way easier to work with Uint8Array than with ArrayBuffer\n if (dataType === \"arraybuffer\") {\n data = exports.transformTo(\"uint8array\", data);\n } else if (dataType === \"string\") {\n if (isBase64) {\n data = base64.decode(data);\n }\n else if (isBinary) {\n // optimizedBinaryString === true means that the file has already been filtered with a 0xFF mask\n if (isOptimizedBinaryString !== true) {\n // this is a string, not in a base64 format.\n // Be sure that this is a correct \"binary string\"\n data = string2binary(data);\n }\n }\n }\n return data;\n });\n};\n", "\"use strict\";\n\n/**\n * A worker that does nothing but passing chunks to the next one. This is like\n * a nodejs stream but with some differences. On the good side :\n * - it works on IE 6-9 without any issue / polyfill\n * - it weights less than the full dependencies bundled with browserify\n * - it forwards errors (no need to declare an error handler EVERYWHERE)\n *\n * A chunk is an object with 2 attributes : `meta` and `data`. The former is an\n * object containing anything (`percent` for example), see each worker for more\n * details. The latter is the real data (String, Uint8Array, etc).\n *\n * @constructor\n * @param {String} name the name of the stream (mainly used for debugging purposes)\n */\nfunction GenericWorker(name) {\n // the name of the worker\n this.name = name || \"default\";\n // an object containing metadata about the workers chain\n this.streamInfo = {};\n // an error which happened when the worker was paused\n this.generatedError = null;\n // an object containing metadata to be merged by this worker into the general metadata\n this.extraStreamInfo = {};\n // true if the stream is paused (and should not do anything), false otherwise\n this.isPaused = true;\n // true if the stream is finished (and should not do anything), false otherwise\n this.isFinished = false;\n // true if the stream is locked to prevent further structure updates (pipe), false otherwise\n this.isLocked = false;\n // the event listeners\n this._listeners = {\n \"data\":[],\n \"end\":[],\n \"error\":[]\n };\n // the previous worker, if any\n this.previous = null;\n}\n\nGenericWorker.prototype = {\n /**\n * Push a chunk to the next workers.\n * @param {Object} chunk the chunk to push\n */\n push : function (chunk) {\n this.emit(\"data\", chunk);\n },\n /**\n * End the stream.\n * @return {Boolean} true if this call ended the worker, false otherwise.\n */\n end : function () {\n if (this.isFinished) {\n return false;\n }\n\n this.flush();\n try {\n this.emit(\"end\");\n this.cleanUp();\n this.isFinished = true;\n } catch (e) {\n this.emit(\"error\", e);\n }\n return true;\n },\n /**\n * End the stream with an error.\n * @param {Error} e the error which caused the premature end.\n * @return {Boolean} true if this call ended the worker with an error, false otherwise.\n */\n error : function (e) {\n if (this.isFinished) {\n return false;\n }\n\n if(this.isPaused) {\n this.generatedError = e;\n } else {\n this.isFinished = true;\n\n this.emit(\"error\", e);\n\n // in the workers chain exploded in the middle of the chain,\n // the error event will go downward but we also need to notify\n // workers upward that there has been an error.\n if(this.previous) {\n this.previous.error(e);\n }\n\n this.cleanUp();\n }\n return true;\n },\n /**\n * Add a callback on an event.\n * @param {String} name the name of the event (data, end, error)\n * @param {Function} listener the function to call when the event is triggered\n * @return {GenericWorker} the current object for chainability\n */\n on : function (name, listener) {\n this._listeners[name].push(listener);\n return this;\n },\n /**\n * Clean any references when a worker is ending.\n */\n cleanUp : function () {\n this.streamInfo = this.generatedError = this.extraStreamInfo = null;\n this._listeners = [];\n },\n /**\n * Trigger an event. This will call registered callback with the provided arg.\n * @param {String} name the name of the event (data, end, error)\n * @param {Object} arg the argument to call the callback with.\n */\n emit : function (name, arg) {\n if (this._listeners[name]) {\n for(var i = 0; i < this._listeners[name].length; i++) {\n this._listeners[name][i].call(this, arg);\n }\n }\n },\n /**\n * Chain a worker with an other.\n * @param {Worker} next the worker receiving events from the current one.\n * @return {worker} the next worker for chainability\n */\n pipe : function (next) {\n return next.registerPrevious(this);\n },\n /**\n * Same as `pipe` in the other direction.\n * Using an API with `pipe(next)` is very easy.\n * Implementing the API with the point of view of the next one registering\n * a source is easier, see the ZipFileWorker.\n * @param {Worker} previous the previous worker, sending events to this one\n * @return {Worker} the current worker for chainability\n */\n registerPrevious : function (previous) {\n if (this.isLocked) {\n throw new Error(\"The stream '\" + this + \"' has already been used.\");\n }\n\n // sharing the streamInfo...\n this.streamInfo = previous.streamInfo;\n // ... and adding our own bits\n this.mergeStreamInfo();\n this.previous = previous;\n var self = this;\n previous.on(\"data\", function (chunk) {\n self.processChunk(chunk);\n });\n previous.on(\"end\", function () {\n self.end();\n });\n previous.on(\"error\", function (e) {\n self.error(e);\n });\n return this;\n },\n /**\n * Pause the stream so it doesn't send events anymore.\n * @return {Boolean} true if this call paused the worker, false otherwise.\n */\n pause : function () {\n if(this.isPaused || this.isFinished) {\n return false;\n }\n this.isPaused = true;\n\n if(this.previous) {\n this.previous.pause();\n }\n return true;\n },\n /**\n * Resume a paused stream.\n * @return {Boolean} true if this call resumed the worker, false otherwise.\n */\n resume : function () {\n if(!this.isPaused || this.isFinished) {\n return false;\n }\n this.isPaused = false;\n\n // if true, the worker tried to resume but failed\n var withError = false;\n if(this.generatedError) {\n this.error(this.generatedError);\n withError = true;\n }\n if(this.previous) {\n this.previous.resume();\n }\n\n return !withError;\n },\n /**\n * Flush any remaining bytes as the stream is ending.\n */\n flush : function () {},\n /**\n * Process a chunk. This is usually the method overridden.\n * @param {Object} chunk the chunk to process.\n */\n processChunk : function(chunk) {\n this.push(chunk);\n },\n /**\n * Add a key/value to be added in the workers chain streamInfo once activated.\n * @param {String} key the key to use\n * @param {Object} value the associated value\n * @return {Worker} the current worker for chainability\n */\n withStreamInfo : function (key, value) {\n this.extraStreamInfo[key] = value;\n this.mergeStreamInfo();\n return this;\n },\n /**\n * Merge this worker's streamInfo into the chain's streamInfo.\n */\n mergeStreamInfo : function () {\n for(var key in this.extraStreamInfo) {\n if (!Object.prototype.hasOwnProperty.call(this.extraStreamInfo, key)) {\n continue;\n }\n this.streamInfo[key] = this.extraStreamInfo[key];\n }\n },\n\n /**\n * Lock the stream to prevent further updates on the workers chain.\n * After calling this method, all calls to pipe will fail.\n */\n lock: function () {\n if (this.isLocked) {\n throw new Error(\"The stream '\" + this + \"' has already been used.\");\n }\n this.isLocked = true;\n if (this.previous) {\n this.previous.lock();\n }\n },\n\n /**\n *\n * Pretty print the workers chain.\n */\n toString : function () {\n var me = \"Worker \" + this.name;\n if (this.previous) {\n return this.previous + \" -> \" + me;\n } else {\n return me;\n }\n }\n};\n\nmodule.exports = GenericWorker;\n", "\"use strict\";\n\nvar utils = require(\"./utils\");\nvar support = require(\"./support\");\nvar nodejsUtils = require(\"./nodejsUtils\");\nvar GenericWorker = require(\"./stream/GenericWorker\");\n\n/**\n * The following functions come from pako, from pako/lib/utils/strings\n * released under the MIT license, see pako https://github.com/nodeca/pako/\n */\n\n// Table with utf8 lengths (calculated by first byte of sequence)\n// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,\n// because max possible codepoint is 0x10ffff\nvar _utf8len = new Array(256);\nfor (var i=0; i<256; i++) {\n _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);\n}\n_utf8len[254]=_utf8len[254]=1; // Invalid sequence start\n\n// convert string to array (typed, when possible)\nvar string2buf = function (str) {\n var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;\n\n // count binary size\n for (m_pos = 0; m_pos < str_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {\n c2 = str.charCodeAt(m_pos+1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n }\n\n // allocate buffer\n if (support.uint8array) {\n buf = new Uint8Array(buf_len);\n } else {\n buf = new Array(buf_len);\n }\n\n // convert\n for (i=0, m_pos = 0; i < buf_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {\n c2 = str.charCodeAt(m_pos+1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n if (c < 0x80) {\n /* one byte */\n buf[i++] = c;\n } else if (c < 0x800) {\n /* two bytes */\n buf[i++] = 0xC0 | (c >>> 6);\n buf[i++] = 0x80 | (c & 0x3f);\n } else if (c < 0x10000) {\n /* three bytes */\n buf[i++] = 0xE0 | (c >>> 12);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n } else {\n /* four bytes */\n buf[i++] = 0xf0 | (c >>> 18);\n buf[i++] = 0x80 | (c >>> 12 & 0x3f);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n }\n }\n\n return buf;\n};\n\n// Calculate max possible position in utf8 buffer,\n// that will not break sequence. If that's not possible\n// - (very small limits) return max size as is.\n//\n// buf[] - utf8 bytes array\n// max - length limit (mandatory);\nvar utf8border = function(buf, max) {\n var pos;\n\n max = max || buf.length;\n if (max > buf.length) { max = buf.length; }\n\n // go back from last position, until start of sequence found\n pos = max-1;\n while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }\n\n // Fuckup - very small and broken sequence,\n // return max, because we should return something anyway.\n if (pos < 0) { return max; }\n\n // If we came to start of buffer - that means vuffer is too small,\n // return max too.\n if (pos === 0) { return max; }\n\n return (pos + _utf8len[buf[pos]] > max) ? pos : max;\n};\n\n// convert array to string\nvar buf2string = function (buf) {\n var i, out, c, c_len;\n var len = buf.length;\n\n // Reserve max possible length (2 words per char)\n // NB: by unknown reasons, Array is significantly faster for\n // String.fromCharCode.apply than Uint16Array.\n var utf16buf = new Array(len*2);\n\n for (out=0, i=0; i<len;) {\n c = buf[i++];\n // quick process ascii\n if (c < 0x80) { utf16buf[out++] = c; continue; }\n\n c_len = _utf8len[c];\n // skip 5 & 6 byte codes\n if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }\n\n // apply mask on first byte\n c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;\n // join the rest\n while (c_len > 1 && i < len) {\n c = (c << 6) | (buf[i++] & 0x3f);\n c_len--;\n }\n\n // terminated by end of string?\n if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }\n\n if (c < 0x10000) {\n utf16buf[out++] = c;\n } else {\n c -= 0x10000;\n utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);\n utf16buf[out++] = 0xdc00 | (c & 0x3ff);\n }\n }\n\n // shrinkBuf(utf16buf, out)\n if (utf16buf.length !== out) {\n if(utf16buf.subarray) {\n utf16buf = utf16buf.subarray(0, out);\n } else {\n utf16buf.length = out;\n }\n }\n\n // return String.fromCharCode.apply(null, utf16buf);\n return utils.applyFromCharCode(utf16buf);\n};\n\n\n// That's all for the pako functions.\n\n\n/**\n * Transform a javascript string into an array (typed if possible) of bytes,\n * UTF-8 encoded.\n * @param {String} str the string to encode\n * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.\n */\nexports.utf8encode = function utf8encode(str) {\n if (support.nodebuffer) {\n return nodejsUtils.newBufferFrom(str, \"utf-8\");\n }\n\n return string2buf(str);\n};\n\n\n/**\n * Transform a bytes array (or a representation) representing an UTF-8 encoded\n * string into a javascript string.\n * @param {Array|Uint8Array|Buffer} buf the data de decode\n * @return {String} the decoded string.\n */\nexports.utf8decode = function utf8decode(buf) {\n if (support.nodebuffer) {\n return utils.transformTo(\"nodebuffer\", buf).toString(\"utf-8\");\n }\n\n buf = utils.transformTo(support.uint8array ? \"uint8array\" : \"array\", buf);\n\n return buf2string(buf);\n};\n\n/**\n * A worker to decode utf8 encoded binary chunks into string chunks.\n * @constructor\n */\nfunction Utf8DecodeWorker() {\n GenericWorker.call(this, \"utf-8 decode\");\n // the last bytes if a chunk didn't end with a complete codepoint.\n this.leftOver = null;\n}\nutils.inherits(Utf8DecodeWorker, GenericWorker);\n\n/**\n * @see GenericWorker.processChunk\n */\nUtf8DecodeWorker.prototype.processChunk = function (chunk) {\n\n var data = utils.transformTo(support.uint8array ? \"uint8array\" : \"array\", chunk.data);\n\n // 1st step, re-use what's left of the previous chunk\n if (this.leftOver && this.leftOver.length) {\n if(support.uint8array) {\n var previousData = data;\n data = new Uint8Array(previousData.length + this.leftOver.length);\n data.set(this.leftOver, 0);\n data.set(previousData, this.leftOver.length);\n } else {\n data = this.leftOver.concat(data);\n }\n this.leftOver = null;\n }\n\n var nextBoundary = utf8border(data);\n var usableData = data;\n if (nextBoundary !== data.length) {\n if (support.uint8array) {\n usableData = data.subarray(0, nextBoundary);\n this.leftOver = data.subarray(nextBoundary, data.length);\n } else {\n usableData = data.slice(0, nextBoundary);\n this.leftOver = data.slice(nextBoundary, data.length);\n }\n }\n\n this.push({\n data : exports.utf8decode(usableData),\n meta : chunk.meta\n });\n};\n\n/**\n * @see GenericWorker.flush\n */\nUtf8DecodeWorker.prototype.flush = function () {\n if(this.leftOver && this.leftOver.length) {\n this.push({\n data : exports.utf8decode(this.leftOver),\n meta : {}\n });\n this.leftOver = null;\n }\n};\nexports.Utf8DecodeWorker = Utf8DecodeWorker;\n\n/**\n * A worker to endcode string chunks into utf8 encoded binary chunks.\n * @constructor\n */\nfunction Utf8EncodeWorker() {\n GenericWorker.call(this, \"utf-8 encode\");\n}\nutils.inherits(Utf8EncodeWorker, GenericWorker);\n\n/**\n * @see GenericWorker.processChunk\n */\nUtf8EncodeWorker.prototype.processChunk = function (chunk) {\n this.push({\n data : exports.utf8encode(chunk.data),\n meta : chunk.meta\n });\n};\nexports.Utf8EncodeWorker = Utf8EncodeWorker;\n", "\"use strict\";\n\nvar GenericWorker = require(\"./GenericWorker\");\nvar utils = require(\"../utils\");\n\n/**\n * A worker which convert chunks to a specified type.\n * @constructor\n * @param {String} destType the destination type.\n */\nfunction ConvertWorker(destType) {\n GenericWorker.call(this, \"ConvertWorker to \" + destType);\n this.destType = destType;\n}\nutils.inherits(ConvertWorker, GenericWorker);\n\n/**\n * @see GenericWorker.processChunk\n */\nConvertWorker.prototype.processChunk = function (chunk) {\n this.push({\n data : utils.transformTo(this.destType, chunk.data),\n meta : chunk.meta\n });\n};\nmodule.exports = ConvertWorker;\n", "\"use strict\";\n\nvar Readable = require(\"readable-stream\").Readable;\n\nvar utils = require(\"../utils\");\nutils.inherits(NodejsStreamOutputAdapter, Readable);\n\n/**\n* A nodejs stream using a worker as source.\n* @see the SourceWrapper in http://nodejs.org/api/stream.html\n* @constructor\n* @param {StreamHelper} helper the helper wrapping the worker\n* @param {Object} options the nodejs stream options\n* @param {Function} updateCb the update callback.\n*/\nfunction NodejsStreamOutputAdapter(helper, options, updateCb) {\n Readable.call(this, options);\n this._helper = helper;\n\n var self = this;\n helper.on(\"data\", function (data, meta) {\n if (!self.push(data)) {\n self._helper.pause();\n }\n if(updateCb) {\n updateCb(meta);\n }\n })\n .on(\"error\", function(e) {\n self.emit(\"error\", e);\n })\n .on(\"end\", function () {\n self.push(null);\n });\n}\n\n\nNodejsStreamOutputAdapter.prototype._read = function() {\n this._helper.resume();\n};\n\nmodule.exports = NodejsStreamOutputAdapter;\n", "\"use strict\";\n\nvar utils = require(\"../utils\");\nvar ConvertWorker = require(\"./ConvertWorker\");\nvar GenericWorker = require(\"./GenericWorker\");\nvar base64 = require(\"../base64\");\nvar support = require(\"../support\");\nvar external = require(\"../external\");\n\nvar NodejsStreamOutputAdapter = null;\nif (support.nodestream) {\n try {\n NodejsStreamOutputAdapter = require(\"../nodejs/NodejsStreamOutputAdapter\");\n } catch(e) {\n // ignore\n }\n}\n\n/**\n * Apply the final transformation of the data. If the user wants a Blob for\n * example, it's easier to work with an U8intArray and finally do the\n * ArrayBuffer/Blob conversion.\n * @param {String} type the name of the final type\n * @param {String|Uint8Array|Buffer} content the content to transform\n * @param {String} mimeType the mime type of the content, if applicable.\n * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the content in the right format.\n */\nfunction transformZipOutput(type, content, mimeType) {\n switch(type) {\n case \"blob\" :\n return utils.newBlob(utils.transformTo(\"arraybuffer\", content), mimeType);\n case \"base64\" :\n return base64.encode(content);\n default :\n return utils.transformTo(type, content);\n }\n}\n\n/**\n * Concatenate an array of data of the given type.\n * @param {String} type the type of the data in the given array.\n * @param {Array} dataArray the array containing the data chunks to concatenate\n * @return {String|Uint8Array|Buffer} the concatenated data\n * @throws Error if the asked type is unsupported\n */\nfunction concat (type, dataArray) {\n var i, index = 0, res = null, totalLength = 0;\n for(i = 0; i < dataArray.length; i++) {\n totalLength += dataArray[i].length;\n }\n switch(type) {\n case \"string\":\n return dataArray.join(\"\");\n case \"array\":\n return Array.prototype.concat.apply([], dataArray);\n case \"uint8array\":\n res = new Uint8Array(totalLength);\n for(i = 0; i < dataArray.length; i++) {\n res.set(dataArray[i], index);\n index += dataArray[i].length;\n }\n return res;\n case \"nodebuffer\":\n return Buffer.concat(dataArray);\n default:\n throw new Error(\"concat : unsupported type '\" + type + \"'\");\n }\n}\n\n/**\n * Listen a StreamHelper, accumulate its content and concatenate it into a\n * complete block.\n * @param {StreamHelper} helper the helper to use.\n * @param {Function} updateCallback a callback called on each update. Called\n * with one arg :\n * - the metadata linked to the update received.\n * @return Promise the promise for the accumulation.\n */\nfunction accumulate(helper, updateCallback) {\n return new external.Promise(function (resolve, reject){\n var dataArray = [];\n var chunkType = helper._internalType,\n resultType = helper._outputType,\n mimeType = helper._mimeType;\n helper\n .on(\"data\", function (data, meta) {\n dataArray.push(data);\n if(updateCallback) {\n updateCallback(meta);\n }\n })\n .on(\"error\", function(err) {\n dataArray = [];\n reject(err);\n })\n .on(\"end\", function (){\n try {\n var result = transformZipOutput(resultType, concat(chunkType, dataArray), mimeType);\n resolve(result);\n } catch (e) {\n reject(e);\n }\n dataArray = [];\n })\n .resume();\n });\n}\n\n/**\n * An helper to easily use workers outside of JSZip.\n * @constructor\n * @param {Worker} worker the worker to wrap\n * @param {String} outputType the type of data expected by the use\n * @param {String} mimeType the mime type of the content, if applicable.\n */\nfunction StreamHelper(worker, outputType, mimeType) {\n var internalType = outputType;\n switch(outputType) {\n case \"blob\":\n case \"arraybuffer\":\n internalType = \"uint8array\";\n break;\n case \"base64\":\n internalType = \"string\";\n break;\n }\n\n try {\n // the type used internally\n this._internalType = internalType;\n // the type used to output results\n this._outputType = outputType;\n // the mime type\n this._mimeType = mimeType;\n utils.checkSupport(internalType);\n this._worker = worker.pipe(new ConvertWorker(internalType));\n // the last workers can be rewired without issues but we need to\n // prevent any updates on previous workers.\n worker.lock();\n } catch(e) {\n this._worker = new GenericWorker(\"error\");\n this._worker.error(e);\n }\n}\n\nStreamHelper.prototype = {\n /**\n * Listen a StreamHelper, accumulate its content and concatenate it into a\n * complete block.\n * @param {Function} updateCb the update callback.\n * @return Promise the promise for the accumulation.\n */\n accumulate : function (updateCb) {\n return accumulate(this, updateCb);\n },\n /**\n * Add a listener on an event triggered on a stream.\n * @param {String} evt the name of the event\n * @param {Function} fn the listener\n * @return {StreamHelper} the current helper.\n */\n on : function (evt, fn) {\n var self = this;\n\n if(evt === \"data\") {\n this._worker.on(evt, function (chunk) {\n fn.call(self, chunk.data, chunk.meta);\n });\n } else {\n this._worker.on(evt, function () {\n utils.delay(fn, arguments, self);\n });\n }\n return this;\n },\n /**\n * Resume the flow of chunks.\n * @return {StreamHelper} the current helper.\n */\n resume : function () {\n utils.delay(this._worker.resume, [], this._worker);\n return this;\n },\n /**\n * Pause the flow of chunks.\n * @return {StreamHelper} the current helper.\n */\n pause : function () {\n this._worker.pause();\n return this;\n },\n /**\n * Return a nodejs stream for this helper.\n * @param {Function} updateCb the update callback.\n * @return {NodejsStreamOutputAdapter} the nodejs stream.\n */\n toNodejsStream : function (updateCb) {\n utils.checkSupport(\"nodestream\");\n if (this._outputType !== \"nodebuffer\") {\n // an object stream containing blob/arraybuffer/uint8array/string\n // is strange and I don't know if it would be useful.\n // I you find this comment and have a good usecase, please open a\n // bug report !\n throw new Error(this._outputType + \" is not supported by this method\");\n }\n\n return new NodejsStreamOutputAdapter(this, {\n objectMode : this._outputType !== \"nodebuffer\"\n }, updateCb);\n }\n};\n\n\nmodule.exports = StreamHelper;\n", "\"use strict\";\nexports.base64 = false;\nexports.binary = false;\nexports.dir = false;\nexports.createFolders = true;\nexports.date = null;\nexports.compression = null;\nexports.compressionOptions = null;\nexports.comment = null;\nexports.unixPermissions = null;\nexports.dosPermissions = null;\n", "\"use strict\";\n\nvar utils = require(\"../utils\");\nvar GenericWorker = require(\"./GenericWorker\");\n\n// the size of the generated chunks\n// TODO expose this as a public variable\nvar DEFAULT_BLOCK_SIZE = 16 * 1024;\n\n/**\n * A worker that reads a content and emits chunks.\n * @constructor\n * @param {Promise} dataP the promise of the data to split\n */\nfunction DataWorker(dataP) {\n GenericWorker.call(this, \"DataWorker\");\n var self = this;\n this.dataIsReady = false;\n this.index = 0;\n this.max = 0;\n this.data = null;\n this.type = \"\";\n\n this._tickScheduled = false;\n\n dataP.then(function (data) {\n self.dataIsReady = true;\n self.data = data;\n self.max = data && data.length || 0;\n self.type = utils.getTypeOf(data);\n if(!self.isPaused) {\n self._tickAndRepeat();\n }\n }, function (e) {\n self.error(e);\n });\n}\n\nutils.inherits(DataWorker, GenericWorker);\n\n/**\n * @see GenericWorker.cleanUp\n */\nDataWorker.prototype.cleanUp = function () {\n GenericWorker.prototype.cleanUp.call(this);\n this.data = null;\n};\n\n/**\n * @see GenericWorker.resume\n */\nDataWorker.prototype.resume = function () {\n if(!GenericWorker.prototype.resume.call(this)) {\n return false;\n }\n\n if (!this._tickScheduled && this.dataIsReady) {\n this._tickScheduled = true;\n utils.delay(this._tickAndRepeat, [], this);\n }\n return true;\n};\n\n/**\n * Trigger a tick a schedule an other call to this function.\n */\nDataWorker.prototype._tickAndRepeat = function() {\n this._tickScheduled = false;\n if(this.isPaused || this.isFinished) {\n return;\n }\n this._tick();\n if(!this.isFinished) {\n utils.delay(this._tickAndRepeat, [], this);\n this._tickScheduled = true;\n }\n};\n\n/**\n * Read and push a chunk.\n */\nDataWorker.prototype._tick = function() {\n\n if(this.isPaused || this.isFinished) {\n return false;\n }\n\n var size = DEFAULT_BLOCK_SIZE;\n var data = null, nextIndex = Math.min(this.max, this.index + size);\n if (this.index >= this.max) {\n // EOF\n return this.end();\n } else {\n switch(this.type) {\n case \"string\":\n data = this.data.substring(this.index, nextIndex);\n break;\n case \"uint8array\":\n data = this.data.subarray(this.index, nextIndex);\n break;\n case \"array\":\n case \"nodebuffer\":\n data = this.data.slice(this.index, nextIndex);\n break;\n }\n this.index = nextIndex;\n return this.push({\n data : data,\n meta : {\n percent : this.max ? this.index / this.max * 100 : 0\n }\n });\n }\n};\n\nmodule.exports = DataWorker;\n", "\"use strict\";\n\nvar utils = require(\"./utils\");\n\n/**\n * The following functions come from pako, from pako/lib/zlib/crc32.js\n * released under the MIT license, see pako https://github.com/nodeca/pako/\n */\n\n// Use ordinary array, since untyped makes no boost here\nfunction makeTable() {\n var c, table = [];\n\n for(var n =0; n < 256; n++){\n c = n;\n for(var k =0; k < 8; k++){\n c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n table[n] = c;\n }\n\n return table;\n}\n\n// Create table on load. Just 255 signed longs. Not a problem.\nvar crcTable = makeTable();\n\n\nfunction crc32(crc, buf, len, pos) {\n var t = crcTable, end = pos + len;\n\n crc = crc ^ (-1);\n\n for (var i = pos; i < end; i++ ) {\n crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];\n }\n\n return (crc ^ (-1)); // >>> 0;\n}\n\n// That's all for the pako functions.\n\n/**\n * Compute the crc32 of a string.\n * This is almost the same as the function crc32, but for strings. Using the\n * same function for the two use cases leads to horrible performances.\n * @param {Number} crc the starting value of the crc.\n * @param {String} str the string to use.\n * @param {Number} len the length of the string.\n * @param {Number} pos the starting position for the crc32 computation.\n * @return {Number} the computed crc32.\n */\nfunction crc32str(crc, str, len, pos) {\n var t = crcTable, end = pos + len;\n\n crc = crc ^ (-1);\n\n for (var i = pos; i < end; i++ ) {\n crc = (crc >>> 8) ^ t[(crc ^ str.charCodeAt(i)) & 0xFF];\n }\n\n return (crc ^ (-1)); // >>> 0;\n}\n\nmodule.exports = function crc32wrapper(input, crc) {\n if (typeof input === \"undefined\" || !input.length) {\n return 0;\n }\n\n var isArray = utils.getTypeOf(input) !== \"string\";\n\n if(isArray) {\n return crc32(crc|0, input, input.length, 0);\n } else {\n return crc32str(crc|0, input, input.length, 0);\n }\n};\n", "\"use strict\";\n\nvar GenericWorker = require(\"./GenericWorker\");\nvar crc32 = require(\"../crc32\");\nvar utils = require(\"../utils\");\n\n/**\n * A worker which calculate the crc32 of the data flowing through.\n * @constructor\n */\nfunction Crc32Probe() {\n GenericWorker.call(this, \"Crc32Probe\");\n this.withStreamInfo(\"crc32\", 0);\n}\nutils.inherits(Crc32Probe, GenericWorker);\n\n/**\n * @see GenericWorker.processChunk\n */\nCrc32Probe.prototype.processChunk = function (chunk) {\n this.streamInfo.crc32 = crc32(chunk.data, this.streamInfo.crc32 || 0);\n this.push(chunk);\n};\nmodule.exports = Crc32Probe;\n", "\"use strict\";\n\nvar utils = require(\"../utils\");\nvar GenericWorker = require(\"./GenericWorker\");\n\n/**\n * A worker which calculate the total length of the data flowing through.\n * @constructor\n * @param {String} propName the name used to expose the length\n */\nfunction DataLengthProbe(propName) {\n GenericWorker.call(this, \"DataLengthProbe for \" + propName);\n this.propName = propName;\n this.withStreamInfo(propName, 0);\n}\nutils.inherits(DataLengthProbe, GenericWorker);\n\n/**\n * @see GenericWorker.processChunk\n */\nDataLengthProbe.prototype.processChunk = function (chunk) {\n if(chunk) {\n var length = this.streamInfo[this.propName] || 0;\n this.streamInfo[this.propName] = length + chunk.data.length;\n }\n GenericWorker.prototype.processChunk.call(this, chunk);\n};\nmodule.exports = DataLengthProbe;\n\n", "\"use strict\";\n\nvar external = require(\"./external\");\nvar DataWorker = require(\"./stream/DataWorker\");\nvar Crc32Probe = require(\"./stream/Crc32Probe\");\nvar DataLengthProbe = require(\"./stream/DataLengthProbe\");\n\n/**\n * Represent a compressed object, with everything needed to decompress it.\n * @constructor\n * @param {number} compressedSize the size of the data compressed.\n * @param {number} uncompressedSize the size of the data after decompression.\n * @param {number} crc32 the crc32 of the decompressed file.\n * @param {object} compression the type of compression, see lib/compressions.js.\n * @param {String|ArrayBuffer|Uint8Array|Buffer} data the compressed data.\n */\nfunction CompressedObject(compressedSize, uncompressedSize, crc32, compression, data) {\n this.compressedSize = compressedSize;\n this.uncompressedSize = uncompressedSize;\n this.crc32 = crc32;\n this.compression = compression;\n this.compressedContent = data;\n}\n\nCompressedObject.prototype = {\n /**\n * Create a worker to get the uncompressed content.\n * @return {GenericWorker} the worker.\n */\n getContentWorker: function () {\n var worker = new DataWorker(external.Promise.resolve(this.compressedContent))\n .pipe(this.compression.uncompressWorker())\n .pipe(new DataLengthProbe(\"data_length\"));\n\n var that = this;\n worker.on(\"end\", function () {\n if (this.streamInfo[\"data_length\"] !== that.uncompressedSize) {\n throw new Error(\"Bug : uncompressed data size mismatch\");\n }\n });\n return worker;\n },\n /**\n * Create a worker to get the compressed content.\n * @return {GenericWorker} the worker.\n */\n getCompressedWorker: function () {\n return new DataWorker(external.Promise.resolve(this.compressedContent))\n .withStreamInfo(\"compressedSize\", this.compressedSize)\n .withStreamInfo(\"uncompressedSize\", this.uncompressedSize)\n .withStreamInfo(\"crc32\", this.crc32)\n .withStreamInfo(\"compression\", this.compression)\n ;\n }\n};\n\n/**\n * Chain the given worker with other workers to compress the content with the\n * given compression.\n * @param {GenericWorker} uncompressedWorker the worker to pipe.\n * @param {Object} compression the compression object.\n * @param {Object} compressionOptions the options to use when compressing.\n * @return {GenericWorker} the new worker compressing the content.\n */\nCompressedObject.createWorkerFrom = function (uncompressedWorker, compression, compressionOptions) {\n return uncompressedWorker\n .pipe(new Crc32Probe())\n .pipe(new DataLengthProbe(\"uncompressedSize\"))\n .pipe(compression.compressWorker(compressionOptions))\n .pipe(new DataLengthProbe(\"compressedSize\"))\n .withStreamInfo(\"compression\", compression);\n};\n\nmodule.exports = CompressedObject;\n", "\"use strict\";\n\nvar StreamHelper = require(\"./stream/StreamHelper\");\nvar DataWorker = require(\"./stream/DataWorker\");\nvar utf8 = require(\"./utf8\");\nvar CompressedObject = require(\"./compressedObject\");\nvar GenericWorker = require(\"./stream/GenericWorker\");\n\n/**\n * A simple object representing a file in the zip file.\n * @constructor\n * @param {string} name the name of the file\n * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data\n * @param {Object} options the options of the file\n */\nvar ZipObject = function(name, data, options) {\n this.name = name;\n this.dir = options.dir;\n this.date = options.date;\n this.comment = options.comment;\n this.unixPermissions = options.unixPermissions;\n this.dosPermissions = options.dosPermissions;\n\n this._data = data;\n this._dataBinary = options.binary;\n // keep only the compression\n this.options = {\n compression : options.compression,\n compressionOptions : options.compressionOptions\n };\n};\n\nZipObject.prototype = {\n /**\n * Create an internal stream for the content of this object.\n * @param {String} type the type of each chunk.\n * @return StreamHelper the stream.\n */\n internalStream: function (type) {\n var result = null, outputType = \"string\";\n try {\n if (!type) {\n throw new Error(\"No output type specified.\");\n }\n outputType = type.toLowerCase();\n var askUnicodeString = outputType === \"string\" || outputType === \"text\";\n if (outputType === \"binarystring\" || outputType === \"text\") {\n outputType = \"string\";\n }\n result = this._decompressWorker();\n\n var isUnicodeString = !this._dataBinary;\n\n if (isUnicodeString && !askUnicodeString) {\n result = result.pipe(new utf8.Utf8EncodeWorker());\n }\n if (!isUnicodeString && askUnicodeString) {\n result = result.pipe(new utf8.Utf8DecodeWorker());\n }\n } catch (e) {\n result = new GenericWorker(\"error\");\n result.error(e);\n }\n\n return new StreamHelper(result, outputType, \"\");\n },\n\n /**\n * Prepare the content in the asked type.\n * @param {String} type the type of the result.\n * @param {Function} onUpdate a function to call on each internal update.\n * @return Promise the promise of the result.\n */\n async: function (type, onUpdate) {\n return this.internalStream(type).accumulate(onUpdate);\n },\n\n /**\n * Prepare the content as a nodejs stream.\n * @param {String} type the type of each chunk.\n * @param {Function} onUpdate a function to call on each internal update.\n * @return Stream the stream.\n */\n nodeStream: function (type, onUpdate) {\n return this.internalStream(type || \"nodebuffer\").toNodejsStream(onUpdate);\n },\n\n /**\n * Return a worker for the compressed content.\n * @private\n * @param {Object} compression the compression object to use.\n * @param {Object} compressionOptions the options to use when compressing.\n * @return Worker the worker.\n */\n _compressWorker: function (compression, compressionOptions) {\n if (\n this._data instanceof CompressedObject &&\n this._data.compression.magic === compression.magic\n ) {\n return this._data.getCompressedWorker();\n } else {\n var result = this._decompressWorker();\n if(!this._dataBinary) {\n result = result.pipe(new utf8.Utf8EncodeWorker());\n }\n return CompressedObject.createWorkerFrom(result, compression, compressionOptions);\n }\n },\n /**\n * Return a worker for the decompressed content.\n * @private\n * @return Worker the worker.\n */\n _decompressWorker : function () {\n if (this._data instanceof CompressedObject) {\n return this._data.getContentWorker();\n } else if (this._data instanceof GenericWorker) {\n return this._data;\n } else {\n return new DataWorker(this._data);\n }\n }\n};\n\nvar removedMethods = [\"asText\", \"asBinary\", \"asNodeBuffer\", \"asUint8Array\", \"asArrayBuffer\"];\nvar removedFn = function () {\n throw new Error(\"This method has been removed in JSZip 3.0, please check the upgrade guide.\");\n};\n\nfor(var i = 0; i < removedMethods.length; i++) {\n ZipObject.prototype[removedMethods[i]] = removedFn;\n}\nmodule.exports = ZipObject;\n", "'use strict';\n\n\nvar TYPED_OK = (typeof Uint8Array !== 'undefined') &&\n (typeof Uint16Array !== 'undefined') &&\n (typeof Int32Array !== 'undefined');\n\nfunction _has(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nexports.assign = function (obj /*from1, from2, from3, ...*/) {\n var sources = Array.prototype.slice.call(arguments, 1);\n while (sources.length) {\n var source = sources.shift();\n if (!source) { continue; }\n\n if (typeof source !== 'object') {\n throw new TypeError(source + 'must be non-object');\n }\n\n for (var p in source) {\n if (_has(source, p)) {\n obj[p] = source[p];\n }\n }\n }\n\n return obj;\n};\n\n\n// reduce buffer size, avoiding mem copy\nexports.shrinkBuf = function (buf, size) {\n if (buf.length === size) { return buf; }\n if (buf.subarray) { return buf.subarray(0, size); }\n buf.length = size;\n return buf;\n};\n\n\nvar fnTyped = {\n arraySet: function (dest, src, src_offs, len, dest_offs) {\n if (src.subarray && dest.subarray) {\n dest.set(src.subarray(src_offs, src_offs + len), dest_offs);\n return;\n }\n // Fallback to ordinary array\n for (var i = 0; i < len; i++) {\n dest[dest_offs + i] = src[src_offs + i];\n }\n },\n // Join array of chunks to single array.\n flattenChunks: function (chunks) {\n var i, l, len, pos, chunk, result;\n\n // calculate data length\n len = 0;\n for (i = 0, l = chunks.length; i < l; i++) {\n len += chunks[i].length;\n }\n\n // join chunks\n result = new Uint8Array(len);\n pos = 0;\n for (i = 0, l = chunks.length; i < l; i++) {\n chunk = chunks[i];\n result.set(chunk, pos);\n pos += chunk.length;\n }\n\n return result;\n }\n};\n\nvar fnUntyped = {\n arraySet: function (dest, src, src_offs, len, dest_offs) {\n for (var i = 0; i < len; i++) {\n dest[dest_offs + i] = src[src_offs + i];\n }\n },\n // Join array of chunks to single array.\n flattenChunks: function (chunks) {\n return [].concat.apply([], chunks);\n }\n};\n\n\n// Enable/Disable typed arrays use, for testing\n//\nexports.setTyped = function (on) {\n if (on) {\n exports.Buf8 = Uint8Array;\n exports.Buf16 = Uint16Array;\n exports.Buf32 = Int32Array;\n exports.assign(exports, fnTyped);\n } else {\n exports.Buf8 = Array;\n exports.Buf16 = Array;\n exports.Buf32 = Array;\n exports.assign(exports, fnUntyped);\n }\n};\n\nexports.setTyped(TYPED_OK);\n", "'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n/* eslint-disable space-unary-ops */\n\nvar utils = require('../utils/common');\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n//var Z_FILTERED = 1;\n//var Z_HUFFMAN_ONLY = 2;\n//var Z_RLE = 3;\nvar Z_FIXED = 4;\n//var Z_DEFAULT_STRATEGY = 0;\n\n/* Possible values of the data_type field (though see inflate()) */\nvar Z_BINARY = 0;\nvar Z_TEXT = 1;\n//var Z_ASCII = 1; // = Z_TEXT\nvar Z_UNKNOWN = 2;\n\n/*============================================================================*/\n\n\nfunction zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }\n\n// From zutil.h\n\nvar STORED_BLOCK = 0;\nvar STATIC_TREES = 1;\nvar DYN_TREES = 2;\n/* The three kinds of block type */\n\nvar MIN_MATCH = 3;\nvar MAX_MATCH = 258;\n/* The minimum and maximum match lengths */\n\n// From deflate.h\n/* ===========================================================================\n * Internal compression state.\n */\n\nvar LENGTH_CODES = 29;\n/* number of length codes, not counting the special END_BLOCK code */\n\nvar LITERALS = 256;\n/* number of literal bytes 0..255 */\n\nvar L_CODES = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\n\nvar D_CODES = 30;\n/* number of distance codes */\n\nvar BL_CODES = 19;\n/* number of codes used to transfer the bit lengths */\n\nvar HEAP_SIZE = 2 * L_CODES + 1;\n/* maximum heap size */\n\nvar MAX_BITS = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nvar Buf_size = 16;\n/* size of bit buffer in bi_buf */\n\n\n/* ===========================================================================\n * Constants\n */\n\nvar MAX_BL_BITS = 7;\n/* Bit length codes must not exceed MAX_BL_BITS bits */\n\nvar END_BLOCK = 256;\n/* end of block literal code */\n\nvar REP_3_6 = 16;\n/* repeat previous bit length 3-6 times (2 bits of repeat count) */\n\nvar REPZ_3_10 = 17;\n/* repeat a zero length 3-10 times (3 bits of repeat count) */\n\nvar REPZ_11_138 = 18;\n/* repeat a zero length 11-138 times (7 bits of repeat count) */\n\n/* eslint-disable comma-spacing,array-bracket-spacing */\nvar extra_lbits = /* extra bits for each length code */\n [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];\n\nvar extra_dbits = /* extra bits for each distance code */\n [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];\n\nvar extra_blbits = /* extra bits for each bit length code */\n [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];\n\nvar bl_order =\n [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];\n/* eslint-enable comma-spacing,array-bracket-spacing */\n\n/* The lengths of the bit length codes are sent in order of decreasing\n * probability, to avoid transmitting the lengths for unused bit length codes.\n */\n\n/* ===========================================================================\n * Local data. These are initialized only once.\n */\n\n// We pre-fill arrays with 0 to avoid uninitialized gaps\n\nvar DIST_CODE_LEN = 512; /* see definition of array dist_code below */\n\n// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1\nvar static_ltree = new Array((L_CODES + 2) * 2);\nzero(static_ltree);\n/* The static literal tree. Since the bit lengths are imposed, there is no\n * need for the L_CODES extra codes used during heap construction. However\n * The codes 286 and 287 are needed to build a canonical tree (see _tr_init\n * below).\n */\n\nvar static_dtree = new Array(D_CODES * 2);\nzero(static_dtree);\n/* The static distance tree. (Actually a trivial tree since all codes use\n * 5 bits.)\n */\n\nvar _dist_code = new Array(DIST_CODE_LEN);\nzero(_dist_code);\n/* Distance codes. The first 256 values correspond to the distances\n * 3 .. 258, the last 256 values correspond to the top 8 bits of\n * the 15 bit distances.\n */\n\nvar _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);\nzero(_length_code);\n/* length code for each normalized match length (0 == MIN_MATCH) */\n\nvar base_length = new Array(LENGTH_CODES);\nzero(base_length);\n/* First normalized length for each code (0 = MIN_MATCH) */\n\nvar base_dist = new Array(D_CODES);\nzero(base_dist);\n/* First normalized distance for each code (0 = distance of 1) */\n\n\nfunction StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {\n\n this.static_tree = static_tree; /* static tree or NULL */\n this.extra_bits = extra_bits; /* extra bits for each code or NULL */\n this.extra_base = extra_base; /* base index for extra_bits */\n this.elems = elems; /* max number of elements in the tree */\n this.max_length = max_length; /* max bit length for the codes */\n\n // show if `static_tree` has data or dummy - needed for monomorphic objects\n this.has_stree = static_tree && static_tree.length;\n}\n\n\nvar static_l_desc;\nvar static_d_desc;\nvar static_bl_desc;\n\n\nfunction TreeDesc(dyn_tree, stat_desc) {\n this.dyn_tree = dyn_tree; /* the dynamic tree */\n this.max_code = 0; /* largest code with non zero frequency */\n this.stat_desc = stat_desc; /* the corresponding static tree */\n}\n\n\n\nfunction d_code(dist) {\n return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];\n}\n\n\n/* ===========================================================================\n * Output a short LSB first on the stream.\n * IN assertion: there is enough room in pendingBuf.\n */\nfunction put_short(s, w) {\n// put_byte(s, (uch)((w) & 0xff));\n// put_byte(s, (uch)((ush)(w) >> 8));\n s.pending_buf[s.pending++] = (w) & 0xff;\n s.pending_buf[s.pending++] = (w >>> 8) & 0xff;\n}\n\n\n/* ===========================================================================\n * Send a value on a given number of bits.\n * IN assertion: length <= 16 and value fits in length bits.\n */\nfunction send_bits(s, value, length) {\n if (s.bi_valid > (Buf_size - length)) {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n put_short(s, s.bi_buf);\n s.bi_buf = value >> (Buf_size - s.bi_valid);\n s.bi_valid += length - Buf_size;\n } else {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n s.bi_valid += length;\n }\n}\n\n\nfunction send_code(s, c, tree) {\n send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);\n}\n\n\n/* ===========================================================================\n * Reverse the first len bits of a code, using straightforward code (a faster\n * method would use a table)\n * IN assertion: 1 <= len <= 15\n */\nfunction bi_reverse(code, len) {\n var res = 0;\n do {\n res |= code & 1;\n code >>>= 1;\n res <<= 1;\n } while (--len > 0);\n return res >>> 1;\n}\n\n\n/* ===========================================================================\n * Flush the bit buffer, keeping at most 7 bits in it.\n */\nfunction bi_flush(s) {\n if (s.bi_valid === 16) {\n put_short(s, s.bi_buf);\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n } else if (s.bi_valid >= 8) {\n s.pending_buf[s.pending++] = s.bi_buf & 0xff;\n s.bi_buf >>= 8;\n s.bi_valid -= 8;\n }\n}\n\n\n/* ===========================================================================\n * Compute the optimal bit lengths for a tree and update the total bit length\n * for the current block.\n * IN assertion: the fields freq and dad are set, heap[heap_max] and\n * above are the tree nodes sorted by increasing frequency.\n * OUT assertions: the field len is set to the optimal bit length, the\n * array bl_count contains the frequencies for each bit length.\n * The length opt_len is updated; static_len is also updated if stree is\n * not null.\n */\nfunction gen_bitlen(s, desc)\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n{\n var tree = desc.dyn_tree;\n var max_code = desc.max_code;\n var stree = desc.stat_desc.static_tree;\n var has_stree = desc.stat_desc.has_stree;\n var extra = desc.stat_desc.extra_bits;\n var base = desc.stat_desc.extra_base;\n var max_length = desc.stat_desc.max_length;\n var h; /* heap index */\n var n, m; /* iterate over the tree elements */\n var bits; /* bit length */\n var xbits; /* extra bits */\n var f; /* frequency */\n var overflow = 0; /* number of elements with bit length too large */\n\n for (bits = 0; bits <= MAX_BITS; bits++) {\n s.bl_count[bits] = 0;\n }\n\n /* In a first pass, compute the optimal bit lengths (which may\n * overflow in the case of the bit length tree).\n */\n tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */\n\n for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {\n n = s.heap[h];\n bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;\n if (bits > max_length) {\n bits = max_length;\n overflow++;\n }\n tree[n * 2 + 1]/*.Len*/ = bits;\n /* We overwrite tree[n].Dad which is no longer needed */\n\n if (n > max_code) { continue; } /* not a leaf node */\n\n s.bl_count[bits]++;\n xbits = 0;\n if (n >= base) {\n xbits = extra[n - base];\n }\n f = tree[n * 2]/*.Freq*/;\n s.opt_len += f * (bits + xbits);\n if (has_stree) {\n s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);\n }\n }\n if (overflow === 0) { return; }\n\n // Trace((stderr,\"\\nbit length overflow\\n\"));\n /* This happens for example on obj2 and pic of the Calgary corpus */\n\n /* Find the first bit length which could increase: */\n do {\n bits = max_length - 1;\n while (s.bl_count[bits] === 0) { bits--; }\n s.bl_count[bits]--; /* move one leaf down the tree */\n s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */\n s.bl_count[max_length]--;\n /* The brother of the overflow item also moves one step up,\n * but this does not affect bl_count[max_length]\n */\n overflow -= 2;\n } while (overflow > 0);\n\n /* Now recompute all bit lengths, scanning in increasing frequency.\n * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all\n * lengths instead of fixing only the wrong ones. This idea is taken\n * from 'ar' written by Haruhiko Okumura.)\n */\n for (bits = max_length; bits !== 0; bits--) {\n n = s.bl_count[bits];\n while (n !== 0) {\n m = s.heap[--h];\n if (m > max_code) { continue; }\n if (tree[m * 2 + 1]/*.Len*/ !== bits) {\n // Trace((stderr,\"code %d bits %d->%d\\n\", m, tree[m].Len, bits));\n s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;\n tree[m * 2 + 1]/*.Len*/ = bits;\n }\n n--;\n }\n }\n}\n\n\n/* ===========================================================================\n * Generate the codes for a given tree and bit counts (which need not be\n * optimal).\n * IN assertion: the array bl_count contains the bit length statistics for\n * the given tree and the field len is set for all tree elements.\n * OUT assertion: the field code is set for all tree elements of non\n * zero code length.\n */\nfunction gen_codes(tree, max_code, bl_count)\n// ct_data *tree; /* the tree to decorate */\n// int max_code; /* largest code with non zero frequency */\n// ushf *bl_count; /* number of codes at each bit length */\n{\n var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */\n var code = 0; /* running code value */\n var bits; /* bit index */\n var n; /* code index */\n\n /* The distribution counts are first used to generate the code values\n * without bit reversal.\n */\n for (bits = 1; bits <= MAX_BITS; bits++) {\n next_code[bits] = code = (code + bl_count[bits - 1]) << 1;\n }\n /* Check that the bit counts in bl_count are consistent. The last code\n * must be all ones.\n */\n //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,\n // \"inconsistent bit counts\");\n //Tracev((stderr,\"\\ngen_codes: max_code %d \", max_code));\n\n for (n = 0; n <= max_code; n++) {\n var len = tree[n * 2 + 1]/*.Len*/;\n if (len === 0) { continue; }\n /* Now reverse the bits */\n tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);\n\n //Tracecv(tree != static_ltree, (stderr,\"\\nn %3d %c l %2d c %4x (%x) \",\n // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));\n }\n}\n\n\n/* ===========================================================================\n * Initialize the various 'constant' tables.\n */\nfunction tr_static_init() {\n var n; /* iterates over tree elements */\n var bits; /* bit counter */\n var length; /* length value */\n var code; /* code value */\n var dist; /* distance index */\n var bl_count = new Array(MAX_BITS + 1);\n /* number of codes at each bit length for an optimal tree */\n\n // do check in _tr_init()\n //if (static_init_done) return;\n\n /* For some embedded targets, global variables are not initialized: */\n/*#ifdef NO_INIT_GLOBAL_POINTERS\n static_l_desc.static_tree = static_ltree;\n static_l_desc.extra_bits = extra_lbits;\n static_d_desc.static_tree = static_dtree;\n static_d_desc.extra_bits = extra_dbits;\n static_bl_desc.extra_bits = extra_blbits;\n#endif*/\n\n /* Initialize the mapping length (0..255) -> length code (0..28) */\n length = 0;\n for (code = 0; code < LENGTH_CODES - 1; code++) {\n base_length[code] = length;\n for (n = 0; n < (1 << extra_lbits[code]); n++) {\n _length_code[length++] = code;\n }\n }\n //Assert (length == 256, \"tr_static_init: length != 256\");\n /* Note that the length 255 (match length 258) can be represented\n * in two different ways: code 284 + 5 bits or code 285, so we\n * overwrite length_code[255] to use the best encoding:\n */\n _length_code[length - 1] = code;\n\n /* Initialize the mapping dist (0..32K) -> dist code (0..29) */\n dist = 0;\n for (code = 0; code < 16; code++) {\n base_dist[code] = dist;\n for (n = 0; n < (1 << extra_dbits[code]); n++) {\n _dist_code[dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: dist != 256\");\n dist >>= 7; /* from now on, all distances are divided by 128 */\n for (; code < D_CODES; code++) {\n base_dist[code] = dist << 7;\n for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {\n _dist_code[256 + dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: 256+dist != 512\");\n\n /* Construct the codes of the static literal tree */\n for (bits = 0; bits <= MAX_BITS; bits++) {\n bl_count[bits] = 0;\n }\n\n n = 0;\n while (n <= 143) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n while (n <= 255) {\n static_ltree[n * 2 + 1]/*.Len*/ = 9;\n n++;\n bl_count[9]++;\n }\n while (n <= 279) {\n static_ltree[n * 2 + 1]/*.Len*/ = 7;\n n++;\n bl_count[7]++;\n }\n while (n <= 287) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n /* Codes 286 and 287 do not exist, but we must include them in the\n * tree construction to get a canonical Huffman tree (longest code\n * all ones)\n */\n gen_codes(static_ltree, L_CODES + 1, bl_count);\n\n /* The static distance tree is trivial: */\n for (n = 0; n < D_CODES; n++) {\n static_dtree[n * 2 + 1]/*.Len*/ = 5;\n static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);\n }\n\n // Now data ready and we can init static trees\n static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);\n static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);\n static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);\n\n //static_init_done = true;\n}\n\n\n/* ===========================================================================\n * Initialize a new block.\n */\nfunction init_block(s) {\n var n; /* iterates over tree elements */\n\n /* Initialize the trees. */\n for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }\n\n s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;\n s.opt_len = s.static_len = 0;\n s.last_lit = s.matches = 0;\n}\n\n\n/* ===========================================================================\n * Flush the bit buffer and align the output on a byte boundary\n */\nfunction bi_windup(s)\n{\n if (s.bi_valid > 8) {\n put_short(s, s.bi_buf);\n } else if (s.bi_valid > 0) {\n //put_byte(s, (Byte)s->bi_buf);\n s.pending_buf[s.pending++] = s.bi_buf;\n }\n s.bi_buf = 0;\n s.bi_valid = 0;\n}\n\n/* ===========================================================================\n * Copy a stored block, storing first the length and its\n * one's complement if requested.\n */\nfunction copy_block(s, buf, len, header)\n//DeflateState *s;\n//charf *buf; /* the input data */\n//unsigned len; /* its length */\n//int header; /* true if block header must be written */\n{\n bi_windup(s); /* align on byte boundary */\n\n if (header) {\n put_short(s, len);\n put_short(s, ~len);\n }\n// while (len--) {\n// put_byte(s, *buf++);\n// }\n utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);\n s.pending += len;\n}\n\n/* ===========================================================================\n * Compares to subtrees, using the tree depth as tie breaker when\n * the subtrees have equal frequency. This minimizes the worst case length.\n */\nfunction smaller(tree, n, m, depth) {\n var _n2 = n * 2;\n var _m2 = m * 2;\n return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||\n (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));\n}\n\n/* ===========================================================================\n * Restore the heap property by moving down the tree starting at node k,\n * exchanging a node with the smallest of its two sons if necessary, stopping\n * when the heap property is re-established (each father smaller than its\n * two sons).\n */\nfunction pqdownheap(s, tree, k)\n// deflate_state *s;\n// ct_data *tree; /* the tree to restore */\n// int k; /* node to move down */\n{\n var v = s.heap[k];\n var j = k << 1; /* left son of k */\n while (j <= s.heap_len) {\n /* Set j to the smallest of the two sons: */\n if (j < s.heap_len &&\n smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {\n j++;\n }\n /* Exit if v is smaller than both sons */\n if (smaller(tree, v, s.heap[j], s.depth)) { break; }\n\n /* Exchange v with the smallest son */\n s.heap[k] = s.heap[j];\n k = j;\n\n /* And continue down the tree, setting j to the left son of k */\n j <<= 1;\n }\n s.heap[k] = v;\n}\n\n\n// inlined manually\n// var SMALLEST = 1;\n\n/* ===========================================================================\n * Send the block data compressed using the given Huffman trees\n */\nfunction compress_block(s, ltree, dtree)\n// deflate_state *s;\n// const ct_data *ltree; /* literal tree */\n// const ct_data *dtree; /* distance tree */\n{\n var dist; /* distance of matched string */\n var lc; /* match length or unmatched char (if dist == 0) */\n var lx = 0; /* running index in l_buf */\n var code; /* the code to send */\n var extra; /* number of extra bits to send */\n\n if (s.last_lit !== 0) {\n do {\n dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);\n lc = s.pending_buf[s.l_buf + lx];\n lx++;\n\n if (dist === 0) {\n send_code(s, lc, ltree); /* send a literal byte */\n //Tracecv(isgraph(lc), (stderr,\" '%c' \", lc));\n } else {\n /* Here, lc is the match length - MIN_MATCH */\n code = _length_code[lc];\n send_code(s, code + LITERALS + 1, ltree); /* send the length code */\n extra = extra_lbits[code];\n if (extra !== 0) {\n lc -= base_length[code];\n send_bits(s, lc, extra); /* send the extra length bits */\n }\n dist--; /* dist is now the match distance - 1 */\n code = d_code(dist);\n //Assert (code < D_CODES, \"bad d_code\");\n\n send_code(s, code, dtree); /* send the distance code */\n extra = extra_dbits[code];\n if (extra !== 0) {\n dist -= base_dist[code];\n send_bits(s, dist, extra); /* send the extra distance bits */\n }\n } /* literal or match pair ? */\n\n /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */\n //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,\n // \"pendingBuf overflow\");\n\n } while (lx < s.last_lit);\n }\n\n send_code(s, END_BLOCK, ltree);\n}\n\n\n/* ===========================================================================\n * Construct one Huffman tree and assigns the code bit strings and lengths.\n * Update the total bit length for the current block.\n * IN assertion: the field freq is set for all tree elements.\n * OUT assertions: the fields len and code are set to the optimal bit length\n * and corresponding code. The length opt_len is updated; static_len is\n * also updated if stree is not null. The field max_code is set.\n */\nfunction build_tree(s, desc)\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n{\n var tree = desc.dyn_tree;\n var stree = desc.stat_desc.static_tree;\n var has_stree = desc.stat_desc.has_stree;\n var elems = desc.stat_desc.elems;\n var n, m; /* iterate over heap elements */\n var max_code = -1; /* largest code with non zero frequency */\n var node; /* new node being created */\n\n /* Construct the initial heap, with least frequent element in\n * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].\n * heap[0] is not used.\n */\n s.heap_len = 0;\n s.heap_max = HEAP_SIZE;\n\n for (n = 0; n < elems; n++) {\n if (tree[n * 2]/*.Freq*/ !== 0) {\n s.heap[++s.heap_len] = max_code = n;\n s.depth[n] = 0;\n\n } else {\n tree[n * 2 + 1]/*.Len*/ = 0;\n }\n }\n\n /* The pkzip format requires that at least one distance code exists,\n * and that at least one bit should be sent even if there is only one\n * possible code. So to avoid special checks later on we force at least\n * two codes of non zero frequency.\n */\n while (s.heap_len < 2) {\n node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);\n tree[node * 2]/*.Freq*/ = 1;\n s.depth[node] = 0;\n s.opt_len--;\n\n if (has_stree) {\n s.static_len -= stree[node * 2 + 1]/*.Len*/;\n }\n /* node is 0 or 1 so it does not have extra bits */\n }\n desc.max_code = max_code;\n\n /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,\n * establish sub-heaps of increasing lengths:\n */\n for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }\n\n /* Construct the Huffman tree by repeatedly combining the least two\n * frequent nodes.\n */\n node = elems; /* next internal node of the tree */\n do {\n //pqremove(s, tree, n); /* n = node of least frequency */\n /*** pqremove ***/\n n = s.heap[1/*SMALLEST*/];\n s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];\n pqdownheap(s, tree, 1/*SMALLEST*/);\n /***/\n\n m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */\n\n s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */\n s.heap[--s.heap_max] = m;\n\n /* Create a new node father of n and m */\n tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;\n s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;\n tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;\n\n /* and insert the new node in the heap */\n s.heap[1/*SMALLEST*/] = node++;\n pqdownheap(s, tree, 1/*SMALLEST*/);\n\n } while (s.heap_len >= 2);\n\n s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];\n\n /* At this point, the fields freq and dad are set. We can now\n * generate the bit lengths.\n */\n gen_bitlen(s, desc);\n\n /* The field len is now set, we can generate the bit codes */\n gen_codes(tree, max_code, s.bl_count);\n}\n\n\n/* ===========================================================================\n * Scan a literal or distance tree to determine the frequencies of the codes\n * in the bit length tree.\n */\nfunction scan_tree(s, tree, max_code)\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n{\n var n; /* iterates over all tree elements */\n var prevlen = -1; /* last emitted length */\n var curlen; /* length of current code */\n\n var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n var count = 0; /* repeat count of the current code */\n var max_count = 7; /* max repeat count */\n var min_count = 4; /* min repeat count */\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n s.bl_tree[curlen * 2]/*.Freq*/ += count;\n\n } else if (curlen !== 0) {\n\n if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }\n s.bl_tree[REP_3_6 * 2]/*.Freq*/++;\n\n } else if (count <= 10) {\n s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;\n\n } else {\n s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;\n }\n\n count = 0;\n prevlen = curlen;\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n}\n\n\n/* ===========================================================================\n * Send a literal or distance tree in compressed form, using the codes in\n * bl_tree.\n */\nfunction send_tree(s, tree, max_code)\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n{\n var n; /* iterates over all tree elements */\n var prevlen = -1; /* last emitted length */\n var curlen; /* length of current code */\n\n var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n var count = 0; /* repeat count of the current code */\n var max_count = 7; /* max repeat count */\n var min_count = 4; /* min repeat count */\n\n /* tree[max_code+1].Len = -1; */ /* guard already set */\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);\n\n } else if (curlen !== 0) {\n if (curlen !== prevlen) {\n send_code(s, curlen, s.bl_tree);\n count--;\n }\n //Assert(count >= 3 && count <= 6, \" 3_6?\");\n send_code(s, REP_3_6, s.bl_tree);\n send_bits(s, count - 3, 2);\n\n } else if (count <= 10) {\n send_code(s, REPZ_3_10, s.bl_tree);\n send_bits(s, count - 3, 3);\n\n } else {\n send_code(s, REPZ_11_138, s.bl_tree);\n send_bits(s, count - 11, 7);\n }\n\n count = 0;\n prevlen = curlen;\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n}\n\n\n/* ===========================================================================\n * Construct the Huffman tree for the bit lengths and return the index in\n * bl_order of the last bit length code to send.\n */\nfunction build_bl_tree(s) {\n var max_blindex; /* index of last bit length code of non zero freq */\n\n /* Determine the bit length frequencies for literal and distance trees */\n scan_tree(s, s.dyn_ltree, s.l_desc.max_code);\n scan_tree(s, s.dyn_dtree, s.d_desc.max_code);\n\n /* Build the bit length tree: */\n build_tree(s, s.bl_desc);\n /* opt_len now includes the length of the tree representations, except\n * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.\n */\n\n /* Determine the number of bit length codes to send. The pkzip format\n * requires that at least 4 bit length codes be sent. (appnote.txt says\n * 3 but the actual value used is 4.)\n */\n for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {\n if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {\n break;\n }\n }\n /* Update opt_len to include the bit length tree and counts */\n s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;\n //Tracev((stderr, \"\\ndyn trees: dyn %ld, stat %ld\",\n // s->opt_len, s->static_len));\n\n return max_blindex;\n}\n\n\n/* ===========================================================================\n * Send the header for a block using dynamic Huffman trees: the counts, the\n * lengths of the bit length codes, the literal tree and the distance tree.\n * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.\n */\nfunction send_all_trees(s, lcodes, dcodes, blcodes)\n// deflate_state *s;\n// int lcodes, dcodes, blcodes; /* number of codes for each tree */\n{\n var rank; /* index in bl_order */\n\n //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, \"not enough codes\");\n //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,\n // \"too many codes\");\n //Tracev((stderr, \"\\nbl counts: \"));\n send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */\n send_bits(s, dcodes - 1, 5);\n send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */\n for (rank = 0; rank < blcodes; rank++) {\n //Tracev((stderr, \"\\nbl code %2d \", bl_order[rank]));\n send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);\n }\n //Tracev((stderr, \"\\nbl tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */\n //Tracev((stderr, \"\\nlit tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */\n //Tracev((stderr, \"\\ndist tree: sent %ld\", s->bits_sent));\n}\n\n\n/* ===========================================================================\n * Check if the data type is TEXT or BINARY, using the following algorithm:\n * - TEXT if the two conditions below are satisfied:\n * a) There are no non-portable control characters belonging to the\n * \"black list\" (0..6, 14..25, 28..31).\n * b) There is at least one printable character belonging to the\n * \"white list\" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).\n * - BINARY otherwise.\n * - The following partially-portable control characters form a\n * \"gray list\" that is ignored in this detection algorithm:\n * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).\n * IN assertion: the fields Freq of dyn_ltree are set.\n */\nfunction detect_data_type(s) {\n /* black_mask is the bit mask of black-listed bytes\n * set bits 0..6, 14..25, and 28..31\n * 0xf3ffc07f = binary 11110011111111111100000001111111\n */\n var black_mask = 0xf3ffc07f;\n var n;\n\n /* Check for non-textual (\"black-listed\") bytes. */\n for (n = 0; n <= 31; n++, black_mask >>>= 1) {\n if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {\n return Z_BINARY;\n }\n }\n\n /* Check for textual (\"white-listed\") bytes. */\n if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||\n s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n for (n = 32; n < LITERALS; n++) {\n if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n }\n\n /* There are no \"black-listed\" or \"white-listed\" bytes:\n * this stream either is empty or has tolerated (\"gray-listed\") bytes only.\n */\n return Z_BINARY;\n}\n\n\nvar static_init_done = false;\n\n/* ===========================================================================\n * Initialize the tree data structures for a new zlib stream.\n */\nfunction _tr_init(s)\n{\n\n if (!static_init_done) {\n tr_static_init();\n static_init_done = true;\n }\n\n s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);\n s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);\n s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);\n\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n /* Initialize the first block of the first file: */\n init_block(s);\n}\n\n\n/* ===========================================================================\n * Send a stored block\n */\nfunction _tr_stored_block(s, buf, stored_len, last)\n//DeflateState *s;\n//charf *buf; /* input block */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n{\n send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */\n copy_block(s, buf, stored_len, true); /* with header */\n}\n\n\n/* ===========================================================================\n * Send one empty static block to give enough lookahead for inflate.\n * This takes 10 bits, of which 7 may remain in the bit buffer.\n */\nfunction _tr_align(s) {\n send_bits(s, STATIC_TREES << 1, 3);\n send_code(s, END_BLOCK, static_ltree);\n bi_flush(s);\n}\n\n\n/* ===========================================================================\n * Determine the best encoding for the current block: dynamic trees, static\n * trees or store, and output the encoded block to the zip file.\n */\nfunction _tr_flush_block(s, buf, stored_len, last)\n//DeflateState *s;\n//charf *buf; /* input block, or NULL if too old */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n{\n var opt_lenb, static_lenb; /* opt_len and static_len in bytes */\n var max_blindex = 0; /* index of last bit length code of non zero freq */\n\n /* Build the Huffman trees unless a stored block is forced */\n if (s.level > 0) {\n\n /* Check if the file is binary or text */\n if (s.strm.data_type === Z_UNKNOWN) {\n s.strm.data_type = detect_data_type(s);\n }\n\n /* Construct the literal and distance trees */\n build_tree(s, s.l_desc);\n // Tracev((stderr, \"\\nlit data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n\n build_tree(s, s.d_desc);\n // Tracev((stderr, \"\\ndist data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n /* At this point, opt_len and static_len are the total bit lengths of\n * the compressed block data, excluding the tree representations.\n */\n\n /* Build the bit length tree for the above two trees, and get the index\n * in bl_order of the last bit length code to send.\n */\n max_blindex = build_bl_tree(s);\n\n /* Determine the best encoding. Compute the block lengths in bytes. */\n opt_lenb = (s.opt_len + 3 + 7) >>> 3;\n static_lenb = (s.static_len + 3 + 7) >>> 3;\n\n // Tracev((stderr, \"\\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u \",\n // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,\n // s->last_lit));\n\n if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }\n\n } else {\n // Assert(buf != (char*)0, \"lost buf\");\n opt_lenb = static_lenb = stored_len + 5; /* force a stored block */\n }\n\n if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {\n /* 4: two words for the lengths */\n\n /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.\n * Otherwise we can't have processed more than WSIZE input bytes since\n * the last block flush, because compression would have been\n * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to\n * transform a block into a stored block.\n */\n _tr_stored_block(s, buf, stored_len, last);\n\n } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {\n\n send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);\n compress_block(s, static_ltree, static_dtree);\n\n } else {\n send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);\n send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);\n compress_block(s, s.dyn_ltree, s.dyn_dtree);\n }\n // Assert (s->compressed_len == s->bits_sent, \"bad compressed size\");\n /* The above check is made mod 2^32, for files larger than 512 MB\n * and uLong implemented on 32 bits.\n */\n init_block(s);\n\n if (last) {\n bi_windup(s);\n }\n // Tracev((stderr,\"\\ncomprlen %lu(%lu) \", s->compressed_len>>3,\n // s->compressed_len-7*last));\n}\n\n/* ===========================================================================\n * Save the match info and tally the frequency counts. Return true if\n * the current block must be flushed.\n */\nfunction _tr_tally(s, dist, lc)\n// deflate_state *s;\n// unsigned dist; /* distance of matched string */\n// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */\n{\n //var out_length, in_length, dcode;\n\n s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;\n s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;\n\n s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;\n s.last_lit++;\n\n if (dist === 0) {\n /* lc is the unmatched char */\n s.dyn_ltree[lc * 2]/*.Freq*/++;\n } else {\n s.matches++;\n /* Here, lc is the match length - MIN_MATCH */\n dist--; /* dist = match distance - 1 */\n //Assert((ush)dist < (ush)MAX_DIST(s) &&\n // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&\n // (ush)d_code(dist) < (ush)D_CODES, \"_tr_tally: bad match\");\n\n s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;\n s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n\n//#ifdef TRUNCATE_BLOCK\n// /* Try to guess if it is profitable to stop the current block here */\n// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {\n// /* Compute an upper bound for the compressed length */\n// out_length = s.last_lit*8;\n// in_length = s.strstart - s.block_start;\n//\n// for (dcode = 0; dcode < D_CODES; dcode++) {\n// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);\n// }\n// out_length >>>= 3;\n// //Tracev((stderr,\"\\nlast_lit %u, in %ld, out ~%ld(%ld%%) \",\n// // s->last_lit, in_length, out_length,\n// // 100L - out_length*100L/in_length));\n// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {\n// return true;\n// }\n// }\n//#endif\n\n return (s.last_lit === s.lit_bufsize - 1);\n /* We avoid equality with lit_bufsize because of wraparound at 64K\n * on 16 bit machines and because stored blocks are restricted to\n * 64K-1 bytes.\n */\n}\n\nexports._tr_init = _tr_init;\nexports._tr_stored_block = _tr_stored_block;\nexports._tr_flush_block = _tr_flush_block;\nexports._tr_tally = _tr_tally;\nexports._tr_align = _tr_align;\n", "'use strict';\n\n// Note: adler32 takes 12% for level 0 and 2% for level 6.\n// It isn't worth it to make additional optimizations as in original.\n// Small size is preferable.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction adler32(adler, buf, len, pos) {\n var s1 = (adler & 0xffff) |0,\n s2 = ((adler >>> 16) & 0xffff) |0,\n n = 0;\n\n while (len !== 0) {\n // Set limit ~ twice less than 5552, to keep\n // s2 in 31-bits, because we force signed ints.\n // in other case %= will fail.\n n = len > 2000 ? 2000 : len;\n len -= n;\n\n do {\n s1 = (s1 + buf[pos++]) |0;\n s2 = (s2 + s1) |0;\n } while (--n);\n\n s1 %= 65521;\n s2 %= 65521;\n }\n\n return (s1 | (s2 << 16)) |0;\n}\n\n\nmodule.exports = adler32;\n", "'use strict';\n\n// Note: we can't get significant speed boost here.\n// So write code to minimize size - no pregenerated tables\n// and array tools dependencies.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// Use ordinary array, since untyped makes no boost here\nfunction makeTable() {\n var c, table = [];\n\n for (var n = 0; n < 256; n++) {\n c = n;\n for (var k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n table[n] = c;\n }\n\n return table;\n}\n\n// Create table on load. Just 255 signed longs. Not a problem.\nvar crcTable = makeTable();\n\n\nfunction crc32(crc, buf, len, pos) {\n var t = crcTable,\n end = pos + len;\n\n crc ^= -1;\n\n for (var i = pos; i < end; i++) {\n crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];\n }\n\n return (crc ^ (-1)); // >>> 0;\n}\n\n\nmodule.exports = crc32;\n", "'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nmodule.exports = {\n 2: 'need dictionary', /* Z_NEED_DICT 2 */\n 1: 'stream end', /* Z_STREAM_END 1 */\n 0: '', /* Z_OK 0 */\n '-1': 'file error', /* Z_ERRNO (-1) */\n '-2': 'stream error', /* Z_STREAM_ERROR (-2) */\n '-3': 'data error', /* Z_DATA_ERROR (-3) */\n '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */\n '-5': 'buffer error', /* Z_BUF_ERROR (-5) */\n '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */\n};\n", "'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar utils = require('../utils/common');\nvar trees = require('./trees');\nvar adler32 = require('./adler32');\nvar crc32 = require('./crc32');\nvar msg = require('./messages');\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n/* Allowed flush values; see deflate() and inflate() below for details */\nvar Z_NO_FLUSH = 0;\nvar Z_PARTIAL_FLUSH = 1;\n//var Z_SYNC_FLUSH = 2;\nvar Z_FULL_FLUSH = 3;\nvar Z_FINISH = 4;\nvar Z_BLOCK = 5;\n//var Z_TREES = 6;\n\n\n/* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\nvar Z_OK = 0;\nvar Z_STREAM_END = 1;\n//var Z_NEED_DICT = 2;\n//var Z_ERRNO = -1;\nvar Z_STREAM_ERROR = -2;\nvar Z_DATA_ERROR = -3;\n//var Z_MEM_ERROR = -4;\nvar Z_BUF_ERROR = -5;\n//var Z_VERSION_ERROR = -6;\n\n\n/* compression levels */\n//var Z_NO_COMPRESSION = 0;\n//var Z_BEST_SPEED = 1;\n//var Z_BEST_COMPRESSION = 9;\nvar Z_DEFAULT_COMPRESSION = -1;\n\n\nvar Z_FILTERED = 1;\nvar Z_HUFFMAN_ONLY = 2;\nvar Z_RLE = 3;\nvar Z_FIXED = 4;\nvar Z_DEFAULT_STRATEGY = 0;\n\n/* Possible values of the data_type field (though see inflate()) */\n//var Z_BINARY = 0;\n//var Z_TEXT = 1;\n//var Z_ASCII = 1; // = Z_TEXT\nvar Z_UNKNOWN = 2;\n\n\n/* The deflate compression method */\nvar Z_DEFLATED = 8;\n\n/*============================================================================*/\n\n\nvar MAX_MEM_LEVEL = 9;\n/* Maximum value for memLevel in deflateInit2 */\nvar MAX_WBITS = 15;\n/* 32K LZ77 window */\nvar DEF_MEM_LEVEL = 8;\n\n\nvar LENGTH_CODES = 29;\n/* number of length codes, not counting the special END_BLOCK code */\nvar LITERALS = 256;\n/* number of literal bytes 0..255 */\nvar L_CODES = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\nvar D_CODES = 30;\n/* number of distance codes */\nvar BL_CODES = 19;\n/* number of codes used to transfer the bit lengths */\nvar HEAP_SIZE = 2 * L_CODES + 1;\n/* maximum heap size */\nvar MAX_BITS = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nvar MIN_MATCH = 3;\nvar MAX_MATCH = 258;\nvar MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);\n\nvar PRESET_DICT = 0x20;\n\nvar INIT_STATE = 42;\nvar EXTRA_STATE = 69;\nvar NAME_STATE = 73;\nvar COMMENT_STATE = 91;\nvar HCRC_STATE = 103;\nvar BUSY_STATE = 113;\nvar FINISH_STATE = 666;\n\nvar BS_NEED_MORE = 1; /* block not completed, need more input or more output */\nvar BS_BLOCK_DONE = 2; /* block flush performed */\nvar BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */\nvar BS_FINISH_DONE = 4; /* finish done, accept no more input or output */\n\nvar OS_CODE = 0x03; // Unix :) . Don't detect, use this default.\n\nfunction err(strm, errorCode) {\n strm.msg = msg[errorCode];\n return errorCode;\n}\n\nfunction rank(f) {\n return ((f) << 1) - ((f) > 4 ? 9 : 0);\n}\n\nfunction zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }\n\n\n/* =========================================================================\n * Flush as much pending output as possible. All deflate() output goes\n * through this function so some applications may wish to modify it\n * to avoid allocating a large strm->output buffer and copying into it.\n * (See also read_buf()).\n */\nfunction flush_pending(strm) {\n var s = strm.state;\n\n //_tr_flush_bits(s);\n var len = s.pending;\n if (len > strm.avail_out) {\n len = strm.avail_out;\n }\n if (len === 0) { return; }\n\n utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);\n strm.next_out += len;\n s.pending_out += len;\n strm.total_out += len;\n strm.avail_out -= len;\n s.pending -= len;\n if (s.pending === 0) {\n s.pending_out = 0;\n }\n}\n\n\nfunction flush_block_only(s, last) {\n trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);\n s.block_start = s.strstart;\n flush_pending(s.strm);\n}\n\n\nfunction put_byte(s, b) {\n s.pending_buf[s.pending++] = b;\n}\n\n\n/* =========================================================================\n * Put a short in the pending buffer. The 16-bit value is put in MSB order.\n * IN assertion: the stream state is correct and there is enough room in\n * pending_buf.\n */\nfunction putShortMSB(s, b) {\n// put_byte(s, (Byte)(b >> 8));\n// put_byte(s, (Byte)(b & 0xff));\n s.pending_buf[s.pending++] = (b >>> 8) & 0xff;\n s.pending_buf[s.pending++] = b & 0xff;\n}\n\n\n/* ===========================================================================\n * Read a new buffer from the current input stream, update the adler32\n * and total number of bytes read. All deflate() input goes through\n * this function so some applications may wish to modify it to avoid\n * allocating a large strm->input buffer and copying from it.\n * (See also flush_pending()).\n */\nfunction read_buf(strm, buf, start, size) {\n var len = strm.avail_in;\n\n if (len > size) { len = size; }\n if (len === 0) { return 0; }\n\n strm.avail_in -= len;\n\n // zmemcpy(buf, strm->next_in, len);\n utils.arraySet(buf, strm.input, strm.next_in, len, start);\n if (strm.state.wrap === 1) {\n strm.adler = adler32(strm.adler, buf, len, start);\n }\n\n else if (strm.state.wrap === 2) {\n strm.adler = crc32(strm.adler, buf, len, start);\n }\n\n strm.next_in += len;\n strm.total_in += len;\n\n return len;\n}\n\n\n/* ===========================================================================\n * Set match_start to the longest match starting at the given string and\n * return its length. Matches shorter or equal to prev_length are discarded,\n * in which case the result is equal to prev_length and match_start is\n * garbage.\n * IN assertions: cur_match is the head of the hash chain for the current\n * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1\n * OUT assertion: the match length is not greater than s->lookahead.\n */\nfunction longest_match(s, cur_match) {\n var chain_length = s.max_chain_length; /* max hash chain length */\n var scan = s.strstart; /* current string */\n var match; /* matched string */\n var len; /* length of current match */\n var best_len = s.prev_length; /* best match length so far */\n var nice_match = s.nice_match; /* stop if match long enough */\n var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n var _win = s.window; // shortcut\n\n var wmask = s.w_mask;\n var prev = s.prev;\n\n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n\n var strend = s.strstart + MAX_MATCH;\n var scan_end1 = _win[scan + best_len - 1];\n var scan_end = _win[scan + best_len];\n\n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n /* Do not waste too much time if we already have a good match: */\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n\n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n\n if (_win[match + best_len] !== scan_end ||\n _win[match + best_len - 1] !== scan_end1 ||\n _win[match] !== _win[scan] ||\n _win[++match] !== _win[scan + 1]) {\n continue;\n }\n\n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n scan += 2;\n match++;\n // Assert(*scan == *match, \"match[2]?\");\n\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n scan < strend);\n\n // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n len = MAX_MATCH - (strend - scan);\n scan = strend - MAX_MATCH;\n\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n if (len >= nice_match) {\n break;\n }\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n if (best_len <= s.lookahead) {\n return best_len;\n }\n return s.lookahead;\n}\n\n\n/* ===========================================================================\n * Fill the window when the lookahead becomes insufficient.\n * Updates strstart and lookahead.\n *\n * IN assertion: lookahead < MIN_LOOKAHEAD\n * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD\n * At least one byte has been read, or avail_in == 0; reads are\n * performed for at least two bytes (required for the zip translate_eol\n * option -- not supported here).\n */\nfunction fill_window(s) {\n var _w_size = s.w_size;\n var p, n, m, more, str;\n\n //Assert(s->lookahead < MIN_LOOKAHEAD, \"already enough lookahead\");\n\n do {\n more = s.window_size - s.lookahead - s.strstart;\n\n // JS ints have 32 bit, block below not needed\n /* Deal with !@#$% 64K limit: */\n //if (sizeof(int) <= 2) {\n // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {\n // more = wsize;\n //\n // } else if (more == (unsigned)(-1)) {\n // /* Very unlikely, but possible on 16 bit machine if\n // * strstart == 0 && lookahead == 1 (input done a byte at time)\n // */\n // more--;\n // }\n //}\n\n\n /* If the window is almost full and there is insufficient lookahead,\n * move the upper half to the lower one to make room in the upper half.\n */\n if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {\n\n utils.arraySet(s.window, s.window, _w_size, _w_size, 0);\n s.match_start -= _w_size;\n s.strstart -= _w_size;\n /* we now have strstart >= MAX_DIST */\n s.block_start -= _w_size;\n\n /* Slide the hash table (could be avoided with 32 bit values\n at the expense of memory usage). We slide even when level == 0\n to keep the hash table consistent if we switch back to level > 0\n later. (Using level 0 permanently is not an optimal usage of\n zlib, so we don't care about this pathological case.)\n */\n\n n = s.hash_size;\n p = n;\n do {\n m = s.head[--p];\n s.head[p] = (m >= _w_size ? m - _w_size : 0);\n } while (--n);\n\n n = _w_size;\n p = n;\n do {\n m = s.prev[--p];\n s.prev[p] = (m >= _w_size ? m - _w_size : 0);\n /* If n is not on any hash chain, prev[n] is garbage but\n * its value will never be used.\n */\n } while (--n);\n\n more += _w_size;\n }\n if (s.strm.avail_in === 0) {\n break;\n }\n\n /* If there was no sliding:\n * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&\n * more == window_size - lookahead - strstart\n * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)\n * => more >= window_size - 2*WSIZE + 2\n * In the BIG_MEM or MMAP case (not yet supported),\n * window_size == input_size + MIN_LOOKAHEAD &&\n * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.\n * Otherwise, window_size == 2*WSIZE so more >= 2.\n * If there was sliding, more >= WSIZE. So in all cases, more >= 2.\n */\n //Assert(more >= 2, \"more < 2\");\n n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);\n s.lookahead += n;\n\n /* Initialize the hash value now that we have some input: */\n if (s.lookahead + s.insert >= MIN_MATCH) {\n str = s.strstart - s.insert;\n s.ins_h = s.window[str];\n\n /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;\n//#if MIN_MATCH != 3\n// Call update_hash() MIN_MATCH-3 more times\n//#endif\n while (s.insert) {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = str;\n str++;\n s.insert--;\n if (s.lookahead + s.insert < MIN_MATCH) {\n break;\n }\n }\n }\n /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,\n * but this is not important since only literal bytes will be emitted.\n */\n\n } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);\n\n /* If the WIN_INIT bytes after the end of the current data have never been\n * written, then zero those bytes in order to avoid memory check reports of\n * the use of uninitialized (or uninitialised as Julian writes) bytes by\n * the longest match routines. Update the high water mark for the next\n * time through here. WIN_INIT is set to MAX_MATCH since the longest match\n * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.\n */\n// if (s.high_water < s.window_size) {\n// var curr = s.strstart + s.lookahead;\n// var init = 0;\n//\n// if (s.high_water < curr) {\n// /* Previous high water mark below current data -- zero WIN_INIT\n// * bytes or up to end of window, whichever is less.\n// */\n// init = s.window_size - curr;\n// if (init > WIN_INIT)\n// init = WIN_INIT;\n// zmemzero(s->window + curr, (unsigned)init);\n// s->high_water = curr + init;\n// }\n// else if (s->high_water < (ulg)curr + WIN_INIT) {\n// /* High water mark at or above current data, but below current data\n// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up\n// * to end of window, whichever is less.\n// */\n// init = (ulg)curr + WIN_INIT - s->high_water;\n// if (init > s->window_size - s->high_water)\n// init = s->window_size - s->high_water;\n// zmemzero(s->window + s->high_water, (unsigned)init);\n// s->high_water += init;\n// }\n// }\n//\n// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,\n// \"not enough room for search\");\n}\n\n/* ===========================================================================\n * Copy without compression as much as possible from the input stream, return\n * the current block state.\n * This function does not insert new strings in the dictionary since\n * uncompressible data is probably not useful. This function is used\n * only for the level=0 compression option.\n * NOTE: this function should be optimized to avoid extra copying from\n * window to pending_buf.\n */\nfunction deflate_stored(s, flush) {\n /* Stored blocks are limited to 0xffff bytes, pending_buf is limited\n * to pending_buf_size, and each stored block has a 5 byte header:\n */\n var max_block_size = 0xffff;\n\n if (max_block_size > s.pending_buf_size - 5) {\n max_block_size = s.pending_buf_size - 5;\n }\n\n /* Copy as much as possible from input to output: */\n for (;;) {\n /* Fill the window as much as possible: */\n if (s.lookahead <= 1) {\n\n //Assert(s->strstart < s->w_size+MAX_DIST(s) ||\n // s->block_start >= (long)s->w_size, \"slide too late\");\n// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||\n// s.block_start >= s.w_size)) {\n// throw new Error(\"slide too late\");\n// }\n\n fill_window(s);\n if (s.lookahead === 0 && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n\n if (s.lookahead === 0) {\n break;\n }\n /* flush the current block */\n }\n //Assert(s->block_start >= 0L, \"block gone\");\n// if (s.block_start < 0) throw new Error(\"block gone\");\n\n s.strstart += s.lookahead;\n s.lookahead = 0;\n\n /* Emit a stored block if pending_buf will be full: */\n var max_start = s.block_start + max_block_size;\n\n if (s.strstart === 0 || s.strstart >= max_start) {\n /* strstart == 0 is possible when wraparound on 16-bit machine */\n s.lookahead = s.strstart - max_start;\n s.strstart = max_start;\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n\n\n }\n /* Flush if we may have to slide, otherwise block_start may become\n * negative and the data will be gone:\n */\n if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n\n s.insert = 0;\n\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n\n if (s.strstart > s.block_start) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_NEED_MORE;\n}\n\n/* ===========================================================================\n * Compress as much as possible from the input stream, return the current\n * block state.\n * This function does not perform lazy evaluation of matches and inserts\n * new strings in the dictionary only for unmatched strings or for short\n * matches. It is used only for the fast compression options.\n */\nfunction deflate_fast(s, flush) {\n var hash_head; /* head of the hash chain */\n var bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) {\n break; /* flush the current block */\n }\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n * At this point we have always match_length < MIN_MATCH\n */\n if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n }\n if (s.match_length >= MIN_MATCH) {\n // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only\n\n /*** _tr_tally_dist(s, s.strstart - s.match_start,\n s.match_length - MIN_MATCH, bflush); ***/\n bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n\n /* Insert new strings in the hash table only if the match length\n * is not too large. This saves time but degrades compression.\n */\n if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {\n s.match_length--; /* string at strstart already in table */\n do {\n s.strstart++;\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n /* strstart never exceeds WSIZE-MAX_MATCH, so there are\n * always MIN_MATCH bytes ahead.\n */\n } while (--s.match_length !== 0);\n s.strstart++;\n } else\n {\n s.strstart += s.match_length;\n s.match_length = 0;\n s.ins_h = s.window[s.strstart];\n /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;\n\n//#if MIN_MATCH != 3\n// Call UPDATE_HASH() MIN_MATCH-3 more times\n//#endif\n /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not\n * matter since it will be recomputed at next deflate call.\n */\n }\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s.window[s.strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* ===========================================================================\n * Same as above, but achieves better compression. We use a lazy\n * evaluation for matches: a match is finally adopted only if there is\n * no better match at the next window position.\n */\nfunction deflate_slow(s, flush) {\n var hash_head; /* head of hash chain */\n var bflush; /* set if current block must be flushed */\n\n var max_insert;\n\n /* Process the input block. */\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n */\n s.prev_length = s.match_length;\n s.prev_match = s.match_start;\n s.match_length = MIN_MATCH - 1;\n\n if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&\n s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n\n if (s.match_length <= 5 &&\n (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {\n\n /* If prev_match is also MIN_MATCH, match_start is garbage\n * but we will ignore the current match anyway.\n */\n s.match_length = MIN_MATCH - 1;\n }\n }\n /* If there was a match at the previous step and the current\n * match is not better, output the previous match:\n */\n if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {\n max_insert = s.strstart + s.lookahead - MIN_MATCH;\n /* Do not insert strings in hash table beyond this. */\n\n //check_match(s, s.strstart-1, s.prev_match, s.prev_length);\n\n /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,\n s.prev_length - MIN_MATCH, bflush);***/\n bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);\n /* Insert in hash table all strings up to the end of the match.\n * strstart-1 and strstart are already inserted. If there is not\n * enough lookahead, the last two strings are not inserted in\n * the hash table.\n */\n s.lookahead -= s.prev_length - 1;\n s.prev_length -= 2;\n do {\n if (++s.strstart <= max_insert) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n } while (--s.prev_length !== 0);\n s.match_available = 0;\n s.match_length = MIN_MATCH - 1;\n s.strstart++;\n\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n } else if (s.match_available) {\n /* If there was no match at the previous position, output a\n * single literal. If there was a match but the current match\n * is longer, truncate the previous match to a single literal.\n */\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);\n\n if (bflush) {\n /*** FLUSH_BLOCK_ONLY(s, 0) ***/\n flush_block_only(s, false);\n /***/\n }\n s.strstart++;\n s.lookahead--;\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n } else {\n /* There is no previous match to compare with, wait for\n * the next step to decide.\n */\n s.match_available = 1;\n s.strstart++;\n s.lookahead--;\n }\n }\n //Assert (flush != Z_NO_FLUSH, \"no flush?\");\n if (s.match_available) {\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);\n\n s.match_available = 0;\n }\n s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_BLOCK_DONE;\n}\n\n\n/* ===========================================================================\n * For Z_RLE, simply look for runs of bytes, generate matches only of distance\n * one. Do not maintain a hash table. (It will be regenerated if this run of\n * deflate switches away from Z_RLE.)\n */\nfunction deflate_rle(s, flush) {\n var bflush; /* set if current block must be flushed */\n var prev; /* byte at distance one to match */\n var scan, strend; /* scan goes up to strend for length of run */\n\n var _win = s.window;\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the longest run, plus one for the unrolled loop.\n */\n if (s.lookahead <= MAX_MATCH) {\n fill_window(s);\n if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* See how many times the previous byte repeats */\n s.match_length = 0;\n if (s.lookahead >= MIN_MATCH && s.strstart > 0) {\n scan = s.strstart - 1;\n prev = _win[scan];\n if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {\n strend = s.strstart + MAX_MATCH;\n do {\n /*jshint noempty:false*/\n } while (prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n scan < strend);\n s.match_length = MAX_MATCH - (strend - scan);\n if (s.match_length > s.lookahead) {\n s.match_length = s.lookahead;\n }\n }\n //Assert(scan <= s->window+(uInt)(s->window_size-1), \"wild scan\");\n }\n\n /* Emit match if have run of MIN_MATCH or longer, else emit literal */\n if (s.match_length >= MIN_MATCH) {\n //check_match(s, s.strstart, s.strstart - 1, s.match_length);\n\n /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/\n bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n s.strstart += s.match_length;\n s.match_length = 0;\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* ===========================================================================\n * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.\n * (It will be regenerated if this run of deflate switches away from Huffman.)\n */\nfunction deflate_huff(s, flush) {\n var bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we have a literal to write. */\n if (s.lookahead === 0) {\n fill_window(s);\n if (s.lookahead === 0) {\n if (flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n break; /* flush the current block */\n }\n }\n\n /* Output a literal byte */\n s.match_length = 0;\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n s.lookahead--;\n s.strstart++;\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* Values for max_lazy_match, good_match and max_chain_length, depending on\n * the desired pack level (0..9). The values given below have been tuned to\n * exclude worst case performance for pathological files. Better values may be\n * found for specific files.\n */\nfunction Config(good_length, max_lazy, nice_length, max_chain, func) {\n this.good_length = good_length;\n this.max_lazy = max_lazy;\n this.nice_length = nice_length;\n this.max_chain = max_chain;\n this.func = func;\n}\n\nvar configuration_table;\n\nconfiguration_table = [\n /* good lazy nice chain */\n new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */\n new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */\n new Config(4, 5, 16, 8, deflate_fast), /* 2 */\n new Config(4, 6, 32, 32, deflate_fast), /* 3 */\n\n new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */\n new Config(8, 16, 32, 32, deflate_slow), /* 5 */\n new Config(8, 16, 128, 128, deflate_slow), /* 6 */\n new Config(8, 32, 128, 256, deflate_slow), /* 7 */\n new Config(32, 128, 258, 1024, deflate_slow), /* 8 */\n new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */\n];\n\n\n/* ===========================================================================\n * Initialize the \"longest match\" routines for a new zlib stream\n */\nfunction lm_init(s) {\n s.window_size = 2 * s.w_size;\n\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n\n /* Set the default configuration parameters:\n */\n s.max_lazy_match = configuration_table[s.level].max_lazy;\n s.good_match = configuration_table[s.level].good_length;\n s.nice_match = configuration_table[s.level].nice_length;\n s.max_chain_length = configuration_table[s.level].max_chain;\n\n s.strstart = 0;\n s.block_start = 0;\n s.lookahead = 0;\n s.insert = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n s.ins_h = 0;\n}\n\n\nfunction DeflateState() {\n this.strm = null; /* pointer back to this zlib stream */\n this.status = 0; /* as the name implies */\n this.pending_buf = null; /* output still pending */\n this.pending_buf_size = 0; /* size of pending_buf */\n this.pending_out = 0; /* next pending byte to output to the stream */\n this.pending = 0; /* nb of bytes in the pending buffer */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.gzhead = null; /* gzip header information to write */\n this.gzindex = 0; /* where in extra, name, or comment */\n this.method = Z_DEFLATED; /* can only be DEFLATED */\n this.last_flush = -1; /* value of flush param for previous deflate call */\n\n this.w_size = 0; /* LZ77 window size (32K by default) */\n this.w_bits = 0; /* log2(w_size) (8..16) */\n this.w_mask = 0; /* w_size - 1 */\n\n this.window = null;\n /* Sliding window. Input bytes are read into the second half of the window,\n * and move to the first half later to keep a dictionary of at least wSize\n * bytes. With this organization, matches are limited to a distance of\n * wSize-MAX_MATCH bytes, but this ensures that IO is always\n * performed with a length multiple of the block size.\n */\n\n this.window_size = 0;\n /* Actual size of window: 2*wSize, except when the user input buffer\n * is directly used as sliding window.\n */\n\n this.prev = null;\n /* Link to older string with same hash index. To limit the size of this\n * array to 64K, this link is maintained only for the last 32K strings.\n * An index in this array is thus a window index modulo 32K.\n */\n\n this.head = null; /* Heads of the hash chains or NIL. */\n\n this.ins_h = 0; /* hash index of string to be inserted */\n this.hash_size = 0; /* number of elements in hash table */\n this.hash_bits = 0; /* log2(hash_size) */\n this.hash_mask = 0; /* hash_size-1 */\n\n this.hash_shift = 0;\n /* Number of bits by which ins_h must be shifted at each input\n * step. It must be such that after MIN_MATCH steps, the oldest\n * byte no longer takes part in the hash key, that is:\n * hash_shift * MIN_MATCH >= hash_bits\n */\n\n this.block_start = 0;\n /* Window position at the beginning of the current output block. Gets\n * negative when the window is moved backwards.\n */\n\n this.match_length = 0; /* length of best match */\n this.prev_match = 0; /* previous match */\n this.match_available = 0; /* set if previous match exists */\n this.strstart = 0; /* start of string to insert */\n this.match_start = 0; /* start of matching string */\n this.lookahead = 0; /* number of valid bytes ahead in window */\n\n this.prev_length = 0;\n /* Length of the best match at previous step. Matches not greater than this\n * are discarded. This is used in the lazy match evaluation.\n */\n\n this.max_chain_length = 0;\n /* To speed up deflation, hash chains are never searched beyond this\n * length. A higher limit improves compression ratio but degrades the\n * speed.\n */\n\n this.max_lazy_match = 0;\n /* Attempt to find a better match only when the current match is strictly\n * smaller than this value. This mechanism is used only for compression\n * levels >= 4.\n */\n // That's alias to max_lazy_match, don't use directly\n //this.max_insert_length = 0;\n /* Insert new strings in the hash table only if the match length is not\n * greater than this length. This saves time but degrades compression.\n * max_insert_length is used only for compression levels <= 3.\n */\n\n this.level = 0; /* compression level (1..9) */\n this.strategy = 0; /* favor or force Huffman coding*/\n\n this.good_match = 0;\n /* Use a faster search when the previous match is longer than this */\n\n this.nice_match = 0; /* Stop searching when current match exceeds this */\n\n /* used by trees.c: */\n\n /* Didn't use ct_data typedef below to suppress compiler warning */\n\n // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */\n // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */\n // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */\n\n // Use flat array of DOUBLE size, with interleaved fata,\n // because JS does not support effective\n this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);\n this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);\n this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);\n zero(this.dyn_ltree);\n zero(this.dyn_dtree);\n zero(this.bl_tree);\n\n this.l_desc = null; /* desc. for literal tree */\n this.d_desc = null; /* desc. for distance tree */\n this.bl_desc = null; /* desc. for bit length tree */\n\n //ush bl_count[MAX_BITS+1];\n this.bl_count = new utils.Buf16(MAX_BITS + 1);\n /* number of codes at each bit length for an optimal tree */\n\n //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */\n this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */\n zero(this.heap);\n\n this.heap_len = 0; /* number of elements in the heap */\n this.heap_max = 0; /* element of largest frequency */\n /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.\n * The same heap array is used to build all trees.\n */\n\n this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];\n zero(this.depth);\n /* Depth of each subtree used as tie breaker for trees of equal frequency\n */\n\n this.l_buf = 0; /* buffer index for literals or lengths */\n\n this.lit_bufsize = 0;\n /* Size of match buffer for literals/lengths. There are 4 reasons for\n * limiting lit_bufsize to 64K:\n * - frequencies can be kept in 16 bit counters\n * - if compression is not successful for the first block, all input\n * data is still in the window so we can still emit a stored block even\n * when input comes from standard input. (This can also be done for\n * all blocks if lit_bufsize is not greater than 32K.)\n * - if compression is not successful for a file smaller than 64K, we can\n * even emit a stored file instead of a stored block (saving 5 bytes).\n * This is applicable only for zip (not gzip or zlib).\n * - creating new Huffman trees less frequently may not provide fast\n * adaptation to changes in the input data statistics. (Take for\n * example a binary file with poorly compressible code followed by\n * a highly compressible string table.) Smaller buffer sizes give\n * fast adaptation but have of course the overhead of transmitting\n * trees more frequently.\n * - I can't count above 4\n */\n\n this.last_lit = 0; /* running index in l_buf */\n\n this.d_buf = 0;\n /* Buffer index for distances. To simplify the code, d_buf and l_buf have\n * the same number of elements. To use different lengths, an extra flag\n * array would be necessary.\n */\n\n this.opt_len = 0; /* bit length of current block with optimal trees */\n this.static_len = 0; /* bit length of current block with static trees */\n this.matches = 0; /* number of string matches in current block */\n this.insert = 0; /* bytes at end of window left to insert */\n\n\n this.bi_buf = 0;\n /* Output buffer. bits are inserted starting at the bottom (least\n * significant bits).\n */\n this.bi_valid = 0;\n /* Number of valid bits in bi_buf. All bits above the last valid bit\n * are always zero.\n */\n\n // Used for window memory init. We safely ignore it for JS. That makes\n // sense only for pointers and memory check tools.\n //this.high_water = 0;\n /* High water mark offset in window for initialized bytes -- bytes above\n * this are set to zero in order to avoid memory check warnings when\n * longest match routines access bytes past the input. This is then\n * updated to the new high water mark.\n */\n}\n\n\nfunction deflateResetKeep(strm) {\n var s;\n\n if (!strm || !strm.state) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n strm.total_in = strm.total_out = 0;\n strm.data_type = Z_UNKNOWN;\n\n s = strm.state;\n s.pending = 0;\n s.pending_out = 0;\n\n if (s.wrap < 0) {\n s.wrap = -s.wrap;\n /* was made negative by deflate(..., Z_FINISH); */\n }\n s.status = (s.wrap ? INIT_STATE : BUSY_STATE);\n strm.adler = (s.wrap === 2) ?\n 0 // crc32(0, Z_NULL, 0)\n :\n 1; // adler32(0, Z_NULL, 0)\n s.last_flush = Z_NO_FLUSH;\n trees._tr_init(s);\n return Z_OK;\n}\n\n\nfunction deflateReset(strm) {\n var ret = deflateResetKeep(strm);\n if (ret === Z_OK) {\n lm_init(strm.state);\n }\n return ret;\n}\n\n\nfunction deflateSetHeader(strm, head) {\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }\n strm.state.gzhead = head;\n return Z_OK;\n}\n\n\nfunction deflateInit2(strm, level, method, windowBits, memLevel, strategy) {\n if (!strm) { // === Z_NULL\n return Z_STREAM_ERROR;\n }\n var wrap = 1;\n\n if (level === Z_DEFAULT_COMPRESSION) {\n level = 6;\n }\n\n if (windowBits < 0) { /* suppress zlib wrapper */\n wrap = 0;\n windowBits = -windowBits;\n }\n\n else if (windowBits > 15) {\n wrap = 2; /* write gzip wrapper instead */\n windowBits -= 16;\n }\n\n\n if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||\n windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||\n strategy < 0 || strategy > Z_FIXED) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n\n if (windowBits === 8) {\n windowBits = 9;\n }\n /* until 256-byte window bug fixed */\n\n var s = new DeflateState();\n\n strm.state = s;\n s.strm = strm;\n\n s.wrap = wrap;\n s.gzhead = null;\n s.w_bits = windowBits;\n s.w_size = 1 << s.w_bits;\n s.w_mask = s.w_size - 1;\n\n s.hash_bits = memLevel + 7;\n s.hash_size = 1 << s.hash_bits;\n s.hash_mask = s.hash_size - 1;\n s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);\n\n s.window = new utils.Buf8(s.w_size * 2);\n s.head = new utils.Buf16(s.hash_size);\n s.prev = new utils.Buf16(s.w_size);\n\n // Don't need mem init magic for JS.\n //s.high_water = 0; /* nothing written to s->window yet */\n\n s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */\n\n s.pending_buf_size = s.lit_bufsize * 4;\n\n //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);\n //s->pending_buf = (uchf *) overlay;\n s.pending_buf = new utils.Buf8(s.pending_buf_size);\n\n // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)\n //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);\n s.d_buf = 1 * s.lit_bufsize;\n\n //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;\n s.l_buf = (1 + 2) * s.lit_bufsize;\n\n s.level = level;\n s.strategy = strategy;\n s.method = method;\n\n return deflateReset(strm);\n}\n\nfunction deflateInit(strm, level) {\n return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);\n}\n\n\nfunction deflate(strm, flush) {\n var old_flush, s;\n var beg, val; // for gzip header write only\n\n if (!strm || !strm.state ||\n flush > Z_BLOCK || flush < 0) {\n return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;\n }\n\n s = strm.state;\n\n if (!strm.output ||\n (!strm.input && strm.avail_in !== 0) ||\n (s.status === FINISH_STATE && flush !== Z_FINISH)) {\n return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);\n }\n\n s.strm = strm; /* just in case */\n old_flush = s.last_flush;\n s.last_flush = flush;\n\n /* Write the header */\n if (s.status === INIT_STATE) {\n\n if (s.wrap === 2) { // GZIP header\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n put_byte(s, 31);\n put_byte(s, 139);\n put_byte(s, 8);\n if (!s.gzhead) { // s->gzhead == Z_NULL\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, OS_CODE);\n s.status = BUSY_STATE;\n }\n else {\n put_byte(s, (s.gzhead.text ? 1 : 0) +\n (s.gzhead.hcrc ? 2 : 0) +\n (!s.gzhead.extra ? 0 : 4) +\n (!s.gzhead.name ? 0 : 8) +\n (!s.gzhead.comment ? 0 : 16)\n );\n put_byte(s, s.gzhead.time & 0xff);\n put_byte(s, (s.gzhead.time >> 8) & 0xff);\n put_byte(s, (s.gzhead.time >> 16) & 0xff);\n put_byte(s, (s.gzhead.time >> 24) & 0xff);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, s.gzhead.os & 0xff);\n if (s.gzhead.extra && s.gzhead.extra.length) {\n put_byte(s, s.gzhead.extra.length & 0xff);\n put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);\n }\n if (s.gzhead.hcrc) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);\n }\n s.gzindex = 0;\n s.status = EXTRA_STATE;\n }\n }\n else // DEFLATE header\n {\n var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;\n var level_flags = -1;\n\n if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {\n level_flags = 0;\n } else if (s.level < 6) {\n level_flags = 1;\n } else if (s.level === 6) {\n level_flags = 2;\n } else {\n level_flags = 3;\n }\n header |= (level_flags << 6);\n if (s.strstart !== 0) { header |= PRESET_DICT; }\n header += 31 - (header % 31);\n\n s.status = BUSY_STATE;\n putShortMSB(s, header);\n\n /* Save the adler32 of the preset dictionary: */\n if (s.strstart !== 0) {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n strm.adler = 1; // adler32(0L, Z_NULL, 0);\n }\n }\n\n//#ifdef GZIP\n if (s.status === EXTRA_STATE) {\n if (s.gzhead.extra/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n\n while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n break;\n }\n }\n put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);\n s.gzindex++;\n }\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (s.gzindex === s.gzhead.extra.length) {\n s.gzindex = 0;\n s.status = NAME_STATE;\n }\n }\n else {\n s.status = NAME_STATE;\n }\n }\n if (s.status === NAME_STATE) {\n if (s.gzhead.name/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n //int val;\n\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.name.length) {\n val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.gzindex = 0;\n s.status = COMMENT_STATE;\n }\n }\n else {\n s.status = COMMENT_STATE;\n }\n }\n if (s.status === COMMENT_STATE) {\n if (s.gzhead.comment/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n //int val;\n\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.comment.length) {\n val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.status = HCRC_STATE;\n }\n }\n else {\n s.status = HCRC_STATE;\n }\n }\n if (s.status === HCRC_STATE) {\n if (s.gzhead.hcrc) {\n if (s.pending + 2 > s.pending_buf_size) {\n flush_pending(strm);\n }\n if (s.pending + 2 <= s.pending_buf_size) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n s.status = BUSY_STATE;\n }\n }\n else {\n s.status = BUSY_STATE;\n }\n }\n//#endif\n\n /* Flush as much pending output as possible */\n if (s.pending !== 0) {\n flush_pending(strm);\n if (strm.avail_out === 0) {\n /* Since avail_out is 0, deflate will be called again with\n * more output space, but possibly with both pending and\n * avail_in equal to zero. There won't be anything to do,\n * but this is not an error situation so make sure we\n * return OK instead of BUF_ERROR at next call of deflate:\n */\n s.last_flush = -1;\n return Z_OK;\n }\n\n /* Make sure there is something to do and avoid duplicate consecutive\n * flushes. For repeated and useless calls with Z_FINISH, we keep\n * returning Z_STREAM_END instead of Z_BUF_ERROR.\n */\n } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&\n flush !== Z_FINISH) {\n return err(strm, Z_BUF_ERROR);\n }\n\n /* User must not provide more input after the first FINISH: */\n if (s.status === FINISH_STATE && strm.avail_in !== 0) {\n return err(strm, Z_BUF_ERROR);\n }\n\n /* Start a new block or continue the current one.\n */\n if (strm.avail_in !== 0 || s.lookahead !== 0 ||\n (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {\n var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :\n (s.strategy === Z_RLE ? deflate_rle(s, flush) :\n configuration_table[s.level].func(s, flush));\n\n if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {\n s.status = FINISH_STATE;\n }\n if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {\n if (strm.avail_out === 0) {\n s.last_flush = -1;\n /* avoid BUF_ERROR next call, see above */\n }\n return Z_OK;\n /* If flush != Z_NO_FLUSH && avail_out == 0, the next call\n * of deflate should use the same flush parameter to make sure\n * that the flush is complete. So we don't have to output an\n * empty block here, this will be done at next call. This also\n * ensures that for a very small output buffer, we emit at most\n * one empty block.\n */\n }\n if (bstate === BS_BLOCK_DONE) {\n if (flush === Z_PARTIAL_FLUSH) {\n trees._tr_align(s);\n }\n else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */\n\n trees._tr_stored_block(s, 0, 0, false);\n /* For a full flush, this empty block will be recognized\n * as a special marker by inflate_sync().\n */\n if (flush === Z_FULL_FLUSH) {\n /*** CLEAR_HASH(s); ***/ /* forget history */\n zero(s.head); // Fill with NIL (= 0);\n\n if (s.lookahead === 0) {\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n }\n }\n flush_pending(strm);\n if (strm.avail_out === 0) {\n s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */\n return Z_OK;\n }\n }\n }\n //Assert(strm->avail_out > 0, \"bug2\");\n //if (strm.avail_out <= 0) { throw new Error(\"bug2\");}\n\n if (flush !== Z_FINISH) { return Z_OK; }\n if (s.wrap <= 0) { return Z_STREAM_END; }\n\n /* Write the trailer */\n if (s.wrap === 2) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n put_byte(s, (strm.adler >> 16) & 0xff);\n put_byte(s, (strm.adler >> 24) & 0xff);\n put_byte(s, strm.total_in & 0xff);\n put_byte(s, (strm.total_in >> 8) & 0xff);\n put_byte(s, (strm.total_in >> 16) & 0xff);\n put_byte(s, (strm.total_in >> 24) & 0xff);\n }\n else\n {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n\n flush_pending(strm);\n /* If avail_out is zero, the application will call deflate again\n * to flush the rest.\n */\n if (s.wrap > 0) { s.wrap = -s.wrap; }\n /* write the trailer only once! */\n return s.pending !== 0 ? Z_OK : Z_STREAM_END;\n}\n\nfunction deflateEnd(strm) {\n var status;\n\n if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {\n return Z_STREAM_ERROR;\n }\n\n status = strm.state.status;\n if (status !== INIT_STATE &&\n status !== EXTRA_STATE &&\n status !== NAME_STATE &&\n status !== COMMENT_STATE &&\n status !== HCRC_STATE &&\n status !== BUSY_STATE &&\n status !== FINISH_STATE\n ) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n strm.state = null;\n\n return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;\n}\n\n\n/* =========================================================================\n * Initializes the compression dictionary from the given byte\n * sequence without producing any compressed output.\n */\nfunction deflateSetDictionary(strm, dictionary) {\n var dictLength = dictionary.length;\n\n var s;\n var str, n;\n var wrap;\n var avail;\n var next;\n var input;\n var tmpDict;\n\n if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {\n return Z_STREAM_ERROR;\n }\n\n s = strm.state;\n wrap = s.wrap;\n\n if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {\n return Z_STREAM_ERROR;\n }\n\n /* when using zlib wrappers, compute Adler-32 for provided dictionary */\n if (wrap === 1) {\n /* adler32(strm->adler, dictionary, dictLength); */\n strm.adler = adler32(strm.adler, dictionary, dictLength, 0);\n }\n\n s.wrap = 0; /* avoid computing Adler-32 in read_buf */\n\n /* if dictionary would fill window, just replace the history */\n if (dictLength >= s.w_size) {\n if (wrap === 0) { /* already empty otherwise */\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n /* use the tail */\n // dictionary = dictionary.slice(dictLength - s.w_size);\n tmpDict = new utils.Buf8(s.w_size);\n utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);\n dictionary = tmpDict;\n dictLength = s.w_size;\n }\n /* insert dictionary into window and hash */\n avail = strm.avail_in;\n next = strm.next_in;\n input = strm.input;\n strm.avail_in = dictLength;\n strm.next_in = 0;\n strm.input = dictionary;\n fill_window(s);\n while (s.lookahead >= MIN_MATCH) {\n str = s.strstart;\n n = s.lookahead - (MIN_MATCH - 1);\n do {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n\n s.head[s.ins_h] = str;\n str++;\n } while (--n);\n s.strstart = str;\n s.lookahead = MIN_MATCH - 1;\n fill_window(s);\n }\n s.strstart += s.lookahead;\n s.block_start = s.strstart;\n s.insert = s.lookahead;\n s.lookahead = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n strm.next_in = next;\n strm.input = input;\n strm.avail_in = avail;\n s.wrap = wrap;\n return Z_OK;\n}\n\n\nexports.deflateInit = deflateInit;\nexports.deflateInit2 = deflateInit2;\nexports.deflateReset = deflateReset;\nexports.deflateResetKeep = deflateResetKeep;\nexports.deflateSetHeader = deflateSetHeader;\nexports.deflate = deflate;\nexports.deflateEnd = deflateEnd;\nexports.deflateSetDictionary = deflateSetDictionary;\nexports.deflateInfo = 'pako deflate (from Nodeca project)';\n\n/* Not implemented\nexports.deflateBound = deflateBound;\nexports.deflateCopy = deflateCopy;\nexports.deflateParams = deflateParams;\nexports.deflatePending = deflatePending;\nexports.deflatePrime = deflatePrime;\nexports.deflateTune = deflateTune;\n*/\n", "// String encode/decode helpers\n'use strict';\n\n\nvar utils = require('./common');\n\n\n// Quick check if we can use fast array to bin string conversion\n//\n// - apply(Array) can fail on Android 2.2\n// - apply(Uint8Array) can fail on iOS 5.1 Safari\n//\nvar STR_APPLY_OK = true;\nvar STR_APPLY_UIA_OK = true;\n\ntry { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }\ntry { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }\n\n\n// Table with utf8 lengths (calculated by first byte of sequence)\n// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,\n// because max possible codepoint is 0x10ffff\nvar _utf8len = new utils.Buf8(256);\nfor (var q = 0; q < 256; q++) {\n _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);\n}\n_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start\n\n\n// convert string to array (typed, when possible)\nexports.string2buf = function (str) {\n var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;\n\n // count binary size\n for (m_pos = 0; m_pos < str_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n }\n\n // allocate buffer\n buf = new utils.Buf8(buf_len);\n\n // convert\n for (i = 0, m_pos = 0; i < buf_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n if (c < 0x80) {\n /* one byte */\n buf[i++] = c;\n } else if (c < 0x800) {\n /* two bytes */\n buf[i++] = 0xC0 | (c >>> 6);\n buf[i++] = 0x80 | (c & 0x3f);\n } else if (c < 0x10000) {\n /* three bytes */\n buf[i++] = 0xE0 | (c >>> 12);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n } else {\n /* four bytes */\n buf[i++] = 0xf0 | (c >>> 18);\n buf[i++] = 0x80 | (c >>> 12 & 0x3f);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n }\n }\n\n return buf;\n};\n\n// Helper (used in 2 places)\nfunction buf2binstring(buf, len) {\n // On Chrome, the arguments in a function call that are allowed is `65534`.\n // If the length of the buffer is smaller than that, we can use this optimization,\n // otherwise we will take a slower path.\n if (len < 65534) {\n if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {\n return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));\n }\n }\n\n var result = '';\n for (var i = 0; i < len; i++) {\n result += String.fromCharCode(buf[i]);\n }\n return result;\n}\n\n\n// Convert byte array to binary string\nexports.buf2binstring = function (buf) {\n return buf2binstring(buf, buf.length);\n};\n\n\n// Convert binary string (typed, when possible)\nexports.binstring2buf = function (str) {\n var buf = new utils.Buf8(str.length);\n for (var i = 0, len = buf.length; i < len; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n};\n\n\n// convert array to string\nexports.buf2string = function (buf, max) {\n var i, out, c, c_len;\n var len = max || buf.length;\n\n // Reserve max possible length (2 words per char)\n // NB: by unknown reasons, Array is significantly faster for\n // String.fromCharCode.apply than Uint16Array.\n var utf16buf = new Array(len * 2);\n\n for (out = 0, i = 0; i < len;) {\n c = buf[i++];\n // quick process ascii\n if (c < 0x80) { utf16buf[out++] = c; continue; }\n\n c_len = _utf8len[c];\n // skip 5 & 6 byte codes\n if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }\n\n // apply mask on first byte\n c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;\n // join the rest\n while (c_len > 1 && i < len) {\n c = (c << 6) | (buf[i++] & 0x3f);\n c_len--;\n }\n\n // terminated by end of string?\n if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }\n\n if (c < 0x10000) {\n utf16buf[out++] = c;\n } else {\n c -= 0x10000;\n utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);\n utf16buf[out++] = 0xdc00 | (c & 0x3ff);\n }\n }\n\n return buf2binstring(utf16buf, out);\n};\n\n\n// Calculate max possible position in utf8 buffer,\n// that will not break sequence. If that's not possible\n// - (very small limits) return max size as is.\n//\n// buf[] - utf8 bytes array\n// max - length limit (mandatory);\nexports.utf8border = function (buf, max) {\n var pos;\n\n max = max || buf.length;\n if (max > buf.length) { max = buf.length; }\n\n // go back from last position, until start of sequence found\n pos = max - 1;\n while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }\n\n // Very small and broken sequence,\n // return max, because we should return something anyway.\n if (pos < 0) { return max; }\n\n // If we came to start of buffer - that means buffer is too small,\n // return max too.\n if (pos === 0) { return max; }\n\n return (pos + _utf8len[buf[pos]] > max) ? pos : max;\n};\n", "'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction ZStream() {\n /* next input byte */\n this.input = null; // JS specific, because we have no pointers\n this.next_in = 0;\n /* number of bytes available at input */\n this.avail_in = 0;\n /* total number of input bytes read so far */\n this.total_in = 0;\n /* next output byte should be put there */\n this.output = null; // JS specific, because we have no pointers\n this.next_out = 0;\n /* remaining free space at output */\n this.avail_out = 0;\n /* total number of bytes output so far */\n this.total_out = 0;\n /* last error message, NULL if no error */\n this.msg = ''/*Z_NULL*/;\n /* not visible by applications */\n this.state = null;\n /* best guess about the data type: binary or text */\n this.data_type = 2/*Z_UNKNOWN*/;\n /* adler32 value of the uncompressed data */\n this.adler = 0;\n}\n\nmodule.exports = ZStream;\n", "'use strict';\n\n\nvar zlib_deflate = require('./zlib/deflate');\nvar utils = require('./utils/common');\nvar strings = require('./utils/strings');\nvar msg = require('./zlib/messages');\nvar ZStream = require('./zlib/zstream');\n\nvar toString = Object.prototype.toString;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nvar Z_NO_FLUSH = 0;\nvar Z_FINISH = 4;\n\nvar Z_OK = 0;\nvar Z_STREAM_END = 1;\nvar Z_SYNC_FLUSH = 2;\n\nvar Z_DEFAULT_COMPRESSION = -1;\n\nvar Z_DEFAULT_STRATEGY = 0;\n\nvar Z_DEFLATED = 8;\n\n/* ===========================================================================*/\n\n\n/**\n * class Deflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[deflate]],\n * [[deflateRaw]] and [[gzip]].\n **/\n\n/* internal\n * Deflate.chunks -> Array\n *\n * Chunks of output data, if [[Deflate#onData]] not overridden.\n **/\n\n/**\n * Deflate.result -> Uint8Array|Array\n *\n * Compressed result, generated by default [[Deflate#onData]]\n * and [[Deflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you\n * push a chunk with explicit flush (call [[Deflate#push]] with\n * `Z_SYNC_FLUSH` param).\n **/\n\n/**\n * Deflate.err -> Number\n *\n * Error code after deflate finished. 0 (Z_OK) on success.\n * You will not need it in real life, because deflate errors\n * are possible only on wrong options or bad `onData` / `onEnd`\n * custom handlers.\n **/\n\n/**\n * Deflate.msg -> String\n *\n * Error message, if [[Deflate.err]] != 0\n **/\n\n\n/**\n * new Deflate(options)\n * - options (Object): zlib deflate options.\n *\n * Creates new deflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `level`\n * - `windowBits`\n * - `memLevel`\n * - `strategy`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw deflate\n * - `gzip` (Boolean) - create gzip wrapper\n * - `to` (String) - if equal to 'string', then result will be \"binary string\"\n * (each char code [0..255])\n * - `header` (Object) - custom header for gzip\n * - `text` (Boolean) - true if compressed data believed to be text\n * - `time` (Number) - modification time, unix timestamp\n * - `os` (Number) - operation system code\n * - `extra` (Array) - array of bytes with extra data (max 65536)\n * - `name` (String) - file name (binary string)\n * - `comment` (String) - comment (binary string)\n * - `hcrc` (Boolean) - true if header crc should be added\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * var deflate = new pako.Deflate({ level: 3});\n *\n * deflate.push(chunk1, false);\n * deflate.push(chunk2, true); // true -> last chunk\n *\n * if (deflate.err) { throw new Error(deflate.err); }\n *\n * console.log(deflate.result);\n * ```\n **/\nfunction Deflate(options) {\n if (!(this instanceof Deflate)) return new Deflate(options);\n\n this.options = utils.assign({\n level: Z_DEFAULT_COMPRESSION,\n method: Z_DEFLATED,\n chunkSize: 16384,\n windowBits: 15,\n memLevel: 8,\n strategy: Z_DEFAULT_STRATEGY,\n to: ''\n }, options || {});\n\n var opt = this.options;\n\n if (opt.raw && (opt.windowBits > 0)) {\n opt.windowBits = -opt.windowBits;\n }\n\n else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {\n opt.windowBits += 16;\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new ZStream();\n this.strm.avail_out = 0;\n\n var status = zlib_deflate.deflateInit2(\n this.strm,\n opt.level,\n opt.method,\n opt.windowBits,\n opt.memLevel,\n opt.strategy\n );\n\n if (status !== Z_OK) {\n throw new Error(msg[status]);\n }\n\n if (opt.header) {\n zlib_deflate.deflateSetHeader(this.strm, opt.header);\n }\n\n if (opt.dictionary) {\n var dict;\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n // If we need to compress text, change encoding to utf8.\n dict = strings.string2buf(opt.dictionary);\n } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {\n dict = new Uint8Array(opt.dictionary);\n } else {\n dict = opt.dictionary;\n }\n\n status = zlib_deflate.deflateSetDictionary(this.strm, dict);\n\n if (status !== Z_OK) {\n throw new Error(msg[status]);\n }\n\n this._dict_set = true;\n }\n}\n\n/**\n * Deflate#push(data[, mode]) -> Boolean\n * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be\n * converted to utf8 byte sequence.\n * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with\n * new compressed chunks. Returns `true` on success. The last data block must have\n * mode Z_FINISH (or `true`). That will flush internal pending buffers and call\n * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you\n * can use mode Z_SYNC_FLUSH, keeping the compression context.\n *\n * On fail call [[Deflate#onEnd]] with error code and return false.\n *\n * We strongly recommend to use `Uint8Array` on input for best speed (output\n * array format is detected automatically). Also, don't skip last param and always\n * use the same type in your code (boolean or number). That will improve JS speed.\n *\n * For regular `Array`-s make sure all elements are [0..255].\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nDeflate.prototype.push = function (data, mode) {\n var strm = this.strm;\n var chunkSize = this.options.chunkSize;\n var status, _mode;\n\n if (this.ended) { return false; }\n\n _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);\n\n // Convert data if needed\n if (typeof data === 'string') {\n // If we need to compress text, change encoding to utf8.\n strm.input = strings.string2buf(data);\n } else if (toString.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n do {\n if (strm.avail_out === 0) {\n strm.output = new utils.Buf8(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n status = zlib_deflate.deflate(strm, _mode); /* no bad return value */\n\n if (status !== Z_STREAM_END && status !== Z_OK) {\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {\n if (this.options.to === 'string') {\n this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));\n } else {\n this.onData(utils.shrinkBuf(strm.output, strm.next_out));\n }\n }\n } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);\n\n // Finalize on the last chunk.\n if (_mode === Z_FINISH) {\n status = zlib_deflate.deflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === Z_OK;\n }\n\n // callback interim results if Z_SYNC_FLUSH.\n if (_mode === Z_SYNC_FLUSH) {\n this.onEnd(Z_OK);\n strm.avail_out = 0;\n return true;\n }\n\n return true;\n};\n\n\n/**\n * Deflate#onData(chunk) -> Void\n * - chunk (Uint8Array|Array|String): output data. Type of array depends\n * on js engine support. When string output requested, each chunk\n * will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nDeflate.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Deflate#onEnd(status) -> Void\n * - status (Number): deflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called once after you tell deflate that the input stream is\n * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)\n * or if an error happened. By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nDeflate.prototype.onEnd = function (status) {\n // On success - join\n if (status === Z_OK) {\n if (this.options.to === 'string') {\n this.result = this.chunks.join('');\n } else {\n this.result = utils.flattenChunks(this.chunks);\n }\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * deflate(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * Compress `data` with deflate algorithm and `options`.\n *\n * Supported options are:\n *\n * - level\n * - windowBits\n * - memLevel\n * - strategy\n * - dictionary\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be \"binary string\"\n * (each char code [0..255])\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);\n *\n * console.log(pako.deflate(data));\n * ```\n **/\nfunction deflate(input, options) {\n var deflator = new Deflate(options);\n\n deflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (deflator.err) { throw deflator.msg || msg[deflator.err]; }\n\n return deflator.result;\n}\n\n\n/**\n * deflateRaw(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction deflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return deflate(input, options);\n}\n\n\n/**\n * gzip(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but create gzip wrapper instead of\n * deflate one.\n **/\nfunction gzip(input, options) {\n options = options || {};\n options.gzip = true;\n return deflate(input, options);\n}\n\n\nexports.Deflate = Deflate;\nexports.deflate = deflate;\nexports.deflateRaw = deflateRaw;\nexports.gzip = gzip;\n", "'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// See state defs from inflate.js\nvar BAD = 30; /* got a data error -- remain here until reset */\nvar TYPE = 12; /* i: waiting for type bits, including last-flag bit */\n\n/*\n Decode literal, length, and distance codes and write out the resulting\n literal and match bytes until either not enough input or output is\n available, an end-of-block is encountered, or a data error is encountered.\n When large enough input and output buffers are supplied to inflate(), for\n example, a 16K input buffer and a 64K output buffer, more than 95% of the\n inflate execution time is spent in this routine.\n\n Entry assumptions:\n\n state.mode === LEN\n strm.avail_in >= 6\n strm.avail_out >= 258\n start >= strm.avail_out\n state.bits < 8\n\n On return, state.mode is one of:\n\n LEN -- ran out of enough output space or enough available input\n TYPE -- reached end of block code, inflate() to interpret next block\n BAD -- error in block data\n\n Notes:\n\n - The maximum input bits used by a length/distance pair is 15 bits for the\n length code, 5 bits for the length extra, 15 bits for the distance code,\n and 13 bits for the distance extra. This totals 48 bits, or six bytes.\n Therefore if strm.avail_in >= 6, then there is enough input to avoid\n checking for available input while decoding.\n\n - The maximum bytes that a single length/distance pair can output is 258\n bytes, which is the maximum length that can be coded. inflate_fast()\n requires strm.avail_out >= 258 for each loop to avoid checking for\n output space.\n */\nmodule.exports = function inflate_fast(strm, start) {\n var state;\n var _in; /* local strm.input */\n var last; /* have enough input while in < last */\n var _out; /* local strm.output */\n var beg; /* inflate()'s initial strm.output */\n var end; /* while out < end, enough space available */\n//#ifdef INFLATE_STRICT\n var dmax; /* maximum distance from zlib header */\n//#endif\n var wsize; /* window size or zero if not using window */\n var whave; /* valid bytes in the window */\n var wnext; /* window write index */\n // Use `s_window` instead `window`, avoid conflict with instrumentation tools\n var s_window; /* allocated sliding window, if wsize != 0 */\n var hold; /* local strm.hold */\n var bits; /* local strm.bits */\n var lcode; /* local strm.lencode */\n var dcode; /* local strm.distcode */\n var lmask; /* mask for first level of length codes */\n var dmask; /* mask for first level of distance codes */\n var here; /* retrieved table entry */\n var op; /* code bits, operation, extra bits, or */\n /* window position, window bytes to copy */\n var len; /* match length, unused bytes */\n var dist; /* match distance */\n var from; /* where to copy match from */\n var from_source;\n\n\n var input, output; // JS specific, because we have no pointers\n\n /* copy state to local variables */\n state = strm.state;\n //here = state.here;\n _in = strm.next_in;\n input = strm.input;\n last = _in + (strm.avail_in - 5);\n _out = strm.next_out;\n output = strm.output;\n beg = _out - (start - strm.avail_out);\n end = _out + (strm.avail_out - 257);\n//#ifdef INFLATE_STRICT\n dmax = state.dmax;\n//#endif\n wsize = state.wsize;\n whave = state.whave;\n wnext = state.wnext;\n s_window = state.window;\n hold = state.hold;\n bits = state.bits;\n lcode = state.lencode;\n dcode = state.distcode;\n lmask = (1 << state.lenbits) - 1;\n dmask = (1 << state.distbits) - 1;\n\n\n /* decode literals and length/distances until end-of-block or not enough\n input data or output space */\n\n top:\n do {\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n\n here = lcode[hold & lmask];\n\n dolen:\n for (;;) { // Goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n if (op === 0) { /* literal */\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n output[_out++] = here & 0xffff/*here.val*/;\n }\n else if (op & 16) { /* length base */\n len = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (op) {\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n len += hold & ((1 << op) - 1);\n hold >>>= op;\n bits -= op;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", len));\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n here = dcode[hold & dmask];\n\n dodist:\n for (;;) { // goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n\n if (op & 16) { /* distance base */\n dist = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n }\n dist += hold & ((1 << op) - 1);\n//#ifdef INFLATE_STRICT\n if (dist > dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n//#endif\n hold >>>= op;\n bits -= op;\n //Tracevv((stderr, \"inflate: distance %u\\n\", dist));\n op = _out - beg; /* max distance in output */\n if (dist > op) { /* see if copy from window */\n op = dist - op; /* distance back in window */\n if (op > whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// if (len <= op - whave) {\n// do {\n// output[_out++] = 0;\n// } while (--len);\n// continue top;\n// }\n// len -= op - whave;\n// do {\n// output[_out++] = 0;\n// } while (--op > whave);\n// if (op === 0) {\n// from = _out - dist;\n// do {\n// output[_out++] = output[from++];\n// } while (--len);\n// continue top;\n// }\n//#endif\n }\n from = 0; // window index\n from_source = s_window;\n if (wnext === 0) { /* very common case */\n from += wsize - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n else if (wnext < op) { /* wrap around window */\n from += wsize + wnext - op;\n op -= wnext;\n if (op < len) { /* some from end of window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = 0;\n if (wnext < len) { /* some from start of window */\n op = wnext;\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n }\n else { /* contiguous in window */\n from += wnext - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n while (len > 2) {\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n len -= 3;\n }\n if (len) {\n output[_out++] = from_source[from++];\n if (len > 1) {\n output[_out++] = from_source[from++];\n }\n }\n }\n else {\n from = _out - dist; /* copy direct from output */\n do { /* minimum length is three */\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n len -= 3;\n } while (len > 2);\n if (len) {\n output[_out++] = output[from++];\n if (len > 1) {\n output[_out++] = output[from++];\n }\n }\n }\n }\n else if ((op & 64) === 0) { /* 2nd level distance code */\n here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dodist;\n }\n else {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n }\n else if ((op & 64) === 0) { /* 2nd level length code */\n here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dolen;\n }\n else if (op & 32) { /* end-of-block */\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.mode = TYPE;\n break top;\n }\n else {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } while (_in < last && _out < end);\n\n /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n len = bits >> 3;\n _in -= len;\n bits -= len << 3;\n hold &= (1 << bits) - 1;\n\n /* update state and return */\n strm.next_in = _in;\n strm.next_out = _out;\n strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));\n strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));\n state.hold = hold;\n state.bits = bits;\n return;\n};\n", "'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar utils = require('../utils/common');\n\nvar MAXBITS = 15;\nvar ENOUGH_LENS = 852;\nvar ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nvar CODES = 0;\nvar LENS = 1;\nvar DISTS = 2;\n\nvar lbase = [ /* Length codes 257..285 base */\n 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n];\n\nvar lext = [ /* Length codes 257..285 extra */\n 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78\n];\n\nvar dbase = [ /* Distance codes 0..29 base */\n 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n 8193, 12289, 16385, 24577, 0, 0\n];\n\nvar dext = [ /* Distance codes 0..29 extra */\n 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n 28, 28, 29, 29, 64, 64\n];\n\nmodule.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)\n{\n var bits = opts.bits;\n //here = opts.here; /* table entry for duplication */\n\n var len = 0; /* a code's length in bits */\n var sym = 0; /* index of code symbols */\n var min = 0, max = 0; /* minimum and maximum code lengths */\n var root = 0; /* number of index bits for root table */\n var curr = 0; /* number of index bits for current table */\n var drop = 0; /* code bits to drop for sub-table */\n var left = 0; /* number of prefix codes available */\n var used = 0; /* code entries in table used */\n var huff = 0; /* Huffman code */\n var incr; /* for incrementing code, index */\n var fill; /* index for replicating entries */\n var low; /* low bits for current root entry */\n var mask; /* mask for low root bits */\n var next; /* next available space in table */\n var base = null; /* base value table to use */\n var base_index = 0;\n// var shoextra; /* extra bits table to use */\n var end; /* use base and extra for symbol > end */\n var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */\n var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */\n var extra = null;\n var extra_index = 0;\n\n var here_bits, here_op, here_val;\n\n /*\n Process a set of code lengths to create a canonical Huffman code. The\n code lengths are lens[0..codes-1]. Each length corresponds to the\n symbols 0..codes-1. The Huffman code is generated by first sorting the\n symbols by length from short to long, and retaining the symbol order\n for codes with equal lengths. Then the code starts with all zero bits\n for the first code of the shortest length, and the codes are integer\n increments for the same length, and zeros are appended as the length\n increases. For the deflate format, these bits are stored backwards\n from their more natural integer increment ordering, and so when the\n decoding tables are built in the large loop below, the integer codes\n are incremented backwards.\n\n This routine assumes, but does not check, that all of the entries in\n lens[] are in the range 0..MAXBITS. The caller must assure this.\n 1..MAXBITS is interpreted as that code length. zero means that that\n symbol does not occur in this code.\n\n The codes are sorted by computing a count of codes for each length,\n creating from that a table of starting indices for each length in the\n sorted table, and then entering the symbols in order in the sorted\n table. The sorted table is work[], with that space being provided by\n the caller.\n\n The length counts are used for other purposes as well, i.e. finding\n the minimum and maximum length codes, determining if there are any\n codes at all, checking for a valid set of lengths, and looking ahead\n at length counts to determine sub-table sizes when building the\n decoding tables.\n */\n\n /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n for (len = 0; len <= MAXBITS; len++) {\n count[len] = 0;\n }\n for (sym = 0; sym < codes; sym++) {\n count[lens[lens_index + sym]]++;\n }\n\n /* bound code lengths, force root to be within code lengths */\n root = bits;\n for (max = MAXBITS; max >= 1; max--) {\n if (count[max] !== 0) { break; }\n }\n if (root > max) {\n root = max;\n }\n if (max === 0) { /* no symbols to code at all */\n //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */\n //table.bits[opts.table_index] = 1; //here.bits = (var char)1;\n //table.val[opts.table_index++] = 0; //here.val = (var short)0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n\n //table.op[opts.table_index] = 64;\n //table.bits[opts.table_index] = 1;\n //table.val[opts.table_index++] = 0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n opts.bits = 1;\n return 0; /* no symbols, but wait for decoding to report error */\n }\n for (min = 1; min < max; min++) {\n if (count[min] !== 0) { break; }\n }\n if (root < min) {\n root = min;\n }\n\n /* check for an over-subscribed or incomplete set of lengths */\n left = 1;\n for (len = 1; len <= MAXBITS; len++) {\n left <<= 1;\n left -= count[len];\n if (left < 0) {\n return -1;\n } /* over-subscribed */\n }\n if (left > 0 && (type === CODES || max !== 1)) {\n return -1; /* incomplete set */\n }\n\n /* generate offsets into symbol table for each length for sorting */\n offs[1] = 0;\n for (len = 1; len < MAXBITS; len++) {\n offs[len + 1] = offs[len] + count[len];\n }\n\n /* sort symbols by length, by symbol order within each length */\n for (sym = 0; sym < codes; sym++) {\n if (lens[lens_index + sym] !== 0) {\n work[offs[lens[lens_index + sym]]++] = sym;\n }\n }\n\n /*\n Create and fill in decoding tables. In this loop, the table being\n filled is at next and has curr index bits. The code being used is huff\n with length len. That code is converted to an index by dropping drop\n bits off of the bottom. For codes where len is less than drop + curr,\n those top drop + curr - len bits are incremented through all values to\n fill the table with replicated entries.\n\n root is the number of index bits for the root table. When len exceeds\n root, sub-tables are created pointed to by the root entry with an index\n of the low root bits of huff. This is saved in low to check for when a\n new sub-table should be started. drop is zero when the root table is\n being filled, and drop is root when sub-tables are being filled.\n\n When a new sub-table is needed, it is necessary to look ahead in the\n code lengths to determine what size sub-table is needed. The length\n counts are used for this, and so count[] is decremented as codes are\n entered in the tables.\n\n used keeps track of how many table entries have been allocated from the\n provided *table space. It is checked for LENS and DIST tables against\n the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n the initial root table size constants. See the comments in inftrees.h\n for more information.\n\n sym increments through all symbols, and the loop terminates when\n all codes of length max, i.e. all codes, have been processed. This\n routine permits incomplete codes, so another loop after this one fills\n in the rest of the decoding tables with invalid code markers.\n */\n\n /* set up for code type */\n // poor man optimization - use if-else instead of switch,\n // to avoid deopts in old v8\n if (type === CODES) {\n base = extra = work; /* dummy value--not used */\n end = 19;\n\n } else if (type === LENS) {\n base = lbase;\n base_index -= 257;\n extra = lext;\n extra_index -= 257;\n end = 256;\n\n } else { /* DISTS */\n base = dbase;\n extra = dext;\n end = -1;\n }\n\n /* initialize opts for loop */\n huff = 0; /* starting code */\n sym = 0; /* starting code symbol */\n len = min; /* starting code length */\n next = table_index; /* current table to fill in */\n curr = root; /* current table index bits */\n drop = 0; /* current bits to drop from code for index */\n low = -1; /* trigger new sub-table when len > root */\n used = 1 << root; /* use root table entries */\n mask = used - 1; /* mask for comparing low */\n\n /* check available table space */\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* process all codes and make table entries */\n for (;;) {\n /* create table entry */\n here_bits = len - drop;\n if (work[sym] < end) {\n here_op = 0;\n here_val = work[sym];\n }\n else if (work[sym] > end) {\n here_op = extra[extra_index + work[sym]];\n here_val = base[base_index + work[sym]];\n }\n else {\n here_op = 32 + 64; /* end of block */\n here_val = 0;\n }\n\n /* replicate for those indices with low len bits equal to huff */\n incr = 1 << (len - drop);\n fill = 1 << curr;\n min = fill; /* save offset to next table */\n do {\n fill -= incr;\n table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;\n } while (fill !== 0);\n\n /* backwards increment the len-bit code huff */\n incr = 1 << (len - 1);\n while (huff & incr) {\n incr >>= 1;\n }\n if (incr !== 0) {\n huff &= incr - 1;\n huff += incr;\n } else {\n huff = 0;\n }\n\n /* go to next symbol, update count, len */\n sym++;\n if (--count[len] === 0) {\n if (len === max) { break; }\n len = lens[lens_index + work[sym]];\n }\n\n /* create new sub-table if needed */\n if (len > root && (huff & mask) !== low) {\n /* if first time, transition to sub-tables */\n if (drop === 0) {\n drop = root;\n }\n\n /* increment past last table */\n next += min; /* here min is 1 << curr */\n\n /* determine length of next table */\n curr = len - drop;\n left = 1 << curr;\n while (curr + drop < max) {\n left -= count[curr + drop];\n if (left <= 0) { break; }\n curr++;\n left <<= 1;\n }\n\n /* check for enough space */\n used += 1 << curr;\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* point entry in root table to sub-table */\n low = huff & mask;\n /*table.op[low] = curr;\n table.bits[low] = root;\n table.val[low] = next - opts.table_index;*/\n table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;\n }\n }\n\n /* fill in remaining table entry if code is incomplete (guaranteed to have\n at most one remaining entry, since if the code is incomplete, the\n maximum code length that was allowed to get this far is one bit) */\n if (huff !== 0) {\n //table.op[next + huff] = 64; /* invalid code marker */\n //table.bits[next + huff] = len - drop;\n //table.val[next + huff] = 0;\n table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;\n }\n\n /* set return parameters */\n //opts.table_index += used;\n opts.bits = root;\n return 0;\n};\n", "'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar utils = require('../utils/common');\nvar adler32 = require('./adler32');\nvar crc32 = require('./crc32');\nvar inflate_fast = require('./inffast');\nvar inflate_table = require('./inftrees');\n\nvar CODES = 0;\nvar LENS = 1;\nvar DISTS = 2;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n/* Allowed flush values; see deflate() and inflate() below for details */\n//var Z_NO_FLUSH = 0;\n//var Z_PARTIAL_FLUSH = 1;\n//var Z_SYNC_FLUSH = 2;\n//var Z_FULL_FLUSH = 3;\nvar Z_FINISH = 4;\nvar Z_BLOCK = 5;\nvar Z_TREES = 6;\n\n\n/* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\nvar Z_OK = 0;\nvar Z_STREAM_END = 1;\nvar Z_NEED_DICT = 2;\n//var Z_ERRNO = -1;\nvar Z_STREAM_ERROR = -2;\nvar Z_DATA_ERROR = -3;\nvar Z_MEM_ERROR = -4;\nvar Z_BUF_ERROR = -5;\n//var Z_VERSION_ERROR = -6;\n\n/* The deflate compression method */\nvar Z_DEFLATED = 8;\n\n\n/* STATES ====================================================================*/\n/* ===========================================================================*/\n\n\nvar HEAD = 1; /* i: waiting for magic header */\nvar FLAGS = 2; /* i: waiting for method and flags (gzip) */\nvar TIME = 3; /* i: waiting for modification time (gzip) */\nvar OS = 4; /* i: waiting for extra flags and operating system (gzip) */\nvar EXLEN = 5; /* i: waiting for extra length (gzip) */\nvar EXTRA = 6; /* i: waiting for extra bytes (gzip) */\nvar NAME = 7; /* i: waiting for end of file name (gzip) */\nvar COMMENT = 8; /* i: waiting for end of comment (gzip) */\nvar HCRC = 9; /* i: waiting for header crc (gzip) */\nvar DICTID = 10; /* i: waiting for dictionary check value */\nvar DICT = 11; /* waiting for inflateSetDictionary() call */\nvar TYPE = 12; /* i: waiting for type bits, including last-flag bit */\nvar TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */\nvar STORED = 14; /* i: waiting for stored size (length and complement) */\nvar COPY_ = 15; /* i/o: same as COPY below, but only first time in */\nvar COPY = 16; /* i/o: waiting for input or output to copy stored block */\nvar TABLE = 17; /* i: waiting for dynamic block table lengths */\nvar LENLENS = 18; /* i: waiting for code length code lengths */\nvar CODELENS = 19; /* i: waiting for length/lit and distance code lengths */\nvar LEN_ = 20; /* i: same as LEN below, but only first time in */\nvar LEN = 21; /* i: waiting for length/lit/eob code */\nvar LENEXT = 22; /* i: waiting for length extra bits */\nvar DIST = 23; /* i: waiting for distance code */\nvar DISTEXT = 24; /* i: waiting for distance extra bits */\nvar MATCH = 25; /* o: waiting for output space to copy string */\nvar LIT = 26; /* o: waiting for output space to write literal */\nvar CHECK = 27; /* i: waiting for 32-bit check value */\nvar LENGTH = 28; /* i: waiting for 32-bit length (gzip) */\nvar DONE = 29; /* finished check, done -- remain here until reset */\nvar BAD = 30; /* got a data error -- remain here until reset */\nvar MEM = 31; /* got an inflate() memory error -- remain here until reset */\nvar SYNC = 32; /* looking for synchronization bytes to restart inflate() */\n\n/* ===========================================================================*/\n\n\n\nvar ENOUGH_LENS = 852;\nvar ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nvar MAX_WBITS = 15;\n/* 32K LZ77 window */\nvar DEF_WBITS = MAX_WBITS;\n\n\nfunction zswap32(q) {\n return (((q >>> 24) & 0xff) +\n ((q >>> 8) & 0xff00) +\n ((q & 0xff00) << 8) +\n ((q & 0xff) << 24));\n}\n\n\nfunction InflateState() {\n this.mode = 0; /* current inflate mode */\n this.last = false; /* true if processing last block */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.havedict = false; /* true if dictionary provided */\n this.flags = 0; /* gzip header method and flags (0 if zlib) */\n this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */\n this.check = 0; /* protected copy of check value */\n this.total = 0; /* protected copy of output count */\n // TODO: may be {}\n this.head = null; /* where to save gzip header information */\n\n /* sliding window */\n this.wbits = 0; /* log base 2 of requested window size */\n this.wsize = 0; /* window size or zero if not using window */\n this.whave = 0; /* valid bytes in the window */\n this.wnext = 0; /* window write index */\n this.window = null; /* allocated sliding window, if needed */\n\n /* bit accumulator */\n this.hold = 0; /* input bit accumulator */\n this.bits = 0; /* number of bits in \"in\" */\n\n /* for string and stored block copying */\n this.length = 0; /* literal or length of data to copy */\n this.offset = 0; /* distance back to copy string from */\n\n /* for table and code decoding */\n this.extra = 0; /* extra bits needed */\n\n /* fixed and dynamic code tables */\n this.lencode = null; /* starting table for length/literal codes */\n this.distcode = null; /* starting table for distance codes */\n this.lenbits = 0; /* index bits for lencode */\n this.distbits = 0; /* index bits for distcode */\n\n /* dynamic table building */\n this.ncode = 0; /* number of code length code lengths */\n this.nlen = 0; /* number of length code lengths */\n this.ndist = 0; /* number of distance code lengths */\n this.have = 0; /* number of code lengths in lens[] */\n this.next = null; /* next available space in codes[] */\n\n this.lens = new utils.Buf16(320); /* temporary storage for code lengths */\n this.work = new utils.Buf16(288); /* work area for code table building */\n\n /*\n because we don't have pointers in js, we use lencode and distcode directly\n as buffers so we don't need codes\n */\n //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */\n this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */\n this.distdyn = null; /* dynamic table for distance codes (JS specific) */\n this.sane = 0; /* if false, allow invalid distance too far */\n this.back = 0; /* bits back of last unprocessed length/lit */\n this.was = 0; /* initial length of match */\n}\n\nfunction inflateResetKeep(strm) {\n var state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n strm.total_in = strm.total_out = state.total = 0;\n strm.msg = ''; /*Z_NULL*/\n if (state.wrap) { /* to support ill-conceived Java test suite */\n strm.adler = state.wrap & 1;\n }\n state.mode = HEAD;\n state.last = 0;\n state.havedict = 0;\n state.dmax = 32768;\n state.head = null/*Z_NULL*/;\n state.hold = 0;\n state.bits = 0;\n //state.lencode = state.distcode = state.next = state.codes;\n state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);\n state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);\n\n state.sane = 1;\n state.back = -1;\n //Tracev((stderr, \"inflate: reset\\n\"));\n return Z_OK;\n}\n\nfunction inflateReset(strm) {\n var state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n state.wsize = 0;\n state.whave = 0;\n state.wnext = 0;\n return inflateResetKeep(strm);\n\n}\n\nfunction inflateReset2(strm, windowBits) {\n var wrap;\n var state;\n\n /* get the state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n /* extract wrap request from windowBits parameter */\n if (windowBits < 0) {\n wrap = 0;\n windowBits = -windowBits;\n }\n else {\n wrap = (windowBits >> 4) + 1;\n if (windowBits < 48) {\n windowBits &= 15;\n }\n }\n\n /* set number of window bits, free window if different */\n if (windowBits && (windowBits < 8 || windowBits > 15)) {\n return Z_STREAM_ERROR;\n }\n if (state.window !== null && state.wbits !== windowBits) {\n state.window = null;\n }\n\n /* update state and reset the rest of it */\n state.wrap = wrap;\n state.wbits = windowBits;\n return inflateReset(strm);\n}\n\nfunction inflateInit2(strm, windowBits) {\n var ret;\n var state;\n\n if (!strm) { return Z_STREAM_ERROR; }\n //strm.msg = Z_NULL; /* in case we return an error */\n\n state = new InflateState();\n\n //if (state === Z_NULL) return Z_MEM_ERROR;\n //Tracev((stderr, \"inflate: allocated\\n\"));\n strm.state = state;\n state.window = null/*Z_NULL*/;\n ret = inflateReset2(strm, windowBits);\n if (ret !== Z_OK) {\n strm.state = null/*Z_NULL*/;\n }\n return ret;\n}\n\nfunction inflateInit(strm) {\n return inflateInit2(strm, DEF_WBITS);\n}\n\n\n/*\n Return state with length and distance decoding tables and index sizes set to\n fixed code decoding. Normally this returns fixed tables from inffixed.h.\n If BUILDFIXED is defined, then instead this routine builds the tables the\n first time it's called, and returns those tables the first time and\n thereafter. This reduces the size of the code by about 2K bytes, in\n exchange for a little execution time. However, BUILDFIXED should not be\n used for threaded applications, since the rewriting of the tables and virgin\n may not be thread-safe.\n */\nvar virgin = true;\n\nvar lenfix, distfix; // We have no pointers in JS, so keep tables separate\n\nfunction fixedtables(state) {\n /* build fixed huffman tables if first call (may not be thread safe) */\n if (virgin) {\n var sym;\n\n lenfix = new utils.Buf32(512);\n distfix = new utils.Buf32(32);\n\n /* literal/length table */\n sym = 0;\n while (sym < 144) { state.lens[sym++] = 8; }\n while (sym < 256) { state.lens[sym++] = 9; }\n while (sym < 280) { state.lens[sym++] = 7; }\n while (sym < 288) { state.lens[sym++] = 8; }\n\n inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });\n\n /* distance table */\n sym = 0;\n while (sym < 32) { state.lens[sym++] = 5; }\n\n inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });\n\n /* do this just once */\n virgin = false;\n }\n\n state.lencode = lenfix;\n state.lenbits = 9;\n state.distcode = distfix;\n state.distbits = 5;\n}\n\n\n/*\n Update the window with the last wsize (normally 32K) bytes written before\n returning. If window does not exist yet, create it. This is only called\n when a window is already in use, or when output has been written during this\n inflate call, but the end of the deflate stream has not been reached yet.\n It is also called to create a window for dictionary data when a dictionary\n is loaded.\n\n Providing output buffers larger than 32K to inflate() should provide a speed\n advantage, since only the last 32K of output is copied to the sliding window\n upon return from inflate(), and since all distances after the first 32K of\n output will fall in the output data, making match copies simpler and faster.\n The advantage may be dependent on the size of the processor's data caches.\n */\nfunction updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}\n\nfunction inflate(strm, flush) {\n var state;\n var input, output; // input/output buffers\n var next; /* next input INDEX */\n var put; /* next output INDEX */\n var have, left; /* available input and output */\n var hold; /* bit buffer */\n var bits; /* bits in bit buffer */\n var _in, _out; /* save starting available input and output */\n var copy; /* number of stored or match bytes to copy */\n var from; /* where to copy match bytes from */\n var from_source;\n var here = 0; /* current decoding table entry */\n var here_bits, here_op, here_val; // paked \"here\" denormalized (JS specific)\n //var last; /* parent table entry */\n var last_bits, last_op, last_val; // paked \"last\" denormalized (JS specific)\n var len; /* length to copy for repeats, bits to drop */\n var ret; /* return code */\n var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */\n var opts;\n\n var n; // temporary var for NEED_BITS\n\n var order = /* permutation of code lengths */\n [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];\n\n\n if (!strm || !strm.state || !strm.output ||\n (!strm.input && strm.avail_in !== 0)) {\n return Z_STREAM_ERROR;\n }\n\n state = strm.state;\n if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */\n\n\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n _in = have;\n _out = left;\n ret = Z_OK;\n\n inf_leave: // goto emulation\n for (;;) {\n switch (state.mode) {\n case HEAD:\n if (state.wrap === 0) {\n state.mode = TYPEDO;\n break;\n }\n //=== NEEDBITS(16);\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */\n state.check = 0/*crc32(0L, Z_NULL, 0)*/;\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = FLAGS;\n break;\n }\n state.flags = 0; /* expect zlib header */\n if (state.head) {\n state.head.done = false;\n }\n if (!(state.wrap & 1) || /* check if zlib header allowed */\n (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {\n strm.msg = 'incorrect header check';\n state.mode = BAD;\n break;\n }\n if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n len = (hold & 0x0f)/*BITS(4)*/ + 8;\n if (state.wbits === 0) {\n state.wbits = len;\n }\n else if (len > state.wbits) {\n strm.msg = 'invalid window size';\n state.mode = BAD;\n break;\n }\n state.dmax = 1 << len;\n //Tracev((stderr, \"inflate: zlib header ok\\n\"));\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = hold & 0x200 ? DICTID : TYPE;\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n break;\n case FLAGS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.flags = hold;\n if ((state.flags & 0xff) !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n if (state.flags & 0xe000) {\n strm.msg = 'unknown header flags set';\n state.mode = BAD;\n break;\n }\n if (state.head) {\n state.head.text = ((hold >> 8) & 1);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = TIME;\n /* falls through */\n case TIME:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.time = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC4(state.check, hold)\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n hbuf[2] = (hold >>> 16) & 0xff;\n hbuf[3] = (hold >>> 24) & 0xff;\n state.check = crc32(state.check, hbuf, 4, 0);\n //===\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = OS;\n /* falls through */\n case OS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.xflags = (hold & 0xff);\n state.head.os = (hold >> 8);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = EXLEN;\n /* falls through */\n case EXLEN:\n if (state.flags & 0x0400) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length = hold;\n if (state.head) {\n state.head.extra_len = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n else if (state.head) {\n state.head.extra = null/*Z_NULL*/;\n }\n state.mode = EXTRA;\n /* falls through */\n case EXTRA:\n if (state.flags & 0x0400) {\n copy = state.length;\n if (copy > have) { copy = have; }\n if (copy) {\n if (state.head) {\n len = state.head.extra_len - state.length;\n if (!state.head.extra) {\n // Use untyped array for more convenient processing later\n state.head.extra = new Array(state.head.extra_len);\n }\n utils.arraySet(\n state.head.extra,\n input,\n next,\n // extra field is limited to 65536 bytes\n // - no need for additional size check\n copy,\n /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n len\n );\n //zmemcpy(state.head.extra + len, next,\n // len + copy > state.head.extra_max ?\n // state.head.extra_max - len : copy);\n }\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n state.length -= copy;\n }\n if (state.length) { break inf_leave; }\n }\n state.length = 0;\n state.mode = NAME;\n /* falls through */\n case NAME:\n if (state.flags & 0x0800) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n // TODO: 2 or 1 bytes?\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.name_max*/)) {\n state.head.name += String.fromCharCode(len);\n }\n } while (len && copy < have);\n\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.name = null;\n }\n state.length = 0;\n state.mode = COMMENT;\n /* falls through */\n case COMMENT:\n if (state.flags & 0x1000) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.comm_max*/)) {\n state.head.comment += String.fromCharCode(len);\n }\n } while (len && copy < have);\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.comment = null;\n }\n state.mode = HCRC;\n /* falls through */\n case HCRC:\n if (state.flags & 0x0200) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.check & 0xffff)) {\n strm.msg = 'header crc mismatch';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n if (state.head) {\n state.head.hcrc = ((state.flags >> 9) & 1);\n state.head.done = true;\n }\n strm.adler = state.check = 0;\n state.mode = TYPE;\n break;\n case DICTID:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n strm.adler = state.check = zswap32(hold);\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = DICT;\n /* falls through */\n case DICT:\n if (state.havedict === 0) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n return Z_NEED_DICT;\n }\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = TYPE;\n /* falls through */\n case TYPE:\n if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case TYPEDO:\n if (state.last) {\n //--- BYTEBITS() ---//\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n state.mode = CHECK;\n break;\n }\n //=== NEEDBITS(3); */\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.last = (hold & 0x01)/*BITS(1)*/;\n //--- DROPBITS(1) ---//\n hold >>>= 1;\n bits -= 1;\n //---//\n\n switch ((hold & 0x03)/*BITS(2)*/) {\n case 0: /* stored block */\n //Tracev((stderr, \"inflate: stored block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = STORED;\n break;\n case 1: /* fixed block */\n fixedtables(state);\n //Tracev((stderr, \"inflate: fixed codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = LEN_; /* decode codes */\n if (flush === Z_TREES) {\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break inf_leave;\n }\n break;\n case 2: /* dynamic block */\n //Tracev((stderr, \"inflate: dynamic codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = TABLE;\n break;\n case 3:\n strm.msg = 'invalid block type';\n state.mode = BAD;\n }\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break;\n case STORED:\n //--- BYTEBITS() ---// /* go to byte boundary */\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {\n strm.msg = 'invalid stored block lengths';\n state.mode = BAD;\n break;\n }\n state.length = hold & 0xffff;\n //Tracev((stderr, \"inflate: stored length %u\\n\",\n // state.length));\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = COPY_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case COPY_:\n state.mode = COPY;\n /* falls through */\n case COPY:\n copy = state.length;\n if (copy) {\n if (copy > have) { copy = have; }\n if (copy > left) { copy = left; }\n if (copy === 0) { break inf_leave; }\n //--- zmemcpy(put, next, copy); ---\n utils.arraySet(output, input, next, copy, put);\n //---//\n have -= copy;\n next += copy;\n left -= copy;\n put += copy;\n state.length -= copy;\n break;\n }\n //Tracev((stderr, \"inflate: stored end\\n\"));\n state.mode = TYPE;\n break;\n case TABLE:\n //=== NEEDBITS(14); */\n while (bits < 14) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n//#ifndef PKZIP_BUG_WORKAROUND\n if (state.nlen > 286 || state.ndist > 30) {\n strm.msg = 'too many length or distance symbols';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracev((stderr, \"inflate: table sizes ok\\n\"));\n state.have = 0;\n state.mode = LENLENS;\n /* falls through */\n case LENLENS:\n while (state.have < state.ncode) {\n //=== NEEDBITS(3);\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n while (state.have < 19) {\n state.lens[order[state.have++]] = 0;\n }\n // We have separate tables & no pointers. 2 commented lines below not needed.\n //state.next = state.codes;\n //state.lencode = state.next;\n // Switch to use dynamic table\n state.lencode = state.lendyn;\n state.lenbits = 7;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n state.lenbits = opts.bits;\n\n if (ret) {\n strm.msg = 'invalid code lengths set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, \"inflate: code lengths ok\\n\"));\n state.have = 0;\n state.mode = CODELENS;\n /* falls through */\n case CODELENS:\n while (state.have < state.nlen + state.ndist) {\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_val < 16) {\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.lens[state.have++] = here_val;\n }\n else {\n if (here_val === 16) {\n //=== NEEDBITS(here.bits + 2);\n n = here_bits + 2;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n if (state.have === 0) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n len = state.lens[state.have - 1];\n copy = 3 + (hold & 0x03);//BITS(2);\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n }\n else if (here_val === 17) {\n //=== NEEDBITS(here.bits + 3);\n n = here_bits + 3;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 3 + (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n else {\n //=== NEEDBITS(here.bits + 7);\n n = here_bits + 7;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 11 + (hold & 0x7f);//BITS(7);\n //--- DROPBITS(7) ---//\n hold >>>= 7;\n bits -= 7;\n //---//\n }\n if (state.have + copy > state.nlen + state.ndist) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n while (copy--) {\n state.lens[state.have++] = len;\n }\n }\n }\n\n /* handle error breaks in while */\n if (state.mode === BAD) { break; }\n\n /* check for end-of-block code (better have one) */\n if (state.lens[256] === 0) {\n strm.msg = 'invalid code -- missing end-of-block';\n state.mode = BAD;\n break;\n }\n\n /* build code tables -- note: do not change the lenbits or distbits\n values here (9 and 6) without reading the comments in inftrees.h\n concerning the ENOUGH constants, which depend on those values */\n state.lenbits = 9;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.lenbits = opts.bits;\n // state.lencode = state.next;\n\n if (ret) {\n strm.msg = 'invalid literal/lengths set';\n state.mode = BAD;\n break;\n }\n\n state.distbits = 6;\n //state.distcode.copy(state.codes);\n // Switch to use dynamic table\n state.distcode = state.distdyn;\n opts = { bits: state.distbits };\n ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.distbits = opts.bits;\n // state.distcode = state.next;\n\n if (ret) {\n strm.msg = 'invalid distances set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, 'inflate: codes ok\\n'));\n state.mode = LEN_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case LEN_:\n state.mode = LEN;\n /* falls through */\n case LEN:\n if (have >= 6 && left >= 258) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n inflate_fast(strm, _out);\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n if (state.mode === TYPE) {\n state.back = -1;\n }\n break;\n }\n state.back = 0;\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if (here_bits <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_op && (here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.lencode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n state.length = here_val;\n if (here_op === 0) {\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n state.mode = LIT;\n break;\n }\n if (here_op & 32) {\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.back = -1;\n state.mode = TYPE;\n break;\n }\n if (here_op & 64) {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break;\n }\n state.extra = here_op & 15;\n state.mode = LENEXT;\n /* falls through */\n case LENEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", state.length));\n state.was = state.length;\n state.mode = DIST;\n /* falls through */\n case DIST:\n for (;;) {\n here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if ((here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.distcode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n if (here_op & 64) {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break;\n }\n state.offset = here_val;\n state.extra = (here_op) & 15;\n state.mode = DISTEXT;\n /* falls through */\n case DISTEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n//#ifdef INFLATE_STRICT\n if (state.offset > state.dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracevv((stderr, \"inflate: distance %u\\n\", state.offset));\n state.mode = MATCH;\n /* falls through */\n case MATCH:\n if (left === 0) { break inf_leave; }\n copy = _out - left;\n if (state.offset > copy) { /* copy from window */\n copy = state.offset - copy;\n if (copy > state.whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// Trace((stderr, \"inflate.c too far\\n\"));\n// copy -= state.whave;\n// if (copy > state.length) { copy = state.length; }\n// if (copy > left) { copy = left; }\n// left -= copy;\n// state.length -= copy;\n// do {\n// output[put++] = 0;\n// } while (--copy);\n// if (state.length === 0) { state.mode = LEN; }\n// break;\n//#endif\n }\n if (copy > state.wnext) {\n copy -= state.wnext;\n from = state.wsize - copy;\n }\n else {\n from = state.wnext - copy;\n }\n if (copy > state.length) { copy = state.length; }\n from_source = state.window;\n }\n else { /* copy from output */\n from_source = output;\n from = put - state.offset;\n copy = state.length;\n }\n if (copy > left) { copy = left; }\n left -= copy;\n state.length -= copy;\n do {\n output[put++] = from_source[from++];\n } while (--copy);\n if (state.length === 0) { state.mode = LEN; }\n break;\n case LIT:\n if (left === 0) { break inf_leave; }\n output[put++] = state.length;\n left--;\n state.mode = LEN;\n break;\n case CHECK:\n if (state.wrap) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n // Use '|' instead of '+' to make sure that result is signed\n hold |= input[next++] << bits;\n bits += 8;\n }\n //===//\n _out -= left;\n strm.total_out += _out;\n state.total += _out;\n if (_out) {\n strm.adler = state.check =\n /*UPDATE(state.check, put - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));\n\n }\n _out = left;\n // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too\n if ((state.flags ? hold : zswap32(hold)) !== state.check) {\n strm.msg = 'incorrect data check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: check matches trailer\\n\"));\n }\n state.mode = LENGTH;\n /* falls through */\n case LENGTH:\n if (state.wrap && state.flags) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.total & 0xffffffff)) {\n strm.msg = 'incorrect length check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: length matches trailer\\n\"));\n }\n state.mode = DONE;\n /* falls through */\n case DONE:\n ret = Z_STREAM_END;\n break inf_leave;\n case BAD:\n ret = Z_DATA_ERROR;\n break inf_leave;\n case MEM:\n return Z_MEM_ERROR;\n case SYNC:\n /* falls through */\n default:\n return Z_STREAM_ERROR;\n }\n }\n\n // inf_leave <- here is real place for \"goto inf_leave\", emulated via \"break inf_leave\"\n\n /*\n Return from inflate(), updating the total counts and the check value.\n If there was no progress during the inflate() call, return a buffer\n error. Call updatewindow() to create and/or update the window state.\n Note: a memory error from inflate() is non-recoverable.\n */\n\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n\n if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&\n (state.mode < CHECK || flush !== Z_FINISH))) {\n if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {\n state.mode = MEM;\n return Z_MEM_ERROR;\n }\n }\n _in -= strm.avail_in;\n _out -= strm.avail_out;\n strm.total_in += _in;\n strm.total_out += _out;\n state.total += _out;\n if (state.wrap && _out) {\n strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));\n }\n strm.data_type = state.bits + (state.last ? 64 : 0) +\n (state.mode === TYPE ? 128 : 0) +\n (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {\n ret = Z_BUF_ERROR;\n }\n return ret;\n}\n\nfunction inflateEnd(strm) {\n\n if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {\n return Z_STREAM_ERROR;\n }\n\n var state = strm.state;\n if (state.window) {\n state.window = null;\n }\n strm.state = null;\n return Z_OK;\n}\n\nfunction inflateGetHeader(strm, head) {\n var state;\n\n /* check state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }\n\n /* save header structure */\n state.head = head;\n head.done = false;\n return Z_OK;\n}\n\nfunction inflateSetDictionary(strm, dictionary) {\n var dictLength = dictionary.length;\n\n var state;\n var dictid;\n var ret;\n\n /* check state */\n if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n if (state.wrap !== 0 && state.mode !== DICT) {\n return Z_STREAM_ERROR;\n }\n\n /* check for correct dictionary identifier */\n if (state.mode === DICT) {\n dictid = 1; /* adler32(0, null, 0)*/\n /* dictid = adler32(dictid, dictionary, dictLength); */\n dictid = adler32(dictid, dictionary, dictLength, 0);\n if (dictid !== state.check) {\n return Z_DATA_ERROR;\n }\n }\n /* copy dictionary to window using updatewindow(), which will amend the\n existing dictionary if appropriate */\n ret = updatewindow(strm, dictionary, dictLength, dictLength);\n if (ret) {\n state.mode = MEM;\n return Z_MEM_ERROR;\n }\n state.havedict = 1;\n // Tracev((stderr, \"inflate: dictionary set\\n\"));\n return Z_OK;\n}\n\nexports.inflateReset = inflateReset;\nexports.inflateReset2 = inflateReset2;\nexports.inflateResetKeep = inflateResetKeep;\nexports.inflateInit = inflateInit;\nexports.inflateInit2 = inflateInit2;\nexports.inflate = inflate;\nexports.inflateEnd = inflateEnd;\nexports.inflateGetHeader = inflateGetHeader;\nexports.inflateSetDictionary = inflateSetDictionary;\nexports.inflateInfo = 'pako inflate (from Nodeca project)';\n\n/* Not implemented\nexports.inflateCopy = inflateCopy;\nexports.inflateGetDictionary = inflateGetDictionary;\nexports.inflateMark = inflateMark;\nexports.inflatePrime = inflatePrime;\nexports.inflateSync = inflateSync;\nexports.inflateSyncPoint = inflateSyncPoint;\nexports.inflateUndermine = inflateUndermine;\n*/\n", "'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nmodule.exports = {\n\n /* Allowed flush values; see deflate() and inflate() below for details */\n Z_NO_FLUSH: 0,\n Z_PARTIAL_FLUSH: 1,\n Z_SYNC_FLUSH: 2,\n Z_FULL_FLUSH: 3,\n Z_FINISH: 4,\n Z_BLOCK: 5,\n Z_TREES: 6,\n\n /* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\n Z_OK: 0,\n Z_STREAM_END: 1,\n Z_NEED_DICT: 2,\n Z_ERRNO: -1,\n Z_STREAM_ERROR: -2,\n Z_DATA_ERROR: -3,\n //Z_MEM_ERROR: -4,\n Z_BUF_ERROR: -5,\n //Z_VERSION_ERROR: -6,\n\n /* compression levels */\n Z_NO_COMPRESSION: 0,\n Z_BEST_SPEED: 1,\n Z_BEST_COMPRESSION: 9,\n Z_DEFAULT_COMPRESSION: -1,\n\n\n Z_FILTERED: 1,\n Z_HUFFMAN_ONLY: 2,\n Z_RLE: 3,\n Z_FIXED: 4,\n Z_DEFAULT_STRATEGY: 0,\n\n /* Possible values of the data_type field (though see inflate()) */\n Z_BINARY: 0,\n Z_TEXT: 1,\n //Z_ASCII: 1, // = Z_TEXT (deprecated)\n Z_UNKNOWN: 2,\n\n /* The deflate compression method */\n Z_DEFLATED: 8\n //Z_NULL: null // Use -1 or null inline, depending on var type\n};\n", "'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction GZheader() {\n /* true if compressed data believed to be text */\n this.text = 0;\n /* modification time */\n this.time = 0;\n /* extra flags (not used when writing a gzip file) */\n this.xflags = 0;\n /* operating system */\n this.os = 0;\n /* pointer to extra field or Z_NULL if none */\n this.extra = null;\n /* extra field length (valid if extra != Z_NULL) */\n this.extra_len = 0; // Actually, we don't need it in JS,\n // but leave for few code modifications\n\n //\n // Setup limits is not necessary because in js we should not preallocate memory\n // for inflate use constant limit in 65536 bytes\n //\n\n /* space at extra (only when reading header) */\n // this.extra_max = 0;\n /* pointer to zero-terminated file name or Z_NULL */\n this.name = '';\n /* space at name (only when reading header) */\n // this.name_max = 0;\n /* pointer to zero-terminated comment or Z_NULL */\n this.comment = '';\n /* space at comment (only when reading header) */\n // this.comm_max = 0;\n /* true if there was or will be a header crc */\n this.hcrc = 0;\n /* true when done reading gzip header (not used when writing a gzip file) */\n this.done = false;\n}\n\nmodule.exports = GZheader;\n", "'use strict';\n\n\nvar zlib_inflate = require('./zlib/inflate');\nvar utils = require('./utils/common');\nvar strings = require('./utils/strings');\nvar c = require('./zlib/constants');\nvar msg = require('./zlib/messages');\nvar ZStream = require('./zlib/zstream');\nvar GZheader = require('./zlib/gzheader');\n\nvar toString = Object.prototype.toString;\n\n/**\n * class Inflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[inflate]]\n * and [[inflateRaw]].\n **/\n\n/* internal\n * inflate.chunks -> Array\n *\n * Chunks of output data, if [[Inflate#onData]] not overridden.\n **/\n\n/**\n * Inflate.result -> Uint8Array|Array|String\n *\n * Uncompressed result, generated by default [[Inflate#onData]]\n * and [[Inflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you\n * push a chunk with explicit flush (call [[Inflate#push]] with\n * `Z_SYNC_FLUSH` param).\n **/\n\n/**\n * Inflate.err -> Number\n *\n * Error code after inflate finished. 0 (Z_OK) on success.\n * Should be checked if broken data possible.\n **/\n\n/**\n * Inflate.msg -> String\n *\n * Error message, if [[Inflate.err]] != 0\n **/\n\n\n/**\n * new Inflate(options)\n * - options (Object): zlib inflate options.\n *\n * Creates new inflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `windowBits`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw inflate\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n * By default, when no options set, autodetect deflate/gzip data format via\n * wrapper header.\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * var inflate = new pako.Inflate({ level: 3});\n *\n * inflate.push(chunk1, false);\n * inflate.push(chunk2, true); // true -> last chunk\n *\n * if (inflate.err) { throw new Error(inflate.err); }\n *\n * console.log(inflate.result);\n * ```\n **/\nfunction Inflate(options) {\n if (!(this instanceof Inflate)) return new Inflate(options);\n\n this.options = utils.assign({\n chunkSize: 16384,\n windowBits: 0,\n to: ''\n }, options || {});\n\n var opt = this.options;\n\n // Force window size for `raw` data, if not set directly,\n // because we have no header for autodetect.\n if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {\n opt.windowBits = -opt.windowBits;\n if (opt.windowBits === 0) { opt.windowBits = -15; }\n }\n\n // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate\n if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&\n !(options && options.windowBits)) {\n opt.windowBits += 32;\n }\n\n // Gzip header has no info about windows size, we can do autodetect only\n // for deflate. So, if window size not set, force it to max when gzip possible\n if ((opt.windowBits > 15) && (opt.windowBits < 48)) {\n // bit 3 (16) -> gzipped data\n // bit 4 (32) -> autodetect gzip/deflate\n if ((opt.windowBits & 15) === 0) {\n opt.windowBits |= 15;\n }\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new ZStream();\n this.strm.avail_out = 0;\n\n var status = zlib_inflate.inflateInit2(\n this.strm,\n opt.windowBits\n );\n\n if (status !== c.Z_OK) {\n throw new Error(msg[status]);\n }\n\n this.header = new GZheader();\n\n zlib_inflate.inflateGetHeader(this.strm, this.header);\n\n // Setup dictionary\n if (opt.dictionary) {\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n opt.dictionary = strings.string2buf(opt.dictionary);\n } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {\n opt.dictionary = new Uint8Array(opt.dictionary);\n }\n if (opt.raw) { //In raw mode we need to set the dictionary early\n status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary);\n if (status !== c.Z_OK) {\n throw new Error(msg[status]);\n }\n }\n }\n}\n\n/**\n * Inflate#push(data[, mode]) -> Boolean\n * - data (Uint8Array|Array|ArrayBuffer|String): input data\n * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with\n * new output chunks. Returns `true` on success. The last data block must have\n * mode Z_FINISH (or `true`). That will flush internal pending buffers and call\n * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you\n * can use mode Z_SYNC_FLUSH, keeping the decompression context.\n *\n * On fail call [[Inflate#onEnd]] with error code and return false.\n *\n * We strongly recommend to use `Uint8Array` on input for best speed (output\n * format is detected automatically). Also, don't skip last param and always\n * use the same type in your code (boolean or number). That will improve JS speed.\n *\n * For regular `Array`-s make sure all elements are [0..255].\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nInflate.prototype.push = function (data, mode) {\n var strm = this.strm;\n var chunkSize = this.options.chunkSize;\n var dictionary = this.options.dictionary;\n var status, _mode;\n var next_out_utf8, tail, utf8str;\n\n // Flag to properly process Z_BUF_ERROR on testing inflate call\n // when we check that all output data was flushed.\n var allowBufError = false;\n\n if (this.ended) { return false; }\n _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);\n\n // Convert data if needed\n if (typeof data === 'string') {\n // Only binary strings can be decompressed on practice\n strm.input = strings.binstring2buf(data);\n } else if (toString.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n do {\n if (strm.avail_out === 0) {\n strm.output = new utils.Buf8(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */\n\n if (status === c.Z_NEED_DICT && dictionary) {\n status = zlib_inflate.inflateSetDictionary(this.strm, dictionary);\n }\n\n if (status === c.Z_BUF_ERROR && allowBufError === true) {\n status = c.Z_OK;\n allowBufError = false;\n }\n\n if (status !== c.Z_STREAM_END && status !== c.Z_OK) {\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n\n if (strm.next_out) {\n if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {\n\n if (this.options.to === 'string') {\n\n next_out_utf8 = strings.utf8border(strm.output, strm.next_out);\n\n tail = strm.next_out - next_out_utf8;\n utf8str = strings.buf2string(strm.output, next_out_utf8);\n\n // move tail\n strm.next_out = tail;\n strm.avail_out = chunkSize - tail;\n if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }\n\n this.onData(utf8str);\n\n } else {\n this.onData(utils.shrinkBuf(strm.output, strm.next_out));\n }\n }\n }\n\n // When no more input data, we should check that internal inflate buffers\n // are flushed. The only way to do it when avail_out = 0 - run one more\n // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.\n // Here we set flag to process this error properly.\n //\n // NOTE. Deflate does not return error in this case and does not needs such\n // logic.\n if (strm.avail_in === 0 && strm.avail_out === 0) {\n allowBufError = true;\n }\n\n } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);\n\n if (status === c.Z_STREAM_END) {\n _mode = c.Z_FINISH;\n }\n\n // Finalize on the last chunk.\n if (_mode === c.Z_FINISH) {\n status = zlib_inflate.inflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === c.Z_OK;\n }\n\n // callback interim results if Z_SYNC_FLUSH.\n if (_mode === c.Z_SYNC_FLUSH) {\n this.onEnd(c.Z_OK);\n strm.avail_out = 0;\n return true;\n }\n\n return true;\n};\n\n\n/**\n * Inflate#onData(chunk) -> Void\n * - chunk (Uint8Array|Array|String): output data. Type of array depends\n * on js engine support. When string output requested, each chunk\n * will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nInflate.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Inflate#onEnd(status) -> Void\n * - status (Number): inflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called either after you tell inflate that the input stream is\n * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)\n * or if an error happened. By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nInflate.prototype.onEnd = function (status) {\n // On success - join\n if (status === c.Z_OK) {\n if (this.options.to === 'string') {\n // Glue & convert here, until we teach pako to send\n // utf8 aligned strings to onData\n this.result = this.chunks.join('');\n } else {\n this.result = utils.flattenChunks(this.chunks);\n }\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * inflate(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Decompress `data` with inflate/ungzip and `options`. Autodetect\n * format via wrapper header by default. That's why we don't provide\n * separate `ungzip` method.\n *\n * Supported options are:\n *\n * - windowBits\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , input = pako.deflate([1,2,3,4,5,6,7,8,9])\n * , output;\n *\n * try {\n * output = pako.inflate(input);\n * } catch (err)\n * console.log(err);\n * }\n * ```\n **/\nfunction inflate(input, options) {\n var inflator = new Inflate(options);\n\n inflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (inflator.err) { throw inflator.msg || msg[inflator.err]; }\n\n return inflator.result;\n}\n\n\n/**\n * inflateRaw(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * The same as [[inflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction inflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return inflate(input, options);\n}\n\n\n/**\n * ungzip(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Just shortcut to [[inflate]], because it autodetects format\n * by header.content. Done for convenience.\n **/\n\n\nexports.Inflate = Inflate;\nexports.inflate = inflate;\nexports.inflateRaw = inflateRaw;\nexports.ungzip = inflate;\n", "// Top level file is just a mixin of submodules & constants\n'use strict';\n\nvar assign = require('./lib/utils/common').assign;\n\nvar deflate = require('./lib/deflate');\nvar inflate = require('./lib/inflate');\nvar constants = require('./lib/zlib/constants');\n\nvar pako = {};\n\nassign(pako, deflate, inflate, constants);\n\nmodule.exports = pako;\n", "\"use strict\";\nvar USE_TYPEDARRAY = (typeof Uint8Array !== \"undefined\") && (typeof Uint16Array !== \"undefined\") && (typeof Uint32Array !== \"undefined\");\n\nvar pako = require(\"pako\");\nvar utils = require(\"./utils\");\nvar GenericWorker = require(\"./stream/GenericWorker\");\n\nvar ARRAY_TYPE = USE_TYPEDARRAY ? \"uint8array\" : \"array\";\n\nexports.magic = \"\\x08\\x00\";\n\n/**\n * Create a worker that uses pako to inflate/deflate.\n * @constructor\n * @param {String} action the name of the pako function to call : either \"Deflate\" or \"Inflate\".\n * @param {Object} options the options to use when (de)compressing.\n */\nfunction FlateWorker(action, options) {\n GenericWorker.call(this, \"FlateWorker/\" + action);\n\n this._pako = null;\n this._pakoAction = action;\n this._pakoOptions = options;\n // the `meta` object from the last chunk received\n // this allow this worker to pass around metadata\n this.meta = {};\n}\n\nutils.inherits(FlateWorker, GenericWorker);\n\n/**\n * @see GenericWorker.processChunk\n */\nFlateWorker.prototype.processChunk = function (chunk) {\n this.meta = chunk.meta;\n if (this._pako === null) {\n this._createPako();\n }\n this._pako.push(utils.transformTo(ARRAY_TYPE, chunk.data), false);\n};\n\n/**\n * @see GenericWorker.flush\n */\nFlateWorker.prototype.flush = function () {\n GenericWorker.prototype.flush.call(this);\n if (this._pako === null) {\n this._createPako();\n }\n this._pako.push([], true);\n};\n/**\n * @see GenericWorker.cleanUp\n */\nFlateWorker.prototype.cleanUp = function () {\n GenericWorker.prototype.cleanUp.call(this);\n this._pako = null;\n};\n\n/**\n * Create the _pako object.\n * TODO: lazy-loading this object isn't the best solution but it's the\n * quickest. The best solution is to lazy-load the worker list. See also the\n * issue #446.\n */\nFlateWorker.prototype._createPako = function () {\n this._pako = new pako[this._pakoAction]({\n raw: true,\n level: this._pakoOptions.level || -1 // default compression\n });\n var self = this;\n this._pako.onData = function(data) {\n self.push({\n data : data,\n meta : self.meta\n });\n };\n};\n\nexports.compressWorker = function (compressionOptions) {\n return new FlateWorker(\"Deflate\", compressionOptions);\n};\nexports.uncompressWorker = function () {\n return new FlateWorker(\"Inflate\", {});\n};\n", "\"use strict\";\n\nvar GenericWorker = require(\"./stream/GenericWorker\");\n\nexports.STORE = {\n magic: \"\\x00\\x00\",\n compressWorker : function () {\n return new GenericWorker(\"STORE compression\");\n },\n uncompressWorker : function () {\n return new GenericWorker(\"STORE decompression\");\n }\n};\nexports.DEFLATE = require(\"./flate\");\n", "\"use strict\";\nexports.LOCAL_FILE_HEADER = \"PK\\x03\\x04\";\nexports.CENTRAL_FILE_HEADER = \"PK\\x01\\x02\";\nexports.CENTRAL_DIRECTORY_END = \"PK\\x05\\x06\";\nexports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = \"PK\\x06\\x07\";\nexports.ZIP64_CENTRAL_DIRECTORY_END = \"PK\\x06\\x06\";\nexports.DATA_DESCRIPTOR = \"PK\\x07\\x08\";\n", "\"use strict\";\n\nvar utils = require(\"../utils\");\nvar GenericWorker = require(\"../stream/GenericWorker\");\nvar utf8 = require(\"../utf8\");\nvar crc32 = require(\"../crc32\");\nvar signature = require(\"../signature\");\n\n/**\n * Transform an integer into a string in hexadecimal.\n * @private\n * @param {number} dec the number to convert.\n * @param {number} bytes the number of bytes to generate.\n * @returns {string} the result.\n */\nvar decToHex = function(dec, bytes) {\n var hex = \"\", i;\n for (i = 0; i < bytes; i++) {\n hex += String.fromCharCode(dec & 0xff);\n dec = dec >>> 8;\n }\n return hex;\n};\n\n/**\n * Generate the UNIX part of the external file attributes.\n * @param {Object} unixPermissions the unix permissions or null.\n * @param {Boolean} isDir true if the entry is a directory, false otherwise.\n * @return {Number} a 32 bit integer.\n *\n * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute :\n *\n * TTTTsstrwxrwxrwx0000000000ADVSHR\n * ^^^^____________________________ file type, see zipinfo.c (UNX_*)\n * ^^^_________________________ setuid, setgid, sticky\n * ^^^^^^^^^________________ permissions\n * ^^^^^^^^^^______ not used ?\n * ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only\n */\nvar generateUnixExternalFileAttr = function (unixPermissions, isDir) {\n\n var result = unixPermissions;\n if (!unixPermissions) {\n // I can't use octal values in strict mode, hence the hexa.\n // 040775 => 0x41fd\n // 0100664 => 0x81b4\n result = isDir ? 0x41fd : 0x81b4;\n }\n return (result & 0xFFFF) << 16;\n};\n\n/**\n * Generate the DOS part of the external file attributes.\n * @param {Object} dosPermissions the dos permissions or null.\n * @param {Boolean} isDir true if the entry is a directory, false otherwise.\n * @return {Number} a 32 bit integer.\n *\n * Bit 0 Read-Only\n * Bit 1 Hidden\n * Bit 2 System\n * Bit 3 Volume Label\n * Bit 4 Directory\n * Bit 5 Archive\n */\nvar generateDosExternalFileAttr = function (dosPermissions) {\n // the dir flag is already set for compatibility\n return (dosPermissions || 0) & 0x3F;\n};\n\n/**\n * Generate the various parts used in the construction of the final zip file.\n * @param {Object} streamInfo the hash with information about the compressed file.\n * @param {Boolean} streamedContent is the content streamed ?\n * @param {Boolean} streamingEnded is the stream finished ?\n * @param {number} offset the current offset from the start of the zip file.\n * @param {String} platform let's pretend we are this platform (change platform dependents fields)\n * @param {Function} encodeFileName the function to encode the file name / comment.\n * @return {Object} the zip parts.\n */\nvar generateZipParts = function(streamInfo, streamedContent, streamingEnded, offset, platform, encodeFileName) {\n var file = streamInfo[\"file\"],\n compression = streamInfo[\"compression\"],\n useCustomEncoding = encodeFileName !== utf8.utf8encode,\n encodedFileName = utils.transformTo(\"string\", encodeFileName(file.name)),\n utfEncodedFileName = utils.transformTo(\"string\", utf8.utf8encode(file.name)),\n comment = file.comment,\n encodedComment = utils.transformTo(\"string\", encodeFileName(comment)),\n utfEncodedComment = utils.transformTo(\"string\", utf8.utf8encode(comment)),\n useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,\n useUTF8ForComment = utfEncodedComment.length !== comment.length,\n dosTime,\n dosDate,\n extraFields = \"\",\n unicodePathExtraField = \"\",\n unicodeCommentExtraField = \"\",\n dir = file.dir,\n date = file.date;\n\n\n var dataInfo = {\n crc32 : 0,\n compressedSize : 0,\n uncompressedSize : 0\n };\n\n // if the content is streamed, the sizes/crc32 are only available AFTER\n // the end of the stream.\n if (!streamedContent || streamingEnded) {\n dataInfo.crc32 = streamInfo[\"crc32\"];\n dataInfo.compressedSize = streamInfo[\"compressedSize\"];\n dataInfo.uncompressedSize = streamInfo[\"uncompressedSize\"];\n }\n\n var bitflag = 0;\n if (streamedContent) {\n // Bit 3: the sizes/crc32 are set to zero in the local header.\n // The correct values are put in the data descriptor immediately\n // following the compressed data.\n bitflag |= 0x0008;\n }\n if (!useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment)) {\n // Bit 11: Language encoding flag (EFS).\n bitflag |= 0x0800;\n }\n\n\n var extFileAttr = 0;\n var versionMadeBy = 0;\n if (dir) {\n // dos or unix, we set the dos dir flag\n extFileAttr |= 0x00010;\n }\n if(platform === \"UNIX\") {\n versionMadeBy = 0x031E; // UNIX, version 3.0\n extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir);\n } else { // DOS or other, fallback to DOS\n versionMadeBy = 0x0014; // DOS, version 2.0\n extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir);\n }\n\n // date\n // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html\n // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html\n // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html\n\n dosTime = date.getUTCHours();\n dosTime = dosTime << 6;\n dosTime = dosTime | date.getUTCMinutes();\n dosTime = dosTime << 5;\n dosTime = dosTime | date.getUTCSeconds() / 2;\n\n dosDate = date.getUTCFullYear() - 1980;\n dosDate = dosDate << 4;\n dosDate = dosDate | (date.getUTCMonth() + 1);\n dosDate = dosDate << 5;\n dosDate = dosDate | date.getUTCDate();\n\n if (useUTF8ForFileName) {\n // set the unicode path extra field. unzip needs at least one extra\n // field to correctly handle unicode path, so using the path is as good\n // as any other information. This could improve the situation with\n // other archive managers too.\n // This field is usually used without the utf8 flag, with a non\n // unicode path in the header (winrar, winzip). This helps (a bit)\n // with the messy Windows' default compressed folders feature but\n // breaks on p7zip which doesn't seek the unicode path extra field.\n // So for now, UTF-8 everywhere !\n unicodePathExtraField =\n // Version\n decToHex(1, 1) +\n // NameCRC32\n decToHex(crc32(encodedFileName), 4) +\n // UnicodeName\n utfEncodedFileName;\n\n extraFields +=\n // Info-ZIP Unicode Path Extra Field\n \"\\x75\\x70\" +\n // size\n decToHex(unicodePathExtraField.length, 2) +\n // content\n unicodePathExtraField;\n }\n\n if(useUTF8ForComment) {\n\n unicodeCommentExtraField =\n // Version\n decToHex(1, 1) +\n // CommentCRC32\n decToHex(crc32(encodedComment), 4) +\n // UnicodeName\n utfEncodedComment;\n\n extraFields +=\n // Info-ZIP Unicode Path Extra Field\n \"\\x75\\x63\" +\n // size\n decToHex(unicodeCommentExtraField.length, 2) +\n // content\n unicodeCommentExtraField;\n }\n\n var header = \"\";\n\n // version needed to extract\n header += \"\\x0A\\x00\";\n // general purpose bit flag\n header += decToHex(bitflag, 2);\n // compression method\n header += compression.magic;\n // last mod file time\n header += decToHex(dosTime, 2);\n // last mod file date\n header += decToHex(dosDate, 2);\n // crc-32\n header += decToHex(dataInfo.crc32, 4);\n // compressed size\n header += decToHex(dataInfo.compressedSize, 4);\n // uncompressed size\n header += decToHex(dataInfo.uncompressedSize, 4);\n // file name length\n header += decToHex(encodedFileName.length, 2);\n // extra field length\n header += decToHex(extraFields.length, 2);\n\n\n var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields;\n\n var dirRecord = signature.CENTRAL_FILE_HEADER +\n // version made by (00: DOS)\n decToHex(versionMadeBy, 2) +\n // file header (common to file and central directory)\n header +\n // file comment length\n decToHex(encodedComment.length, 2) +\n // disk number start\n \"\\x00\\x00\" +\n // internal file attributes TODO\n \"\\x00\\x00\" +\n // external file attributes\n decToHex(extFileAttr, 4) +\n // relative offset of local header\n decToHex(offset, 4) +\n // file name\n encodedFileName +\n // extra field\n extraFields +\n // file comment\n encodedComment;\n\n return {\n fileRecord: fileRecord,\n dirRecord: dirRecord\n };\n};\n\n/**\n * Generate the EOCD record.\n * @param {Number} entriesCount the number of entries in the zip file.\n * @param {Number} centralDirLength the length (in bytes) of the central dir.\n * @param {Number} localDirLength the length (in bytes) of the local dir.\n * @param {String} comment the zip file comment as a binary string.\n * @param {Function} encodeFileName the function to encode the comment.\n * @return {String} the EOCD record.\n */\nvar generateCentralDirectoryEnd = function (entriesCount, centralDirLength, localDirLength, comment, encodeFileName) {\n var dirEnd = \"\";\n var encodedComment = utils.transformTo(\"string\", encodeFileName(comment));\n\n // end of central dir signature\n dirEnd = signature.CENTRAL_DIRECTORY_END +\n // number of this disk\n \"\\x00\\x00\" +\n // number of the disk with the start of the central directory\n \"\\x00\\x00\" +\n // total number of entries in the central directory on this disk\n decToHex(entriesCount, 2) +\n // total number of entries in the central directory\n decToHex(entriesCount, 2) +\n // size of the central directory 4 bytes\n decToHex(centralDirLength, 4) +\n // offset of start of central directory with respect to the starting disk number\n decToHex(localDirLength, 4) +\n // .ZIP file comment length\n decToHex(encodedComment.length, 2) +\n // .ZIP file comment\n encodedComment;\n\n return dirEnd;\n};\n\n/**\n * Generate data descriptors for a file entry.\n * @param {Object} streamInfo the hash generated by a worker, containing information\n * on the file entry.\n * @return {String} the data descriptors.\n */\nvar generateDataDescriptors = function (streamInfo) {\n var descriptor = \"\";\n descriptor = signature.DATA_DESCRIPTOR +\n // crc-32 4 bytes\n decToHex(streamInfo[\"crc32\"], 4) +\n // compressed size 4 bytes\n decToHex(streamInfo[\"compressedSize\"], 4) +\n // uncompressed size 4 bytes\n decToHex(streamInfo[\"uncompressedSize\"], 4);\n\n return descriptor;\n};\n\n\n/**\n * A worker to concatenate other workers to create a zip file.\n * @param {Boolean} streamFiles `true` to stream the content of the files,\n * `false` to accumulate it.\n * @param {String} comment the comment to use.\n * @param {String} platform the platform to use, \"UNIX\" or \"DOS\".\n * @param {Function} encodeFileName the function to encode file names and comments.\n */\nfunction ZipFileWorker(streamFiles, comment, platform, encodeFileName) {\n GenericWorker.call(this, \"ZipFileWorker\");\n // The number of bytes written so far. This doesn't count accumulated chunks.\n this.bytesWritten = 0;\n // The comment of the zip file\n this.zipComment = comment;\n // The platform \"generating\" the zip file.\n this.zipPlatform = platform;\n // the function to encode file names and comments.\n this.encodeFileName = encodeFileName;\n // Should we stream the content of the files ?\n this.streamFiles = streamFiles;\n // If `streamFiles` is false, we will need to accumulate the content of the\n // files to calculate sizes / crc32 (and write them *before* the content).\n // This boolean indicates if we are accumulating chunks (it will change a lot\n // during the lifetime of this worker).\n this.accumulate = false;\n // The buffer receiving chunks when accumulating content.\n this.contentBuffer = [];\n // The list of generated directory records.\n this.dirRecords = [];\n // The offset (in bytes) from the beginning of the zip file for the current source.\n this.currentSourceOffset = 0;\n // The total number of entries in this zip file.\n this.entriesCount = 0;\n // the name of the file currently being added, null when handling the end of the zip file.\n // Used for the emitted metadata.\n this.currentFile = null;\n\n\n\n this._sources = [];\n}\nutils.inherits(ZipFileWorker, GenericWorker);\n\n/**\n * @see GenericWorker.push\n */\nZipFileWorker.prototype.push = function (chunk) {\n\n var currentFilePercent = chunk.meta.percent || 0;\n var entriesCount = this.entriesCount;\n var remainingFiles = this._sources.length;\n\n if(this.accumulate) {\n this.contentBuffer.push(chunk);\n } else {\n this.bytesWritten += chunk.data.length;\n\n GenericWorker.prototype.push.call(this, {\n data : chunk.data,\n meta : {\n currentFile : this.currentFile,\n percent : entriesCount ? (currentFilePercent + 100 * (entriesCount - remainingFiles - 1)) / entriesCount : 100\n }\n });\n }\n};\n\n/**\n * The worker started a new source (an other worker).\n * @param {Object} streamInfo the streamInfo object from the new source.\n */\nZipFileWorker.prototype.openedSource = function (streamInfo) {\n this.currentSourceOffset = this.bytesWritten;\n this.currentFile = streamInfo[\"file\"].name;\n\n var streamedContent = this.streamFiles && !streamInfo[\"file\"].dir;\n\n // don't stream folders (because they don't have any content)\n if(streamedContent) {\n var record = generateZipParts(streamInfo, streamedContent, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);\n this.push({\n data : record.fileRecord,\n meta : {percent:0}\n });\n } else {\n // we need to wait for the whole file before pushing anything\n this.accumulate = true;\n }\n};\n\n/**\n * The worker finished a source (an other worker).\n * @param {Object} streamInfo the streamInfo object from the finished source.\n */\nZipFileWorker.prototype.closedSource = function (streamInfo) {\n this.accumulate = false;\n var streamedContent = this.streamFiles && !streamInfo[\"file\"].dir;\n var record = generateZipParts(streamInfo, streamedContent, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);\n\n this.dirRecords.push(record.dirRecord);\n if(streamedContent) {\n // after the streamed file, we put data descriptors\n this.push({\n data : generateDataDescriptors(streamInfo),\n meta : {percent:100}\n });\n } else {\n // the content wasn't streamed, we need to push everything now\n // first the file record, then the content\n this.push({\n data : record.fileRecord,\n meta : {percent:0}\n });\n while(this.contentBuffer.length) {\n this.push(this.contentBuffer.shift());\n }\n }\n this.currentFile = null;\n};\n\n/**\n * @see GenericWorker.flush\n */\nZipFileWorker.prototype.flush = function () {\n\n var localDirLength = this.bytesWritten;\n for(var i = 0; i < this.dirRecords.length; i++) {\n this.push({\n data : this.dirRecords[i],\n meta : {percent:100}\n });\n }\n var centralDirLength = this.bytesWritten - localDirLength;\n\n var dirEnd = generateCentralDirectoryEnd(this.dirRecords.length, centralDirLength, localDirLength, this.zipComment, this.encodeFileName);\n\n this.push({\n data : dirEnd,\n meta : {percent:100}\n });\n};\n\n/**\n * Prepare the next source to be read.\n */\nZipFileWorker.prototype.prepareNextSource = function () {\n this.previous = this._sources.shift();\n this.openedSource(this.previous.streamInfo);\n if (this.isPaused) {\n this.previous.pause();\n } else {\n this.previous.resume();\n }\n};\n\n/**\n * @see GenericWorker.registerPrevious\n */\nZipFileWorker.prototype.registerPrevious = function (previous) {\n this._sources.push(previous);\n var self = this;\n\n previous.on(\"data\", function (chunk) {\n self.processChunk(chunk);\n });\n previous.on(\"end\", function () {\n self.closedSource(self.previous.streamInfo);\n if(self._sources.length) {\n self.prepareNextSource();\n } else {\n self.end();\n }\n });\n previous.on(\"error\", function (e) {\n self.error(e);\n });\n return this;\n};\n\n/**\n * @see GenericWorker.resume\n */\nZipFileWorker.prototype.resume = function () {\n if(!GenericWorker.prototype.resume.call(this)) {\n return false;\n }\n\n if (!this.previous && this._sources.length) {\n this.prepareNextSource();\n return true;\n }\n if (!this.previous && !this._sources.length && !this.generatedError) {\n this.end();\n return true;\n }\n};\n\n/**\n * @see GenericWorker.error\n */\nZipFileWorker.prototype.error = function (e) {\n var sources = this._sources;\n if(!GenericWorker.prototype.error.call(this, e)) {\n return false;\n }\n for(var i = 0; i < sources.length; i++) {\n try {\n sources[i].error(e);\n } catch(e) {\n // the `error` exploded, nothing to do\n }\n }\n return true;\n};\n\n/**\n * @see GenericWorker.lock\n */\nZipFileWorker.prototype.lock = function () {\n GenericWorker.prototype.lock.call(this);\n var sources = this._sources;\n for(var i = 0; i < sources.length; i++) {\n sources[i].lock();\n }\n};\n\nmodule.exports = ZipFileWorker;\n", "\"use strict\";\n\nvar compressions = require(\"../compressions\");\nvar ZipFileWorker = require(\"./ZipFileWorker\");\n\n/**\n * Find the compression to use.\n * @param {String} fileCompression the compression defined at the file level, if any.\n * @param {String} zipCompression the compression defined at the load() level.\n * @return {Object} the compression object to use.\n */\nvar getCompression = function (fileCompression, zipCompression) {\n\n var compressionName = fileCompression || zipCompression;\n var compression = compressions[compressionName];\n if (!compression) {\n throw new Error(compressionName + \" is not a valid compression method !\");\n }\n return compression;\n};\n\n/**\n * Create a worker to generate a zip file.\n * @param {JSZip} zip the JSZip instance at the right root level.\n * @param {Object} options to generate the zip file.\n * @param {String} comment the comment to use.\n */\nexports.generateWorker = function (zip, options, comment) {\n\n var zipFileWorker = new ZipFileWorker(options.streamFiles, comment, options.platform, options.encodeFileName);\n var entriesCount = 0;\n try {\n\n zip.forEach(function (relativePath, file) {\n entriesCount++;\n var compression = getCompression(file.options.compression, options.compression);\n var compressionOptions = file.options.compressionOptions || options.compressionOptions || {};\n var dir = file.dir, date = file.date;\n\n file._compressWorker(compression, compressionOptions)\n .withStreamInfo(\"file\", {\n name : relativePath,\n dir : dir,\n date : date,\n comment : file.comment || \"\",\n unixPermissions : file.unixPermissions,\n dosPermissions : file.dosPermissions\n })\n .pipe(zipFileWorker);\n });\n zipFileWorker.entriesCount = entriesCount;\n } catch (e) {\n zipFileWorker.error(e);\n }\n\n return zipFileWorker;\n};\n", "\"use strict\";\n\nvar utils = require(\"../utils\");\nvar GenericWorker = require(\"../stream/GenericWorker\");\n\n/**\n * A worker that use a nodejs stream as source.\n * @constructor\n * @param {String} filename the name of the file entry for this stream.\n * @param {Readable} stream the nodejs stream.\n */\nfunction NodejsStreamInputAdapter(filename, stream) {\n GenericWorker.call(this, \"Nodejs stream input adapter for \" + filename);\n this._upstreamEnded = false;\n this._bindStream(stream);\n}\n\nutils.inherits(NodejsStreamInputAdapter, GenericWorker);\n\n/**\n * Prepare the stream and bind the callbacks on it.\n * Do this ASAP on node 0.10 ! A lazy binding doesn't always work.\n * @param {Stream} stream the nodejs stream to use.\n */\nNodejsStreamInputAdapter.prototype._bindStream = function (stream) {\n var self = this;\n this._stream = stream;\n stream.pause();\n stream\n .on(\"data\", function (chunk) {\n self.push({\n data: chunk,\n meta : {\n percent : 0\n }\n });\n })\n .on(\"error\", function (e) {\n if(self.isPaused) {\n this.generatedError = e;\n } else {\n self.error(e);\n }\n })\n .on(\"end\", function () {\n if(self.isPaused) {\n self._upstreamEnded = true;\n } else {\n self.end();\n }\n });\n};\nNodejsStreamInputAdapter.prototype.pause = function () {\n if(!GenericWorker.prototype.pause.call(this)) {\n return false;\n }\n this._stream.pause();\n return true;\n};\nNodejsStreamInputAdapter.prototype.resume = function () {\n if(!GenericWorker.prototype.resume.call(this)) {\n return false;\n }\n\n if(this._upstreamEnded) {\n this.end();\n } else {\n this._stream.resume();\n }\n\n return true;\n};\n\nmodule.exports = NodejsStreamInputAdapter;\n", "\"use strict\";\nvar utf8 = require(\"./utf8\");\nvar utils = require(\"./utils\");\nvar GenericWorker = require(\"./stream/GenericWorker\");\nvar StreamHelper = require(\"./stream/StreamHelper\");\nvar defaults = require(\"./defaults\");\nvar CompressedObject = require(\"./compressedObject\");\nvar ZipObject = require(\"./zipObject\");\nvar generate = require(\"./generate\");\nvar nodejsUtils = require(\"./nodejsUtils\");\nvar NodejsStreamInputAdapter = require(\"./nodejs/NodejsStreamInputAdapter\");\n\n\n/**\n * Add a file in the current folder.\n * @private\n * @param {string} name the name of the file\n * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file\n * @param {Object} originalOptions the options of the file\n * @return {Object} the new file.\n */\nvar fileAdd = function(name, data, originalOptions) {\n // be sure sub folders exist\n var dataType = utils.getTypeOf(data),\n parent;\n\n\n /*\n * Correct options.\n */\n\n var o = utils.extend(originalOptions || {}, defaults);\n o.date = o.date || new Date();\n if (o.compression !== null) {\n o.compression = o.compression.toUpperCase();\n }\n\n if (typeof o.unixPermissions === \"string\") {\n o.unixPermissions = parseInt(o.unixPermissions, 8);\n }\n\n // UNX_IFDIR 0040000 see zipinfo.c\n if (o.unixPermissions && (o.unixPermissions & 0x4000)) {\n o.dir = true;\n }\n // Bit 4 Directory\n if (o.dosPermissions && (o.dosPermissions & 0x0010)) {\n o.dir = true;\n }\n\n if (o.dir) {\n name = forceTrailingSlash(name);\n }\n if (o.createFolders && (parent = parentFolder(name))) {\n folderAdd.call(this, parent, true);\n }\n\n var isUnicodeString = dataType === \"string\" && o.binary === false && o.base64 === false;\n if (!originalOptions || typeof originalOptions.binary === \"undefined\") {\n o.binary = !isUnicodeString;\n }\n\n\n var isCompressedEmpty = (data instanceof CompressedObject) && data.uncompressedSize === 0;\n\n if (isCompressedEmpty || o.dir || !data || data.length === 0) {\n o.base64 = false;\n o.binary = true;\n data = \"\";\n o.compression = \"STORE\";\n dataType = \"string\";\n }\n\n /*\n * Convert content to fit.\n */\n\n var zipObjectContent = null;\n if (data instanceof CompressedObject || data instanceof GenericWorker) {\n zipObjectContent = data;\n } else if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {\n zipObjectContent = new NodejsStreamInputAdapter(name, data);\n } else {\n zipObjectContent = utils.prepareContent(name, data, o.binary, o.optimizedBinaryString, o.base64);\n }\n\n var object = new ZipObject(name, zipObjectContent, o);\n this.files[name] = object;\n /*\n TODO: we can't throw an exception because we have async promises\n (we can have a promise of a Date() for example) but returning a\n promise is useless because file(name, data) returns the JSZip\n object for chaining. Should we break that to allow the user\n to catch the error ?\n\n return external.Promise.resolve(zipObjectContent)\n .then(function () {\n return object;\n });\n */\n};\n\n/**\n * Find the parent folder of the path.\n * @private\n * @param {string} path the path to use\n * @return {string} the parent folder, or \"\"\n */\nvar parentFolder = function (path) {\n if (path.slice(-1) === \"/\") {\n path = path.substring(0, path.length - 1);\n }\n var lastSlash = path.lastIndexOf(\"/\");\n return (lastSlash > 0) ? path.substring(0, lastSlash) : \"\";\n};\n\n/**\n * Returns the path with a slash at the end.\n * @private\n * @param {String} path the path to check.\n * @return {String} the path with a trailing slash.\n */\nvar forceTrailingSlash = function(path) {\n // Check the name ends with a /\n if (path.slice(-1) !== \"/\") {\n path += \"/\"; // IE doesn't like substr(-1)\n }\n return path;\n};\n\n/**\n * Add a (sub) folder in the current folder.\n * @private\n * @param {string} name the folder's name\n * @param {boolean=} [createFolders] If true, automatically create sub\n * folders. Defaults to false.\n * @return {Object} the new folder.\n */\nvar folderAdd = function(name, createFolders) {\n createFolders = (typeof createFolders !== \"undefined\") ? createFolders : defaults.createFolders;\n\n name = forceTrailingSlash(name);\n\n // Does this folder already exist?\n if (!this.files[name]) {\n fileAdd.call(this, name, null, {\n dir: true,\n createFolders: createFolders\n });\n }\n return this.files[name];\n};\n\n/**\n* Cross-window, cross-Node-context regular expression detection\n* @param {Object} object Anything\n* @return {Boolean} true if the object is a regular expression,\n* false otherwise\n*/\nfunction isRegExp(object) {\n return Object.prototype.toString.call(object) === \"[object RegExp]\";\n}\n\n// return the actual prototype of JSZip\nvar out = {\n /**\n * @see loadAsync\n */\n load: function() {\n throw new Error(\"This method has been removed in JSZip 3.0, please check the upgrade guide.\");\n },\n\n\n /**\n * Call a callback function for each entry at this folder level.\n * @param {Function} cb the callback function:\n * function (relativePath, file) {...}\n * It takes 2 arguments : the relative path and the file.\n */\n forEach: function(cb) {\n var filename, relativePath, file;\n // ignore warning about unwanted properties because this.files is a null prototype object\n /* eslint-disable-next-line guard-for-in */\n for (filename in this.files) {\n file = this.files[filename];\n relativePath = filename.slice(this.root.length, filename.length);\n if (relativePath && filename.slice(0, this.root.length) === this.root) { // the file is in the current root\n cb(relativePath, file); // TODO reverse the parameters ? need to be clean AND consistent with the filter search fn...\n }\n }\n },\n\n /**\n * Filter nested files/folders with the specified function.\n * @param {Function} search the predicate to use :\n * function (relativePath, file) {...}\n * It takes 2 arguments : the relative path and the file.\n * @return {Array} An array of matching elements.\n */\n filter: function(search) {\n var result = [];\n this.forEach(function (relativePath, entry) {\n if (search(relativePath, entry)) { // the file matches the function\n result.push(entry);\n }\n\n });\n return result;\n },\n\n /**\n * Add a file to the zip file, or search a file.\n * @param {string|RegExp} name The name of the file to add (if data is defined),\n * the name of the file to find (if no data) or a regex to match files.\n * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded\n * @param {Object} o File options\n * @return {JSZip|Object|Array} this JSZip object (when adding a file),\n * a file (when searching by string) or an array of files (when searching by regex).\n */\n file: function(name, data, o) {\n if (arguments.length === 1) {\n if (isRegExp(name)) {\n var regexp = name;\n return this.filter(function(relativePath, file) {\n return !file.dir && regexp.test(relativePath);\n });\n }\n else { // text\n var obj = this.files[this.root + name];\n if (obj && !obj.dir) {\n return obj;\n } else {\n return null;\n }\n }\n }\n else { // more than one argument : we have data !\n name = this.root + name;\n fileAdd.call(this, name, data, o);\n }\n return this;\n },\n\n /**\n * Add a directory to the zip file, or search.\n * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders.\n * @return {JSZip} an object with the new directory as the root, or an array containing matching folders.\n */\n folder: function(arg) {\n if (!arg) {\n return this;\n }\n\n if (isRegExp(arg)) {\n return this.filter(function(relativePath, file) {\n return file.dir && arg.test(relativePath);\n });\n }\n\n // else, name is a new folder\n var name = this.root + arg;\n var newFolder = folderAdd.call(this, name);\n\n // Allow chaining by returning a new object with this folder as the root\n var ret = this.clone();\n ret.root = newFolder.name;\n return ret;\n },\n\n /**\n * Delete a file, or a directory and all sub-files, from the zip\n * @param {string} name the name of the file to delete\n * @return {JSZip} this JSZip object\n */\n remove: function(name) {\n name = this.root + name;\n var file = this.files[name];\n if (!file) {\n // Look for any folders\n if (name.slice(-1) !== \"/\") {\n name += \"/\";\n }\n file = this.files[name];\n }\n\n if (file && !file.dir) {\n // file\n delete this.files[name];\n } else {\n // maybe a folder, delete recursively\n var kids = this.filter(function(relativePath, file) {\n return file.name.slice(0, name.length) === name;\n });\n for (var i = 0; i < kids.length; i++) {\n delete this.files[kids[i].name];\n }\n }\n\n return this;\n },\n\n /**\n * @deprecated This method has been removed in JSZip 3.0, please check the upgrade guide.\n */\n generate: function() {\n throw new Error(\"This method has been removed in JSZip 3.0, please check the upgrade guide.\");\n },\n\n /**\n * Generate the complete zip file as an internal stream.\n * @param {Object} options the options to generate the zip file :\n * - compression, \"STORE\" by default.\n * - type, \"base64\" by default. Values are : string, base64, uint8array, arraybuffer, blob.\n * @return {StreamHelper} the streamed zip file.\n */\n generateInternalStream: function(options) {\n var worker, opts = {};\n try {\n opts = utils.extend(options || {}, {\n streamFiles: false,\n compression: \"STORE\",\n compressionOptions : null,\n type: \"\",\n platform: \"DOS\",\n comment: null,\n mimeType: \"application/zip\",\n encodeFileName: utf8.utf8encode\n });\n\n opts.type = opts.type.toLowerCase();\n opts.compression = opts.compression.toUpperCase();\n\n // \"binarystring\" is preferred but the internals use \"string\".\n if(opts.type === \"binarystring\") {\n opts.type = \"string\";\n }\n\n if (!opts.type) {\n throw new Error(\"No output type specified.\");\n }\n\n utils.checkSupport(opts.type);\n\n // accept nodejs `process.platform`\n if(\n opts.platform === \"darwin\" ||\n opts.platform === \"freebsd\" ||\n opts.platform === \"linux\" ||\n opts.platform === \"sunos\"\n ) {\n opts.platform = \"UNIX\";\n }\n if (opts.platform === \"win32\") {\n opts.platform = \"DOS\";\n }\n\n var comment = opts.comment || this.comment || \"\";\n worker = generate.generateWorker(this, opts, comment);\n } catch (e) {\n worker = new GenericWorker(\"error\");\n worker.error(e);\n }\n return new StreamHelper(worker, opts.type || \"string\", opts.mimeType);\n },\n /**\n * Generate the complete zip file asynchronously.\n * @see generateInternalStream\n */\n generateAsync: function(options, onUpdate) {\n return this.generateInternalStream(options).accumulate(onUpdate);\n },\n /**\n * Generate the complete zip file asynchronously.\n * @see generateInternalStream\n */\n generateNodeStream: function(options, onUpdate) {\n options = options || {};\n if (!options.type) {\n options.type = \"nodebuffer\";\n }\n return this.generateInternalStream(options).toNodejsStream(onUpdate);\n }\n};\nmodule.exports = out;\n", "\"use strict\";\nvar utils = require(\"../utils\");\n\nfunction DataReader(data) {\n this.data = data; // type : see implementation\n this.length = data.length;\n this.index = 0;\n this.zero = 0;\n}\nDataReader.prototype = {\n /**\n * Check that the offset will not go too far.\n * @param {string} offset the additional offset to check.\n * @throws {Error} an Error if the offset is out of bounds.\n */\n checkOffset: function(offset) {\n this.checkIndex(this.index + offset);\n },\n /**\n * Check that the specified index will not be too far.\n * @param {string} newIndex the index to check.\n * @throws {Error} an Error if the index is out of bounds.\n */\n checkIndex: function(newIndex) {\n if (this.length < this.zero + newIndex || newIndex < 0) {\n throw new Error(\"End of data reached (data length = \" + this.length + \", asked index = \" + (newIndex) + \"). Corrupted zip ?\");\n }\n },\n /**\n * Change the index.\n * @param {number} newIndex The new index.\n * @throws {Error} if the new index is out of the data.\n */\n setIndex: function(newIndex) {\n this.checkIndex(newIndex);\n this.index = newIndex;\n },\n /**\n * Skip the next n bytes.\n * @param {number} n the number of bytes to skip.\n * @throws {Error} if the new index is out of the data.\n */\n skip: function(n) {\n this.setIndex(this.index + n);\n },\n /**\n * Get the byte at the specified index.\n * @param {number} i the index to use.\n * @return {number} a byte.\n */\n byteAt: function() {\n // see implementations\n },\n /**\n * Get the next number with a given byte size.\n * @param {number} size the number of bytes to read.\n * @return {number} the corresponding number.\n */\n readInt: function(size) {\n var result = 0,\n i;\n this.checkOffset(size);\n for (i = this.index + size - 1; i >= this.index; i--) {\n result = (result << 8) + this.byteAt(i);\n }\n this.index += size;\n return result;\n },\n /**\n * Get the next string with a given byte size.\n * @param {number} size the number of bytes to read.\n * @return {string} the corresponding string.\n */\n readString: function(size) {\n return utils.transformTo(\"string\", this.readData(size));\n },\n /**\n * Get raw data without conversion, <size> bytes.\n * @param {number} size the number of bytes to read.\n * @return {Object} the raw data, implementation specific.\n */\n readData: function() {\n // see implementations\n },\n /**\n * Find the last occurrence of a zip signature (4 bytes).\n * @param {string} sig the signature to find.\n * @return {number} the index of the last occurrence, -1 if not found.\n */\n lastIndexOfSignature: function() {\n // see implementations\n },\n /**\n * Read the signature (4 bytes) at the current position and compare it with sig.\n * @param {string} sig the expected signature\n * @return {boolean} true if the signature matches, false otherwise.\n */\n readAndCheckSignature: function() {\n // see implementations\n },\n /**\n * Get the next date.\n * @return {Date} the date.\n */\n readDate: function() {\n var dostime = this.readInt(4);\n return new Date(Date.UTC(\n ((dostime >> 25) & 0x7f) + 1980, // year\n ((dostime >> 21) & 0x0f) - 1, // month\n (dostime >> 16) & 0x1f, // day\n (dostime >> 11) & 0x1f, // hour\n (dostime >> 5) & 0x3f, // minute\n (dostime & 0x1f) << 1)); // second\n }\n};\nmodule.exports = DataReader;\n", "\"use strict\";\nvar DataReader = require(\"./DataReader\");\nvar utils = require(\"../utils\");\n\nfunction ArrayReader(data) {\n DataReader.call(this, data);\n for(var i = 0; i < this.data.length; i++) {\n data[i] = data[i] & 0xFF;\n }\n}\nutils.inherits(ArrayReader, DataReader);\n/**\n * @see DataReader.byteAt\n */\nArrayReader.prototype.byteAt = function(i) {\n return this.data[this.zero + i];\n};\n/**\n * @see DataReader.lastIndexOfSignature\n */\nArrayReader.prototype.lastIndexOfSignature = function(sig) {\n var sig0 = sig.charCodeAt(0),\n sig1 = sig.charCodeAt(1),\n sig2 = sig.charCodeAt(2),\n sig3 = sig.charCodeAt(3);\n for (var i = this.length - 4; i >= 0; --i) {\n if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {\n return i - this.zero;\n }\n }\n\n return -1;\n};\n/**\n * @see DataReader.readAndCheckSignature\n */\nArrayReader.prototype.readAndCheckSignature = function (sig) {\n var sig0 = sig.charCodeAt(0),\n sig1 = sig.charCodeAt(1),\n sig2 = sig.charCodeAt(2),\n sig3 = sig.charCodeAt(3),\n data = this.readData(4);\n return sig0 === data[0] && sig1 === data[1] && sig2 === data[2] && sig3 === data[3];\n};\n/**\n * @see DataReader.readData\n */\nArrayReader.prototype.readData = function(size) {\n this.checkOffset(size);\n if(size === 0) {\n return [];\n }\n var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);\n this.index += size;\n return result;\n};\nmodule.exports = ArrayReader;\n", "\"use strict\";\nvar DataReader = require(\"./DataReader\");\nvar utils = require(\"../utils\");\n\nfunction StringReader(data) {\n DataReader.call(this, data);\n}\nutils.inherits(StringReader, DataReader);\n/**\n * @see DataReader.byteAt\n */\nStringReader.prototype.byteAt = function(i) {\n return this.data.charCodeAt(this.zero + i);\n};\n/**\n * @see DataReader.lastIndexOfSignature\n */\nStringReader.prototype.lastIndexOfSignature = function(sig) {\n return this.data.lastIndexOf(sig) - this.zero;\n};\n/**\n * @see DataReader.readAndCheckSignature\n */\nStringReader.prototype.readAndCheckSignature = function (sig) {\n var data = this.readData(4);\n return sig === data;\n};\n/**\n * @see DataReader.readData\n */\nStringReader.prototype.readData = function(size) {\n this.checkOffset(size);\n // this will work because the constructor applied the \"& 0xff\" mask.\n var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);\n this.index += size;\n return result;\n};\nmodule.exports = StringReader;\n", "\"use strict\";\nvar ArrayReader = require(\"./ArrayReader\");\nvar utils = require(\"../utils\");\n\nfunction Uint8ArrayReader(data) {\n ArrayReader.call(this, data);\n}\nutils.inherits(Uint8ArrayReader, ArrayReader);\n/**\n * @see DataReader.readData\n */\nUint8ArrayReader.prototype.readData = function(size) {\n this.checkOffset(size);\n if(size === 0) {\n // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].\n return new Uint8Array(0);\n }\n var result = this.data.subarray(this.zero + this.index, this.zero + this.index + size);\n this.index += size;\n return result;\n};\nmodule.exports = Uint8ArrayReader;\n", "\"use strict\";\nvar Uint8ArrayReader = require(\"./Uint8ArrayReader\");\nvar utils = require(\"../utils\");\n\nfunction NodeBufferReader(data) {\n Uint8ArrayReader.call(this, data);\n}\nutils.inherits(NodeBufferReader, Uint8ArrayReader);\n\n/**\n * @see DataReader.readData\n */\nNodeBufferReader.prototype.readData = function(size) {\n this.checkOffset(size);\n var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);\n this.index += size;\n return result;\n};\nmodule.exports = NodeBufferReader;\n", "\"use strict\";\n\nvar utils = require(\"../utils\");\nvar support = require(\"../support\");\nvar ArrayReader = require(\"./ArrayReader\");\nvar StringReader = require(\"./StringReader\");\nvar NodeBufferReader = require(\"./NodeBufferReader\");\nvar Uint8ArrayReader = require(\"./Uint8ArrayReader\");\n\n/**\n * Create a reader adapted to the data.\n * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data to read.\n * @return {DataReader} the data reader.\n */\nmodule.exports = function (data) {\n var type = utils.getTypeOf(data);\n utils.checkSupport(type);\n if (type === \"string\" && !support.uint8array) {\n return new StringReader(data);\n }\n if (type === \"nodebuffer\") {\n return new NodeBufferReader(data);\n }\n if (support.uint8array) {\n return new Uint8ArrayReader(utils.transformTo(\"uint8array\", data));\n }\n return new ArrayReader(utils.transformTo(\"array\", data));\n};\n", "\"use strict\";\nvar readerFor = require(\"./reader/readerFor\");\nvar utils = require(\"./utils\");\nvar CompressedObject = require(\"./compressedObject\");\nvar crc32fn = require(\"./crc32\");\nvar utf8 = require(\"./utf8\");\nvar compressions = require(\"./compressions\");\nvar support = require(\"./support\");\n\nvar MADE_BY_DOS = 0x00;\nvar MADE_BY_UNIX = 0x03;\n\n/**\n * Find a compression registered in JSZip.\n * @param {string} compressionMethod the method magic to find.\n * @return {Object|null} the JSZip compression object, null if none found.\n */\nvar findCompression = function(compressionMethod) {\n for (var method in compressions) {\n if (!Object.prototype.hasOwnProperty.call(compressions, method)) {\n continue;\n }\n if (compressions[method].magic === compressionMethod) {\n return compressions[method];\n }\n }\n return null;\n};\n\n// class ZipEntry {{{\n/**\n * An entry in the zip file.\n * @constructor\n * @param {Object} options Options of the current file.\n * @param {Object} loadOptions Options for loading the stream.\n */\nfunction ZipEntry(options, loadOptions) {\n this.options = options;\n this.loadOptions = loadOptions;\n}\nZipEntry.prototype = {\n /**\n * say if the file is encrypted.\n * @return {boolean} true if the file is encrypted, false otherwise.\n */\n isEncrypted: function() {\n // bit 1 is set\n return (this.bitFlag & 0x0001) === 0x0001;\n },\n /**\n * say if the file has utf-8 filename/comment.\n * @return {boolean} true if the filename/comment is in utf-8, false otherwise.\n */\n useUTF8: function() {\n // bit 11 is set\n return (this.bitFlag & 0x0800) === 0x0800;\n },\n /**\n * Read the local part of a zip file and add the info in this object.\n * @param {DataReader} reader the reader to use.\n */\n readLocalPart: function(reader) {\n var compression, localExtraFieldsLength;\n\n // we already know everything from the central dir !\n // If the central dir data are false, we are doomed.\n // On the bright side, the local part is scary : zip64, data descriptors, both, etc.\n // The less data we get here, the more reliable this should be.\n // Let's skip the whole header and dash to the data !\n reader.skip(22);\n // in some zip created on windows, the filename stored in the central dir contains \\ instead of /.\n // Strangely, the filename here is OK.\n // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes\n // or APPNOTE#4.4.17.1, \"All slashes MUST be forward slashes '/'\") but there are a lot of bad zip generators...\n // Search \"unzip mismatching \"local\" filename continuing with \"central\" filename version\" on\n // the internet.\n //\n // I think I see the logic here : the central directory is used to display\n // content and the local directory is used to extract the files. Mixing / and \\\n // may be used to display \\ to windows users and use / when extracting the files.\n // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394\n this.fileNameLength = reader.readInt(2);\n localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir\n // the fileName is stored as binary data, the handleUTF8 method will take care of the encoding.\n this.fileName = reader.readData(this.fileNameLength);\n reader.skip(localExtraFieldsLength);\n\n if (this.compressedSize === -1 || this.uncompressedSize === -1) {\n throw new Error(\"Bug or corrupted zip : didn't get enough information from the central directory \" + \"(compressedSize === -1 || uncompressedSize === -1)\");\n }\n\n compression = findCompression(this.compressionMethod);\n if (compression === null) { // no compression found\n throw new Error(\"Corrupted zip : compression \" + utils.pretty(this.compressionMethod) + \" unknown (inner file : \" + utils.transformTo(\"string\", this.fileName) + \")\");\n }\n this.decompressed = new CompressedObject(this.compressedSize, this.uncompressedSize, this.crc32, compression, reader.readData(this.compressedSize));\n },\n\n /**\n * Read the central part of a zip file and add the info in this object.\n * @param {DataReader} reader the reader to use.\n */\n readCentralPart: function(reader) {\n this.versionMadeBy = reader.readInt(2);\n reader.skip(2);\n // this.versionNeeded = reader.readInt(2);\n this.bitFlag = reader.readInt(2);\n this.compressionMethod = reader.readString(2);\n this.date = reader.readDate();\n this.crc32 = reader.readInt(4);\n this.compressedSize = reader.readInt(4);\n this.uncompressedSize = reader.readInt(4);\n var fileNameLength = reader.readInt(2);\n this.extraFieldsLength = reader.readInt(2);\n this.fileCommentLength = reader.readInt(2);\n this.diskNumberStart = reader.readInt(2);\n this.internalFileAttributes = reader.readInt(2);\n this.externalFileAttributes = reader.readInt(4);\n this.localHeaderOffset = reader.readInt(4);\n\n if (this.isEncrypted()) {\n throw new Error(\"Encrypted zip are not supported\");\n }\n\n // will be read in the local part, see the comments there\n reader.skip(fileNameLength);\n this.readExtraFields(reader);\n this.parseZIP64ExtraField(reader);\n this.fileComment = reader.readData(this.fileCommentLength);\n },\n\n /**\n * Parse the external file attributes and get the unix/dos permissions.\n */\n processAttributes: function () {\n this.unixPermissions = null;\n this.dosPermissions = null;\n var madeBy = this.versionMadeBy >> 8;\n\n // Check if we have the DOS directory flag set.\n // We look for it in the DOS and UNIX permissions\n // but some unknown platform could set it as a compatibility flag.\n this.dir = this.externalFileAttributes & 0x0010 ? true : false;\n\n if(madeBy === MADE_BY_DOS) {\n // first 6 bits (0 to 5)\n this.dosPermissions = this.externalFileAttributes & 0x3F;\n }\n\n if(madeBy === MADE_BY_UNIX) {\n this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF;\n // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8);\n }\n\n // fail safe : if the name ends with a / it probably means a folder\n if (!this.dir && this.fileNameStr.slice(-1) === \"/\") {\n this.dir = true;\n }\n },\n\n /**\n * Parse the ZIP64 extra field and merge the info in the current ZipEntry.\n * @param {DataReader} reader the reader to use.\n */\n parseZIP64ExtraField: function() {\n if (!this.extraFields[0x0001]) {\n return;\n }\n\n // should be something, preparing the extra reader\n var extraReader = readerFor(this.extraFields[0x0001].value);\n\n // I really hope that these 64bits integer can fit in 32 bits integer, because js\n // won't let us have more.\n if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {\n this.uncompressedSize = extraReader.readInt(8);\n }\n if (this.compressedSize === utils.MAX_VALUE_32BITS) {\n this.compressedSize = extraReader.readInt(8);\n }\n if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {\n this.localHeaderOffset = extraReader.readInt(8);\n }\n if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {\n this.diskNumberStart = extraReader.readInt(4);\n }\n },\n /**\n * Read the central part of a zip file and add the info in this object.\n * @param {DataReader} reader the reader to use.\n */\n readExtraFields: function(reader) {\n var end = reader.index + this.extraFieldsLength,\n extraFieldId,\n extraFieldLength,\n extraFieldValue;\n\n if (!this.extraFields) {\n this.extraFields = {};\n }\n\n while (reader.index + 4 < end) {\n extraFieldId = reader.readInt(2);\n extraFieldLength = reader.readInt(2);\n extraFieldValue = reader.readData(extraFieldLength);\n\n this.extraFields[extraFieldId] = {\n id: extraFieldId,\n length: extraFieldLength,\n value: extraFieldValue\n };\n }\n\n reader.setIndex(end);\n },\n /**\n * Apply an UTF8 transformation if needed.\n */\n handleUTF8: function() {\n var decodeParamType = support.uint8array ? \"uint8array\" : \"array\";\n if (this.useUTF8()) {\n this.fileNameStr = utf8.utf8decode(this.fileName);\n this.fileCommentStr = utf8.utf8decode(this.fileComment);\n } else {\n var upath = this.findExtraFieldUnicodePath();\n if (upath !== null) {\n this.fileNameStr = upath;\n } else {\n // ASCII text or unsupported code page\n var fileNameByteArray = utils.transformTo(decodeParamType, this.fileName);\n this.fileNameStr = this.loadOptions.decodeFileName(fileNameByteArray);\n }\n\n var ucomment = this.findExtraFieldUnicodeComment();\n if (ucomment !== null) {\n this.fileCommentStr = ucomment;\n } else {\n // ASCII text or unsupported code page\n var commentByteArray = utils.transformTo(decodeParamType, this.fileComment);\n this.fileCommentStr = this.loadOptions.decodeFileName(commentByteArray);\n }\n }\n },\n\n /**\n * Find the unicode path declared in the extra field, if any.\n * @return {String} the unicode path, null otherwise.\n */\n findExtraFieldUnicodePath: function() {\n var upathField = this.extraFields[0x7075];\n if (upathField) {\n var extraReader = readerFor(upathField.value);\n\n // wrong version\n if (extraReader.readInt(1) !== 1) {\n return null;\n }\n\n // the crc of the filename changed, this field is out of date.\n if (crc32fn(this.fileName) !== extraReader.readInt(4)) {\n return null;\n }\n\n return utf8.utf8decode(extraReader.readData(upathField.length - 5));\n }\n return null;\n },\n\n /**\n * Find the unicode comment declared in the extra field, if any.\n * @return {String} the unicode comment, null otherwise.\n */\n findExtraFieldUnicodeComment: function() {\n var ucommentField = this.extraFields[0x6375];\n if (ucommentField) {\n var extraReader = readerFor(ucommentField.value);\n\n // wrong version\n if (extraReader.readInt(1) !== 1) {\n return null;\n }\n\n // the crc of the comment changed, this field is out of date.\n if (crc32fn(this.fileComment) !== extraReader.readInt(4)) {\n return null;\n }\n\n return utf8.utf8decode(extraReader.readData(ucommentField.length - 5));\n }\n return null;\n }\n};\nmodule.exports = ZipEntry;\n", "\"use strict\";\nvar readerFor = require(\"./reader/readerFor\");\nvar utils = require(\"./utils\");\nvar sig = require(\"./signature\");\nvar ZipEntry = require(\"./zipEntry\");\nvar support = require(\"./support\");\n// class ZipEntries {{{\n/**\n * All the entries in the zip file.\n * @constructor\n * @param {Object} loadOptions Options for loading the stream.\n */\nfunction ZipEntries(loadOptions) {\n this.files = [];\n this.loadOptions = loadOptions;\n}\nZipEntries.prototype = {\n /**\n * Check that the reader is on the specified signature.\n * @param {string} expectedSignature the expected signature.\n * @throws {Error} if it is an other signature.\n */\n checkSignature: function(expectedSignature) {\n if (!this.reader.readAndCheckSignature(expectedSignature)) {\n this.reader.index -= 4;\n var signature = this.reader.readString(4);\n throw new Error(\"Corrupted zip or bug: unexpected signature \" + \"(\" + utils.pretty(signature) + \", expected \" + utils.pretty(expectedSignature) + \")\");\n }\n },\n /**\n * Check if the given signature is at the given index.\n * @param {number} askedIndex the index to check.\n * @param {string} expectedSignature the signature to expect.\n * @return {boolean} true if the signature is here, false otherwise.\n */\n isSignature: function(askedIndex, expectedSignature) {\n var currentIndex = this.reader.index;\n this.reader.setIndex(askedIndex);\n var signature = this.reader.readString(4);\n var result = signature === expectedSignature;\n this.reader.setIndex(currentIndex);\n return result;\n },\n /**\n * Read the end of the central directory.\n */\n readBlockEndOfCentral: function() {\n this.diskNumber = this.reader.readInt(2);\n this.diskWithCentralDirStart = this.reader.readInt(2);\n this.centralDirRecordsOnThisDisk = this.reader.readInt(2);\n this.centralDirRecords = this.reader.readInt(2);\n this.centralDirSize = this.reader.readInt(4);\n this.centralDirOffset = this.reader.readInt(4);\n\n this.zipCommentLength = this.reader.readInt(2);\n // warning : the encoding depends of the system locale\n // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded.\n // On a windows machine, this field is encoded with the localized windows code page.\n var zipComment = this.reader.readData(this.zipCommentLength);\n var decodeParamType = support.uint8array ? \"uint8array\" : \"array\";\n // To get consistent behavior with the generation part, we will assume that\n // this is utf8 encoded unless specified otherwise.\n var decodeContent = utils.transformTo(decodeParamType, zipComment);\n this.zipComment = this.loadOptions.decodeFileName(decodeContent);\n },\n /**\n * Read the end of the Zip 64 central directory.\n * Not merged with the method readEndOfCentral :\n * The end of central can coexist with its Zip64 brother,\n * I don't want to read the wrong number of bytes !\n */\n readBlockZip64EndOfCentral: function() {\n this.zip64EndOfCentralSize = this.reader.readInt(8);\n this.reader.skip(4);\n // this.versionMadeBy = this.reader.readString(2);\n // this.versionNeeded = this.reader.readInt(2);\n this.diskNumber = this.reader.readInt(4);\n this.diskWithCentralDirStart = this.reader.readInt(4);\n this.centralDirRecordsOnThisDisk = this.reader.readInt(8);\n this.centralDirRecords = this.reader.readInt(8);\n this.centralDirSize = this.reader.readInt(8);\n this.centralDirOffset = this.reader.readInt(8);\n\n this.zip64ExtensibleData = {};\n var extraDataSize = this.zip64EndOfCentralSize - 44,\n index = 0,\n extraFieldId,\n extraFieldLength,\n extraFieldValue;\n while (index < extraDataSize) {\n extraFieldId = this.reader.readInt(2);\n extraFieldLength = this.reader.readInt(4);\n extraFieldValue = this.reader.readData(extraFieldLength);\n this.zip64ExtensibleData[extraFieldId] = {\n id: extraFieldId,\n length: extraFieldLength,\n value: extraFieldValue\n };\n }\n },\n /**\n * Read the end of the Zip 64 central directory locator.\n */\n readBlockZip64EndOfCentralLocator: function() {\n this.diskWithZip64CentralDirStart = this.reader.readInt(4);\n this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);\n this.disksCount = this.reader.readInt(4);\n if (this.disksCount > 1) {\n throw new Error(\"Multi-volumes zip are not supported\");\n }\n },\n /**\n * Read the local files, based on the offset read in the central part.\n */\n readLocalFiles: function() {\n var i, file;\n for (i = 0; i < this.files.length; i++) {\n file = this.files[i];\n this.reader.setIndex(file.localHeaderOffset);\n this.checkSignature(sig.LOCAL_FILE_HEADER);\n file.readLocalPart(this.reader);\n file.handleUTF8();\n file.processAttributes();\n }\n },\n /**\n * Read the central directory.\n */\n readCentralDir: function() {\n var file;\n\n this.reader.setIndex(this.centralDirOffset);\n while (this.reader.readAndCheckSignature(sig.CENTRAL_FILE_HEADER)) {\n file = new ZipEntry({\n zip64: this.zip64\n }, this.loadOptions);\n file.readCentralPart(this.reader);\n this.files.push(file);\n }\n\n if (this.centralDirRecords !== this.files.length) {\n if (this.centralDirRecords !== 0 && this.files.length === 0) {\n // We expected some records but couldn't find ANY.\n // This is really suspicious, as if something went wrong.\n throw new Error(\"Corrupted zip or bug: expected \" + this.centralDirRecords + \" records in central dir, got \" + this.files.length);\n } else {\n // We found some records but not all.\n // Something is wrong but we got something for the user: no error here.\n // console.warn(\"expected\", this.centralDirRecords, \"records in central dir, got\", this.files.length);\n }\n }\n },\n /**\n * Read the end of central directory.\n */\n readEndOfCentral: function() {\n var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END);\n if (offset < 0) {\n // Check if the content is a truncated zip or complete garbage.\n // A \"LOCAL_FILE_HEADER\" is not required at the beginning (auto\n // extractible zip for example) but it can give a good hint.\n // If an ajax request was used without responseType, we will also\n // get unreadable data.\n var isGarbage = !this.isSignature(0, sig.LOCAL_FILE_HEADER);\n\n if (isGarbage) {\n throw new Error(\"Can't find end of central directory : is this a zip file ? \" +\n \"If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html\");\n } else {\n throw new Error(\"Corrupted zip: can't find end of central directory\");\n }\n\n }\n this.reader.setIndex(offset);\n var endOfCentralDirOffset = offset;\n this.checkSignature(sig.CENTRAL_DIRECTORY_END);\n this.readBlockEndOfCentral();\n\n\n /* extract from the zip spec :\n 4) If one of the fields in the end of central directory\n record is too small to hold required data, the field\n should be set to -1 (0xFFFF or 0xFFFFFFFF) and the\n ZIP64 format record should be created.\n 5) The end of central directory record and the\n Zip64 end of central directory locator record must\n reside on the same disk when splitting or spanning\n an archive.\n */\n if (this.diskNumber === utils.MAX_VALUE_16BITS || this.diskWithCentralDirStart === utils.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === utils.MAX_VALUE_16BITS || this.centralDirRecords === utils.MAX_VALUE_16BITS || this.centralDirSize === utils.MAX_VALUE_32BITS || this.centralDirOffset === utils.MAX_VALUE_32BITS) {\n this.zip64 = true;\n\n /*\n Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from\n the zip file can fit into a 32bits integer. This cannot be solved : JavaScript represents\n all numbers as 64-bit double precision IEEE 754 floating point numbers.\n So, we have 53bits for integers and bitwise operations treat everything as 32bits.\n see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators\n and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5\n */\n\n // should look for a zip64 EOCD locator\n offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);\n if (offset < 0) {\n throw new Error(\"Corrupted zip: can't find the ZIP64 end of central directory locator\");\n }\n this.reader.setIndex(offset);\n this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);\n this.readBlockZip64EndOfCentralLocator();\n\n // now the zip64 EOCD record\n if (!this.isSignature(this.relativeOffsetEndOfZip64CentralDir, sig.ZIP64_CENTRAL_DIRECTORY_END)) {\n // console.warn(\"ZIP64 end of central directory not where expected.\");\n this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);\n if (this.relativeOffsetEndOfZip64CentralDir < 0) {\n throw new Error(\"Corrupted zip: can't find the ZIP64 end of central directory\");\n }\n }\n this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);\n this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);\n this.readBlockZip64EndOfCentral();\n }\n\n var expectedEndOfCentralDirOffset = this.centralDirOffset + this.centralDirSize;\n if (this.zip64) {\n expectedEndOfCentralDirOffset += 20; // end of central dir 64 locator\n expectedEndOfCentralDirOffset += 12 /* should not include the leading 12 bytes */ + this.zip64EndOfCentralSize;\n }\n\n var extraBytes = endOfCentralDirOffset - expectedEndOfCentralDirOffset;\n\n if (extraBytes > 0) {\n // console.warn(extraBytes, \"extra bytes at beginning or within zipfile\");\n if (this.isSignature(endOfCentralDirOffset, sig.CENTRAL_FILE_HEADER)) {\n // The offsets seem wrong, but we have something at the specified offset.\n // So… we keep it.\n } else {\n // the offset is wrong, update the \"zero\" of the reader\n // this happens if data has been prepended (crx files for example)\n this.reader.zero = extraBytes;\n }\n } else if (extraBytes < 0) {\n throw new Error(\"Corrupted zip: missing \" + Math.abs(extraBytes) + \" bytes.\");\n }\n },\n prepareReader: function(data) {\n this.reader = readerFor(data);\n },\n /**\n * Read a zip file and create ZipEntries.\n * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file.\n */\n load: function(data) {\n this.prepareReader(data);\n this.readEndOfCentral();\n this.readCentralDir();\n this.readLocalFiles();\n }\n};\n// }}} end of ZipEntries\nmodule.exports = ZipEntries;\n", "\"use strict\";\nvar utils = require(\"./utils\");\nvar external = require(\"./external\");\nvar utf8 = require(\"./utf8\");\nvar ZipEntries = require(\"./zipEntries\");\nvar Crc32Probe = require(\"./stream/Crc32Probe\");\nvar nodejsUtils = require(\"./nodejsUtils\");\n\n/**\n * Check the CRC32 of an entry.\n * @param {ZipEntry} zipEntry the zip entry to check.\n * @return {Promise} the result.\n */\nfunction checkEntryCRC32(zipEntry) {\n return new external.Promise(function (resolve, reject) {\n var worker = zipEntry.decompressed.getContentWorker().pipe(new Crc32Probe());\n worker.on(\"error\", function (e) {\n reject(e);\n })\n .on(\"end\", function () {\n if (worker.streamInfo.crc32 !== zipEntry.decompressed.crc32) {\n reject(new Error(\"Corrupted zip : CRC32 mismatch\"));\n } else {\n resolve();\n }\n })\n .resume();\n });\n}\n\nmodule.exports = function (data, options) {\n var zip = this;\n options = utils.extend(options || {}, {\n base64: false,\n checkCRC32: false,\n optimizedBinaryString: false,\n createFolders: false,\n decodeFileName: utf8.utf8decode\n });\n\n if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {\n return external.Promise.reject(new Error(\"JSZip can't accept a stream when loading a zip file.\"));\n }\n\n return utils.prepareContent(\"the loaded zip file\", data, true, options.optimizedBinaryString, options.base64)\n .then(function (data) {\n var zipEntries = new ZipEntries(options);\n zipEntries.load(data);\n return zipEntries;\n }).then(function checkCRC32(zipEntries) {\n var promises = [external.Promise.resolve(zipEntries)];\n var files = zipEntries.files;\n if (options.checkCRC32) {\n for (var i = 0; i < files.length; i++) {\n promises.push(checkEntryCRC32(files[i]));\n }\n }\n return external.Promise.all(promises);\n }).then(function addFiles(results) {\n var zipEntries = results.shift();\n var files = zipEntries.files;\n for (var i = 0; i < files.length; i++) {\n var input = files[i];\n\n var unsafeName = input.fileNameStr;\n var safeName = utils.resolve(input.fileNameStr);\n\n zip.file(safeName, input.decompressed, {\n binary: true,\n optimizedBinaryString: true,\n date: input.date,\n dir: input.dir,\n comment: input.fileCommentStr.length ? input.fileCommentStr : null,\n unixPermissions: input.unixPermissions,\n dosPermissions: input.dosPermissions,\n createFolders: options.createFolders\n });\n if (!input.dir) {\n zip.file(safeName).unsafeOriginalName = unsafeName;\n }\n }\n if (zipEntries.zipComment.length) {\n zip.comment = zipEntries.zipComment;\n }\n\n return zip;\n });\n};\n", "\"use strict\";\n\n/**\n * Representation a of zip file in js\n * @constructor\n */\nfunction JSZip() {\n // if this constructor is used without `new`, it adds `new` before itself:\n if(!(this instanceof JSZip)) {\n return new JSZip();\n }\n\n if(arguments.length) {\n throw new Error(\"The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.\");\n }\n\n // object containing the files :\n // {\n // \"folder/\" : {...},\n // \"folder/data.txt\" : {...}\n // }\n // NOTE: we use a null prototype because we do not\n // want filenames like \"toString\" coming from a zip file\n // to overwrite methods and attributes in a normal Object.\n this.files = Object.create(null);\n\n this.comment = null;\n\n // Where we are in the hierarchy\n this.root = \"\";\n this.clone = function() {\n var newObj = new JSZip();\n for (var i in this) {\n if (typeof this[i] !== \"function\") {\n newObj[i] = this[i];\n }\n }\n return newObj;\n };\n}\nJSZip.prototype = require(\"./object\");\nJSZip.prototype.loadAsync = require(\"./load\");\nJSZip.support = require(\"./support\");\nJSZip.defaults = require(\"./defaults\");\n\n// TODO find a better way to handle this version,\n// a require('package.json').version doesn't work with webpack, see #327\nJSZip.version = \"3.10.2\";\n\nJSZip.loadAsync = function (content, options) {\n return new JSZip().loadAsync(content, options);\n};\n\nJSZip.external = require(\"./external\");\nmodule.exports = JSZip;\n", "/* @license\nPapa Parse\nv5.7.1\nhttps://github.com/mholt/PapaParse\nLicense: MIT\n*/\n\n(function(root, factory)\n{\n\t/* globals define */\n\tif (typeof define === 'function' && define.amd)\n\t{\n\t\t// AMD. Register as an anonymous module.\n\t\tdefine([], factory);\n\t}\n\telse if (typeof module === 'object' && typeof exports !== 'undefined')\n\t{\n\t\t// Node. Does not work with strict CommonJS, but\n\t\t// only CommonJS-like environments that support module.exports,\n\t\t// like Node.\n\t\tmodule.exports = factory();\n\t}\n\telse\n\t{\n\t\t// Browser globals (root is window)\n\t\troot.Papa = factory();\n\t}\n\t// in strict mode we cannot access arguments.callee, so we need a named reference to\n\t// stringify the factory method for the blob worker\n\t// eslint-disable-next-line func-name\n}(this, function moduleFactory()\n{\n\t'use strict';\n\n\tvar global = (function() {\n\t\t// alternative method, similar to `Function('return this')()`\n\t\t// but without using `eval` (which is disabled when\n\t\t// using Content Security Policy).\n\n\t\tif (typeof self !== 'undefined') { return self; }\n\t\tif (typeof window !== 'undefined') { return window; }\n\t\tif (typeof global !== 'undefined') { return global; }\n\n\t\t// When running tests none of the above have been defined\n\t\treturn {};\n\t})();\n\n\n\tfunction getWorkerBlob() {\n\t\tvar URL = global.URL || global.webkitURL || null;\n\t\tvar code = moduleFactory.toString();\n\t\treturn Papa.BLOB_URL || (Papa.BLOB_URL = URL.createObjectURL(new Blob([\"var global = (function() { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } return {}; })(); global.IS_PAPA_WORKER=true; \", '(', code, ')();'], {type: 'text/javascript'})));\n\t}\n\n\tvar IS_WORKER = !global.document && !!global.postMessage,\n\t\tIS_PAPA_WORKER = global.IS_PAPA_WORKER || false;\n\n\tvar workers = {}, workerIdCounter = 0;\n\n\tvar Papa = {};\n\n\tPapa.parse = CsvToJson;\n\tPapa.unparse = JsonToCsv;\n\n\tPapa.RECORD_SEP = String.fromCharCode(30);\n\tPapa.UNIT_SEP = String.fromCharCode(31);\n\tPapa.BYTE_ORDER_MARK = '\\ufeff';\n\tPapa.BAD_DELIMITERS = ['\\r', '\\n', '\"', Papa.BYTE_ORDER_MARK];\n\tPapa.WORKERS_SUPPORTED = !IS_WORKER && !!global.Worker;\n\tPapa.NODE_STREAM_INPUT = 1;\n\n\t// Configurable chunk sizes for local and remote files, respectively\n\tPapa.LocalChunkSize = 1024 * 1024 * 10;\t// 10 MB\n\tPapa.RemoteChunkSize = 1024 * 1024 * 5;\t// 5 MB\n\tPapa.DefaultDelimiter = ',';\t\t\t// Used if not specified and detection fails\n\n\t// Exposed for testing and development only\n\tPapa.Parser = Parser;\n\tPapa.ParserHandle = ParserHandle;\n\tPapa.NetworkStreamer = NetworkStreamer;\n\tPapa.FileStreamer = FileStreamer;\n\tPapa.StringStreamer = StringStreamer;\n\tPapa.ReadableStreamStreamer = ReadableStreamStreamer;\n\tif (typeof PAPA_BROWSER_CONTEXT === 'undefined') {\n\t\tPapa.DuplexStreamStreamer = DuplexStreamStreamer;\n\t}\n\n\tif (IS_PAPA_WORKER)\n\t{\n\t\tglobal.onmessage = workerThreadReceivedMessage;\n\t}\n\n\t// Strip character from UTF-8 BOM encoded files that cause issue parsing the file\n\tfunction stripBom(string) {\n\t\tif (string.charCodeAt(0) === 0xfeff) {\n\t\t\treturn string.slice(1);\n\t\t}\n\t\treturn string;\n\t}\n\n\tfunction CsvToJson(_input, _config)\n\t{\n\t\t_config = _config || {};\n\t\tvar dynamicTyping = _config.dynamicTyping || false;\n\t\tif (isFunction(dynamicTyping)) {\n\t\t\t_config.dynamicTypingFunction = dynamicTyping;\n\t\t\t// Will be filled on first row call\n\t\t\tdynamicTyping = {};\n\t\t}\n\t\t_config.dynamicTyping = dynamicTyping;\n\n\t\t_config.transform = isFunction(_config.transform) ? _config.transform : false;\n\n\t\tif (_config.downloadTimeout !== undefined)\n\t\t{\n\t\t\tvar downloadTimeout = parseInt(_config.downloadTimeout);\n\t\t\tif (isNaN(downloadTimeout))\n\t\t\t{\n\t\t\t\tthrow new Error('Config downloadTimeout value (' + _config.downloadTimeout + ') not parsable by parseInt(val).');\n\t\t\t}\n\t\t\t_config.downloadTimeout = downloadTimeout;\n\t\t}\n\n\t\tif (_config.worker && Papa.WORKERS_SUPPORTED)\n\t\t{\n\t\t\tvar w = newWorker();\n\n\t\t\tw.userStep = _config.step;\n\t\t\tw.userChunk = _config.chunk;\n\t\t\tw.userComplete = _config.complete;\n\t\t\tw.userError = _config.error;\n\n\t\t\t_config.step = isFunction(_config.step);\n\t\t\t_config.chunk = isFunction(_config.chunk);\n\t\t\t_config.complete = isFunction(_config.complete);\n\t\t\t_config.error = isFunction(_config.error);\n\t\t\tdelete _config.worker;\t// prevent infinite loop\n\n\t\t\tw.postMessage({\n\t\t\t\tinput: _input,\n\t\t\t\tconfig: _config,\n\t\t\t\tworkerId: w.id\n\t\t\t});\n\n\t\t\treturn;\n\t\t}\n\n\t\tvar streamer = null;\n\t\tif (_input === Papa.NODE_STREAM_INPUT && typeof PAPA_BROWSER_CONTEXT === 'undefined')\n\t\t{\n\t\t\t// create a node Duplex stream for use\n\t\t\t// with .pipe\n\t\t\tstreamer = new DuplexStreamStreamer(_config);\n\t\t\treturn streamer.getStream();\n\t\t}\n\t\telse if (typeof _input === 'string')\n\t\t{\n\t\t\t_input = stripBom(_input);\n\t\t\tif (_config.download)\n\t\t\t\tstreamer = new NetworkStreamer(_config);\n\t\t\telse\n\t\t\t\tstreamer = new StringStreamer(_config);\n\t\t}\n\t\telse if (_input.readable === true && isFunction(_input.read) && isFunction(_input.on))\n\t\t{\n\t\t\tstreamer = new ReadableStreamStreamer(_config);\n\t\t}\n\t\telse if ((global.File && _input instanceof File) || _input instanceof Object)\t// ...Safari. (see issue #106)\n\t\t\tstreamer = new FileStreamer(_config);\n\n\t\treturn streamer.stream(_input);\n\t}\n\n\n\n\n\n\n\tfunction JsonToCsv(_input, _config)\n\t{\n\t\t// Default configuration\n\n\t\t/** whether to surround every datum with quotes */\n\t\tvar _quotes = false;\n\n\t\t/** whether to write headers */\n\t\tvar _writeHeader = true;\n\n\t\t/** delimiting character(s) */\n\t\tvar _delimiter = ',';\n\n\t\t/** newline character(s) */\n\t\tvar _newline = '\\r\\n';\n\n\t\t/** quote character */\n\t\tvar _quoteChar = '\"';\n\n\t\t/** escaped quote character, either \"\" or <config.escapeChar>\" */\n\t\tvar _escapedQuote = _quoteChar + _quoteChar;\n\n\t\t/** whether to skip empty lines */\n\t\tvar _skipEmptyLines = false;\n\n\t\t/** the columns (keys) we expect when we unparse objects */\n\t\tvar _columns = null;\n\n\t\t/** whether to prevent outputting cells that can be parsed as formulae by spreadsheet software (Excel and LibreOffice) */\n\t\tvar _escapeFormulae = false;\n\n\t\tunpackConfig();\n\n\t\tvar quoteCharRegex = new RegExp(escapeRegExp(_quoteChar), 'g');\n\n\t\tif (typeof _input === 'string')\n\t\t\t_input = JSON.parse(_input);\n\n\t\tif (Array.isArray(_input))\n\t\t{\n\t\t\tif (!_input.length)\n\t\t\t\treturn serialize(_columns, _input, _skipEmptyLines);\n\t\t\telse if (Array.isArray(_input[0]))\n\t\t\t\treturn serialize(null, _input, _skipEmptyLines);\n\t\t\telse if (typeof _input[0] === 'object')\n\t\t\t\treturn serialize(_columns || Object.keys(_input[0]), _input, _skipEmptyLines);\n\t\t}\n\t\telse if (typeof _input === 'object')\n\t\t{\n\t\t\tif (typeof _input.data === 'string')\n\t\t\t\t_input.data = JSON.parse(_input.data);\n\n\t\t\tif (Array.isArray(_input.data))\n\t\t\t{\n\t\t\t\tif (!_input.fields)\n\t\t\t\t\t_input.fields = _input.meta && _input.meta.fields || _columns;\n\n\t\t\t\tif (!_input.fields)\n\t\t\t\t\t_input.fields = Array.isArray(_input.data[0])\n\t\t\t\t\t\t? _input.fields\n\t\t\t\t\t\t: typeof _input.data[0] === 'object'\n\t\t\t\t\t\t\t? Object.keys(_input.data[0])\n\t\t\t\t\t\t\t: [];\n\n\t\t\t\tif (!(Array.isArray(_input.data[0])) && typeof _input.data[0] !== 'object')\n\t\t\t\t\t_input.data = [_input.data];\t// handles input like [1,2,3] or ['asdf']\n\t\t\t}\n\n\t\t\treturn serialize(_input.fields || [], _input.data || [], _skipEmptyLines);\n\t\t}\n\n\t\t// Default (any valid paths should return before this)\n\t\tthrow new Error('Unable to serialize unrecognized input');\n\n\n\t\tfunction unpackConfig()\n\t\t{\n\t\t\tif (typeof _config !== 'object')\n\t\t\t\treturn;\n\n\t\t\tif (typeof _config.delimiter === 'string'\n && !Papa.BAD_DELIMITERS.filter(function(value) { return _config.delimiter.indexOf(value) !== -1; }).length)\n\t\t\t{\n\t\t\t\t_delimiter = _config.delimiter;\n\t\t\t}\n\n\t\t\tif (typeof _config.quotes === 'boolean'\n\t\t\t\t|| typeof _config.quotes === 'function'\n\t\t\t\t|| Array.isArray(_config.quotes))\n\t\t\t\t_quotes = _config.quotes;\n\n\t\t\tif (typeof _config.skipEmptyLines === 'boolean'\n\t\t\t\t|| typeof _config.skipEmptyLines === 'string')\n\t\t\t\t_skipEmptyLines = _config.skipEmptyLines;\n\n\t\t\tif (typeof _config.newline === 'string')\n\t\t\t\t_newline = _config.newline;\n\n\t\t\tif (typeof _config.quoteChar === 'string') {\n\t\t\t\t_quoteChar = _config.quoteChar;\n\t\t\t\t_escapedQuote = _quoteChar + _quoteChar;\n\t\t\t}\n\n\t\t\tif (typeof _config.header === 'boolean')\n\t\t\t\t_writeHeader = _config.header;\n\n\t\t\tif (Array.isArray(_config.columns)) {\n\n\t\t\t\tif (_config.columns.length === 0) throw new Error('Option columns is empty');\n\n\t\t\t\t_columns = _config.columns;\n\t\t\t}\n\n\t\t\tif (_config.escapeChar !== undefined) {\n\t\t\t\t_escapedQuote = _config.escapeChar + _quoteChar;\n\t\t\t}\n\n\t\t\tif (_config.escapeFormulae instanceof RegExp) {\n\t\t\t\t_escapeFormulae = _config.escapeFormulae;\n\t\t\t} else if (typeof _config.escapeFormulae === 'boolean' && _config.escapeFormulae) {\n\t\t\t\t_escapeFormulae = /^[=+\\-@\\t\\r].*$/;\n\t\t\t}\n\t\t}\n\n\t\t/** The double for loop that iterates the data and writes out a CSV string including header row */\n\t\tfunction serialize(fields, data, skipEmptyLines)\n\t\t{\n\t\t\tvar csv = '';\n\n\t\t\tif (typeof fields === 'string')\n\t\t\t\tfields = JSON.parse(fields);\n\t\t\tif (typeof data === 'string')\n\t\t\t\tdata = JSON.parse(data);\n\n\t\t\tvar hasHeader = Array.isArray(fields) && fields.length > 0;\n\t\t\tvar dataKeyedByField = !(Array.isArray(data[0]));\n\n\t\t\t// If there a header row, write it first\n\t\t\tif (hasHeader && _writeHeader)\n\t\t\t{\n\t\t\t\tfor (var i = 0; i < fields.length; i++)\n\t\t\t\t{\n\t\t\t\t\tif (i > 0)\n\t\t\t\t\t\tcsv += _delimiter;\n\t\t\t\t\tcsv += safe(fields[i], i);\n\t\t\t\t}\n\t\t\t\tif (data.length > 0)\n\t\t\t\t\tcsv += _newline;\n\t\t\t}\n\n\t\t\t// Then write out the data\n\t\t\tfor (var row = 0; row < data.length; row++)\n\t\t\t{\n\t\t\t\tvar maxCol = hasHeader ? fields.length : data[row].length;\n\n\t\t\t\tvar emptyLine = false;\n\t\t\t\tvar nullLine = hasHeader ? Object.keys(data[row]).length === 0 : data[row].length === 0;\n\t\t\t\tif (skipEmptyLines && !hasHeader)\n\t\t\t\t{\n\t\t\t\t\temptyLine = skipEmptyLines === 'greedy' ? data[row].join('').trim() === '' : data[row].length === 1 && (data[row][0] === null || data[row][0] === undefined || data[row][0].length === 0);\n\t\t\t\t}\n\t\t\t\tif (skipEmptyLines === 'greedy' && hasHeader) {\n\t\t\t\t\tvar line = [];\n\t\t\t\t\tfor (var c = 0; c < maxCol; c++) {\n\t\t\t\t\t\tvar cx = dataKeyedByField ? fields[c] : c;\n\t\t\t\t\t\tline.push(data[row][cx]);\n\t\t\t\t\t}\n\t\t\t\t\temptyLine = line.join('').trim() === '';\n\t\t\t\t}\n\t\t\t\tif (!emptyLine)\n\t\t\t\t{\n\t\t\t\t\tfor (var col = 0; col < maxCol; col++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (col > 0 && !nullLine)\n\t\t\t\t\t\t\tcsv += _delimiter;\n\t\t\t\t\t\tvar colIdx = hasHeader && dataKeyedByField ? fields[col] : col;\n\t\t\t\t\t\tcsv += safe(data[row][colIdx], col);\n\t\t\t\t\t}\n\t\t\t\t\tif (row < data.length - 1 && (!skipEmptyLines || (maxCol > 0 && !nullLine)))\n\t\t\t\t\t{\n\t\t\t\t\t\tcsv += _newline;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn csv;\n\t\t}\n\n\t\t/** Encloses a value around quotes if needed (makes a value safe for CSV insertion) */\n\t\tfunction safe(str, col)\n\t\t{\n\t\t\tif (typeof str === 'undefined' || str === null)\n\t\t\t\treturn '';\n\n\t\t\tif (str.constructor === Date)\n\t\t\t{\n\t\t\t\t// Return empty string for invalid dates\n\t\t\t\tif (isNaN(str.getTime()))\n\t\t\t\t\treturn '';\n\t\t\t\treturn str.toISOString();\n\t\t\t}\n\n\t\t\tvar needsQuotes = false;\n\t\t\tvar strValue = str.toString();\n\n\t\t\t// Exclude numeric and boolean primitives, but check the serialized text of objects.\n\t\t\tif (_escapeFormulae && typeof str !== 'number' && typeof str !== 'bigint' // eslint-disable-line valid-typeof\n\t\t\t\t&& typeof str !== 'boolean' && _escapeFormulae.test(strValue)) {\n\t\t\t\tstrValue = \"'\" + strValue;\n\t\t\t\tstr = strValue;\n\t\t\t\tneedsQuotes = true;\n\t\t\t}\n\t\t\tvar escapedQuoteStr = strValue.replace(quoteCharRegex, _escapedQuote);\n\n\t\t\tneedsQuotes = needsQuotes\n\t\t\t\t\t\t\t|| _quotes === true\n\t\t\t\t\t\t\t|| (typeof _quotes === 'function' && _quotes(str, col))\n\t\t\t\t\t\t\t|| (Array.isArray(_quotes) && _quotes[col])\n\t\t\t\t\t\t\t|| hasAny(escapedQuoteStr, Papa.BAD_DELIMITERS)\n\t\t\t\t\t\t\t|| escapedQuoteStr.indexOf(_delimiter) > -1\n\t\t\t\t\t\t\t|| strValue.indexOf(_quoteChar) > -1\n\t\t\t\t\t\t\t|| escapedQuoteStr.charAt(0) === ' '\n\t\t\t\t\t\t\t|| escapedQuoteStr.charAt(escapedQuoteStr.length - 1) === ' ';\n\n\t\t\treturn needsQuotes ? _quoteChar + escapedQuoteStr + _quoteChar : escapedQuoteStr;\n\t\t}\n\n\t\tfunction hasAny(str, substrings)\n\t\t{\n\t\t\tfor (var i = 0; i < substrings.length; i++)\n\t\t\t\tif (str.indexOf(substrings[i]) > -1)\n\t\t\t\t\treturn true;\n\t\t\treturn false;\n\t\t}\n\t}\n\n\n\t/** ChunkStreamer is the base prototype for various streamer implementations. */\n\tfunction ChunkStreamer(config)\n\t{\n\t\tthis._handle = null;\n\t\tthis._finished = false;\n\t\tthis._completed = false;\n\t\tthis._halted = false;\n\t\tthis._input = null;\n\t\tthis._baseIndex = 0;\n\t\tthis._partialLine = '';\n\t\tthis._rowCount = 0;\n\t\tthis._start = 0;\n\t\tthis._nextChunk = null;\n\t\tthis.isFirstChunk = true;\n\t\tthis._completeResults = {\n\t\t\tdata: [],\n\t\t\terrors: [],\n\t\t\tmeta: {}\n\t\t};\n\t\treplaceConfig.call(this, config);\n\n\t\tthis.parseChunk = function(chunk, isFakeChunk)\n\t\t{\n\t\t\t// First chunk pre-processing\n\t\t\tconst skipFirstNLines = parseInt(this._config.skipFirstNLines) || 0;\n\t\t\tif (this.isFirstChunk && skipFirstNLines > 0) {\n\t\t\t\tlet _newline = this._config.newline;\n\t\t\t\tif (!_newline) {\n\t\t\t\t\tconst quoteChar = this._config.quoteChar || '\"';\n\t\t\t\t\t_newline = this._handle.guessLineEndings(chunk, quoteChar);\n\t\t\t\t}\n\t\t\t\tconst splitChunk = chunk.split(_newline);\n\t\t\t\tchunk = [...splitChunk.slice(skipFirstNLines)].join(_newline);\n\t\t\t}\n\t\t\tif (this.isFirstChunk && isFunction(this._config.beforeFirstChunk))\n\t\t\t{\n\t\t\t\tvar modifiedChunk = this._config.beforeFirstChunk(chunk);\n\t\t\t\tif (modifiedChunk !== undefined)\n\t\t\t\t\tchunk = modifiedChunk;\n\t\t\t}\n\t\t\tthis.isFirstChunk = false;\n\t\t\tthis._halted = false;\n\n\t\t\t// Rejoin the line we likely just split in two by chunking the file\n\t\t\tvar aggregate = this._partialLine + chunk;\n\t\t\tthis._partialLine = '';\n\t\t\tvar results = this._handle.parse(aggregate, this._baseIndex, !this._finished);\n\n\t\t\tif (this._handle.paused() || this._handle.aborted()) {\n\t\t\t\tthis._halted = true;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tvar lastIndex = results.meta.cursor;\n\n\t\t\tif (!this._finished)\n\t\t\t{\n\t\t\t\tthis._partialLine = aggregate.substring(lastIndex - this._baseIndex);\n\t\t\t\tthis._baseIndex = lastIndex;\n\t\t\t}\n\n\t\t\tif (results && results.data)\n\t\t\t\tthis._rowCount += results.data.length;\n\n\t\t\tvar finishedIncludingPreview = this._finished || (this._config.preview && this._rowCount >= this._config.preview);\n\n\t\t\tif (IS_PAPA_WORKER)\n\t\t\t{\n\t\t\t\tglobal.postMessage({\n\t\t\t\t\tresults: results,\n\t\t\t\t\tworkerId: Papa.WORKER_ID,\n\t\t\t\t\tfinished: finishedIncludingPreview\n\t\t\t\t});\n\t\t\t}\n\t\t\telse if (isFunction(this._config.chunk) && !isFakeChunk)\n\t\t\t{\n\t\t\t\tthis._config.chunk(results, this._handle);\n\t\t\t\tif (this._handle.paused() || this._handle.aborted()) {\n\t\t\t\t\tthis._halted = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tresults = undefined;\n\t\t\t\tthis._completeResults = undefined;\n\t\t\t}\n\n\t\t\tif (!this._config.step && !this._config.chunk) {\n\t\t\t\tthis._completeResults.data = this._completeResults.data.concat(results.data);\n\t\t\t\tthis._completeResults.errors = this._completeResults.errors.concat(results.errors);\n\t\t\t\tthis._completeResults.meta = results.meta;\n\t\t\t}\n\n\t\t\tif (!this._completed && finishedIncludingPreview && isFunction(this._config.complete) && (!results || !results.meta.aborted)) {\n\t\t\t\tthis._config.complete(this._completeResults, this._input);\n\t\t\t\tthis._completed = true;\n\t\t\t}\n\n\t\t\tif (!finishedIncludingPreview && (!results || !results.meta.paused))\n\t\t\t\tthis._nextChunk();\n\n\t\t\treturn results;\n\t\t};\n\n\t\tthis._sendError = function(error)\n\t\t{\n\t\t\tif (isFunction(this._config.error))\n\t\t\t\tthis._config.error(error);\n\t\t\telse if (IS_PAPA_WORKER && this._config.error)\n\t\t\t{\n\t\t\t\tglobal.postMessage({\n\t\t\t\t\tworkerId: Papa.WORKER_ID,\n\t\t\t\t\terror: error,\n\t\t\t\t\tfinished: false\n\t\t\t\t});\n\t\t\t}\n\t\t};\n\n\t\tfunction replaceConfig(config)\n\t\t{\n\t\t\t// Deep-copy the config so we can edit it\n\t\t\tvar configCopy = copy(config);\n\t\t\tconfigCopy.chunkSize = parseInt(configCopy.chunkSize);\t// parseInt VERY important so we don't concatenate strings!\n\t\t\tif (!config.step && !config.chunk)\n\t\t\t\tconfigCopy.chunkSize = null; // disable Range header if not streaming; bad values break IIS - see issue #196\n\t\t\tthis._handle = new ParserHandle(configCopy);\n\t\t\tthis._handle.streamer = this;\n\t\t\tthis._config = configCopy;\t// persist the copy to the caller\n\t\t}\n\t}\n\n\n\tfunction NetworkStreamer(config)\n\t{\n\t\tconfig = config || {};\n\t\tif (!config.chunkSize)\n\t\t\tconfig.chunkSize = Papa.RemoteChunkSize;\n\t\tChunkStreamer.call(this, config);\n\n\t\tvar xhr;\n\n\t\tif (IS_WORKER)\n\t\t{\n\t\t\tthis._nextChunk = function()\n\t\t\t{\n\t\t\t\tthis._readChunk();\n\t\t\t\tthis._chunkLoaded();\n\t\t\t};\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthis._nextChunk = function()\n\t\t\t{\n\t\t\t\tthis._readChunk();\n\t\t\t};\n\t\t}\n\n\t\tthis.stream = function(url)\n\t\t{\n\t\t\tthis._input = url;\n\t\t\tthis._nextChunk();\t// Starts streaming\n\t\t};\n\n\t\tthis._readChunk = function()\n\t\t{\n\t\t\tif (this._finished)\n\t\t\t{\n\t\t\t\tthis._chunkLoaded();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\txhr = new XMLHttpRequest();\n\n\t\t\tif (this._config.withCredentials)\n\t\t\t{\n\t\t\t\txhr.withCredentials = this._config.withCredentials;\n\t\t\t}\n\n\t\t\tif (!IS_WORKER)\n\t\t\t{\n\t\t\t\txhr.onload = bindFunction(this._chunkLoaded, this);\n\t\t\t\txhr.onerror = bindFunction(this._chunkError, this);\n\t\t\t}\n\n\t\t\txhr.ontimeout = bindFunction(this._chunkTimeout, this);\n\n\t\t\txhr.open(this._config.downloadRequestBody ? 'POST' : 'GET', this._input, !IS_WORKER);\n\t\t\t// Timeout is only supported for asynchronous requests\n\t\t\tif (this._config.downloadTimeout && !IS_WORKER)\n\t\t\t{\n\t\t\t\txhr.timeout = this._config.downloadTimeout;\n\t\t\t}\n\t\t\t// Headers can only be set when once the request state is OPENED\n\t\t\tif (this._config.downloadRequestHeaders)\n\t\t\t{\n\t\t\t\tvar headers = this._config.downloadRequestHeaders;\n\n\t\t\t\tfor (var headerName in headers)\n\t\t\t\t{\n\t\t\t\t\txhr.setRequestHeader(headerName, headers[headerName]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (this._config.chunkSize)\n\t\t\t{\n\t\t\t\tvar end = this._start + this._config.chunkSize - 1;\t// minus one because byte range is inclusive\n\t\t\t\txhr.setRequestHeader('Range', 'bytes=' + this._start + '-' + end);\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\txhr.send(this._config.downloadRequestBody);\n\t\t\t}\n\t\t\tcatch (err) {\n\t\t\t\tthis._chunkError(err.message);\n\t\t\t}\n\n\t\t\tif (IS_WORKER && xhr.status === 0)\n\t\t\t\tthis._chunkError();\n\t\t};\n\n\t\tthis._chunkLoaded = function()\n\t\t{\n\t\t\tif (xhr.readyState !== 4)\n\t\t\t\treturn;\n\n\t\t\tif (xhr.status < 200 || xhr.status >= 400)\n\t\t\t{\n\t\t\t\tthis._chunkError();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Use chunckSize as it may be a diference on reponse lentgh due to characters with more than 1 byte\n\t\t\tthis._start += this._config.chunkSize ? this._config.chunkSize : xhr.responseText.length;\n\t\t\tthis._finished = !this._config.chunkSize || this._start >= getFileSize(xhr);\n\t\t\tthis.parseChunk(xhr.responseText);\n\t\t};\n\n\t\tthis._chunkError = function(errorMessage)\n\t\t{\n\t\t\tvar errorText = xhr.statusText || errorMessage;\n\t\t\tthis._sendError(new Error(errorText));\n\t\t};\n\n\t\tthis._chunkTimeout = function()\n\t\t{\n\t\t\tthis._chunkError('Request timed out after ' + this._config.downloadTimeout + 'ms');\n\t\t};\n\n\t\tfunction getFileSize(xhr)\n\t\t{\n\t\t\tvar contentRange = xhr.getResponseHeader('Content-Range');\n\t\t\tif (contentRange === null) { // no content range, then finish!\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\treturn parseInt(contentRange.substring(contentRange.lastIndexOf('/') + 1));\n\t\t}\n\t}\n\tNetworkStreamer.prototype = Object.create(ChunkStreamer.prototype);\n\tNetworkStreamer.prototype.constructor = NetworkStreamer;\n\n\n\tfunction FileStreamer(config)\n\t{\n\t\tconfig = config || {};\n\t\tif (!config.chunkSize)\n\t\t\tconfig.chunkSize = Papa.LocalChunkSize;\n\t\tChunkStreamer.call(this, config);\n\n\t\tvar reader, slice;\n\n\t\t// FileReader is better than FileReaderSync (even in worker) - see http://stackoverflow.com/q/24708649/1048862\n\t\t// But Firefox is a pill, too - see issue #76: https://github.com/mholt/PapaParse/issues/76\n\t\tvar usingAsyncReader = typeof FileReader !== 'undefined';\t// Safari doesn't consider it a function - see issue #105\n\n\t\tthis.stream = function(file)\n\t\t{\n\t\t\tthis._input = file;\n\t\t\tslice = file.slice || file.webkitSlice || file.mozSlice;\n\n\t\t\tif (usingAsyncReader)\n\t\t\t{\n\t\t\t\treader = new FileReader();\t\t// Preferred method of reading files, even in workers\n\t\t\t\treader.onload = bindFunction(this._chunkLoaded, this);\n\t\t\t\treader.onerror = bindFunction(this._chunkError, this);\n\t\t\t}\n\t\t\telse\n\t\t\t\treader = new FileReaderSync();\t// Hack for running in a web worker in Firefox\n\n\t\t\tthis._nextChunk();\t// Starts streaming\n\t\t};\n\n\t\tthis._nextChunk = function()\n\t\t{\n\t\t\tif (!this._finished && (!this._config.preview || this._rowCount < this._config.preview))\n\t\t\t\tthis._readChunk();\n\t\t};\n\n\t\tthis._readChunk = function()\n\t\t{\n\t\t\tvar input = this._input;\n\t\t\tif (this._config.chunkSize)\n\t\t\t{\n\t\t\t\tvar end = Math.min(this._start + this._config.chunkSize, this._input.size);\n\t\t\t\tinput = slice.call(input, this._start, end);\n\t\t\t}\n\t\t\tvar txt = reader.readAsText(input, this._config.encoding);\n\t\t\tif (!usingAsyncReader)\n\t\t\t\tthis._chunkLoaded({ target: { result: txt } });\t// mimic the async signature\n\t\t};\n\n\t\tthis._chunkLoaded = function(event)\n\t\t{\n\t\t\t// Very important to increment start each time before handling results\n\t\t\tthis._start += this._config.chunkSize;\n\t\t\tthis._finished = !this._config.chunkSize || this._start >= this._input.size;\n\t\t\tthis.parseChunk(event.target.result);\n\t\t};\n\n\t\tthis._chunkError = function()\n\t\t{\n\t\t\tthis._sendError(reader.error);\n\t\t};\n\n\t}\n\tFileStreamer.prototype = Object.create(ChunkStreamer.prototype);\n\tFileStreamer.prototype.constructor = FileStreamer;\n\n\n\tfunction StringStreamer(config)\n\t{\n\t\tconfig = config || {};\n\t\tChunkStreamer.call(this, config);\n\n\t\tvar remaining;\n\t\tthis.stream = function(s)\n\t\t{\n\t\t\tremaining = s;\n\t\t\treturn this._nextChunk();\n\t\t};\n\t\tthis._nextChunk = function()\n\t\t{\n\t\t\tif (this._finished) return;\n\t\t\tvar size = this._config.chunkSize;\n\t\t\tvar chunk;\n\t\t\tif(size) {\n\t\t\t\tchunk = remaining.substring(0, size);\n\t\t\t\tremaining = remaining.substring(size);\n\t\t\t} else {\n\t\t\t\tchunk = remaining;\n\t\t\t\tremaining = '';\n\t\t\t}\n\t\t\tthis._finished = !remaining;\n\t\t\treturn this.parseChunk(chunk);\n\t\t};\n\t}\n\tStringStreamer.prototype = Object.create(StringStreamer.prototype);\n\tStringStreamer.prototype.constructor = StringStreamer;\n\n\n\tfunction ReadableStreamStreamer(config)\n\t{\n\t\tconfig = config || {};\n\n\t\tChunkStreamer.call(this, config);\n\n\t\tvar queue = [];\n\t\tvar parseOnData = true;\n\t\tvar streamHasEnded = false;\n\n\t\tthis.pause = function()\n\t\t{\n\t\t\tChunkStreamer.prototype.pause.apply(this, arguments);\n\t\t\tthis._input.pause();\n\t\t};\n\n\t\tthis.resume = function()\n\t\t{\n\t\t\tChunkStreamer.prototype.resume.apply(this, arguments);\n\t\t\tthis._input.resume();\n\t\t};\n\n\t\tthis.stream = function(stream)\n\t\t{\n\t\t\tthis._input = stream;\n\n\t\t\tthis._input.on('data', this._streamData);\n\t\t\tthis._input.on('end', this._streamEnd);\n\t\t\tthis._input.on('error', this._streamError);\n\t\t};\n\n\t\tthis._checkIsFinished = function()\n\t\t{\n\t\t\tif (streamHasEnded && queue.length === 1) {\n\t\t\t\tthis._finished = true;\n\t\t\t}\n\t\t};\n\n\t\tthis._nextChunk = function()\n\t\t{\n\t\t\tthis._checkIsFinished();\n\t\t\tif (queue.length)\n\t\t\t{\n\t\t\t\tthis.parseChunk(queue.shift());\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tparseOnData = true;\n\t\t\t}\n\t\t};\n\n\t\tthis._streamData = bindFunction(function(chunk)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tqueue.push(typeof chunk === 'string' ? chunk : chunk.toString(this._config.encoding));\n\n\t\t\t\tif (parseOnData)\n\t\t\t\t{\n\t\t\t\t\tparseOnData = false;\n\t\t\t\t\tthis._checkIsFinished();\n\t\t\t\t\tthis.parseChunk(queue.shift());\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (error)\n\t\t\t{\n\t\t\t\tthis._streamError(error);\n\t\t\t}\n\t\t}, this);\n\n\t\tthis._streamError = bindFunction(function(error)\n\t\t{\n\t\t\tthis._streamCleanUp();\n\t\t\tthis._sendError(error);\n\t\t}, this);\n\n\t\tthis._streamEnd = bindFunction(function()\n\t\t{\n\t\t\tthis._streamCleanUp();\n\t\t\tstreamHasEnded = true;\n\t\t\tthis._streamData('');\n\t\t}, this);\n\n\t\tthis._streamCleanUp = bindFunction(function()\n\t\t{\n\t\t\tthis._input.removeListener('data', this._streamData);\n\t\t\tthis._input.removeListener('end', this._streamEnd);\n\t\t\tthis._input.removeListener('error', this._streamError);\n\t\t}, this);\n\t}\n\tReadableStreamStreamer.prototype = Object.create(ChunkStreamer.prototype);\n\tReadableStreamStreamer.prototype.constructor = ReadableStreamStreamer;\n\n\n\tfunction DuplexStreamStreamer(_config) {\n\t\tvar Duplex = require('stream').Duplex;\n\t\tvar config = copy(_config);\n\t\tvar parseOnWrite = true;\n\t\tvar writeStreamHasFinished = false;\n\t\tvar parseCallbackQueue = [];\n\t\tvar stream = null;\n\n\t\tthis._onCsvData = function(results)\n\t\t{\n\t\t\tvar data = results.data;\n\t\t\tif (!stream.push(data) && !this._handle.paused()) {\n\t\t\t\t// the writeable consumer buffer has filled up\n\t\t\t\t// so we need to pause until more items\n\t\t\t\t// can be processed\n\t\t\t\tthis._handle.pause();\n\t\t\t}\n\t\t};\n\n\t\tthis._onCsvComplete = function()\n\t\t{\n\t\t\t// node will finish the read stream when\n\t\t\t// null is pushed\n\t\t\tstream.push(null);\n\t\t};\n\n\t\tconfig.step = bindFunction(this._onCsvData, this);\n\t\tconfig.complete = bindFunction(this._onCsvComplete, this);\n\t\tChunkStreamer.call(this, config);\n\n\t\tthis._nextChunk = function()\n\t\t{\n\t\t\tif (writeStreamHasFinished && parseCallbackQueue.length === 1) {\n\t\t\t\tthis._finished = true;\n\t\t\t}\n\t\t\tif (parseCallbackQueue.length) {\n\t\t\t\tparseCallbackQueue.shift()();\n\t\t\t} else {\n\t\t\t\tparseOnWrite = true;\n\t\t\t}\n\t\t};\n\n\t\tthis._addToParseQueue = function(chunk, callback)\n\t\t{\n\t\t\t// add to queue so that we can indicate\n\t\t\t// completion via callback\n\t\t\t// node will automatically pause the incoming stream\n\t\t\t// when too many items have been added without their\n\t\t\t// callback being invoked\n\t\t\tparseCallbackQueue.push(bindFunction(function() {\n\t\t\t\tthis.parseChunk(typeof chunk === 'string' ? chunk : chunk.toString(config.encoding));\n\t\t\t\tif (isFunction(callback)) {\n\t\t\t\t\treturn callback();\n\t\t\t\t}\n\t\t\t}, this));\n\t\t\tif (parseOnWrite) {\n\t\t\t\tparseOnWrite = false;\n\t\t\t\tthis._nextChunk();\n\t\t\t}\n\t\t};\n\n\t\tthis._onRead = function()\n\t\t{\n\t\t\tif (this._handle.paused()) {\n\t\t\t\t// the writeable consumer can handle more data\n\t\t\t\t// so resume the chunk parsing\n\t\t\t\tthis._handle.resume();\n\t\t\t}\n\t\t};\n\n\t\tthis._onWrite = function(chunk, encoding, callback)\n\t\t{\n\t\t\tthis._addToParseQueue(chunk, callback);\n\t\t};\n\n\t\tthis._onWriteComplete = function()\n\t\t{\n\t\t\twriteStreamHasFinished = true;\n\t\t\t// have to write empty string\n\t\t\t// so parser knows its done\n\t\t\tthis._addToParseQueue('');\n\t\t};\n\n\t\tthis.getStream = function()\n\t\t{\n\t\t\treturn stream;\n\t\t};\n\t\tstream = new Duplex({\n\t\t\treadableObjectMode: true,\n\t\t\tdecodeStrings: false,\n\t\t\tread: bindFunction(this._onRead, this),\n\t\t\twrite: bindFunction(this._onWrite, this)\n\t\t});\n\t\tstream.once('finish', bindFunction(this._onWriteComplete, this));\n\t}\n\tif (typeof PAPA_BROWSER_CONTEXT === 'undefined') {\n\t\tDuplexStreamStreamer.prototype = Object.create(ChunkStreamer.prototype);\n\t\tDuplexStreamStreamer.prototype.constructor = DuplexStreamStreamer;\n\t}\n\n\n\t// Use one ParserHandle per entire CSV file or string\n\tfunction ParserHandle(_config)\n\t{\n\t\t// One goal is to minimize the use of regular expressions...\n\t\tvar MAX_FLOAT = Math.pow(2, 53);\n\t\tvar MIN_FLOAT = -MAX_FLOAT;\n\t\tvar FLOAT = /^\\s*-?(\\d+\\.?|\\.\\d+|\\d+\\.\\d+)([eE][-+]?\\d+)?\\s*$/;\n\t\tvar ISO_DATE = /^((\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d\\.\\d+([+-][0-2]\\d:[0-5]\\d|Z))|(\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d([+-][0-2]\\d:[0-5]\\d|Z))|(\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d([+-][0-2]\\d:[0-5]\\d|Z)))$/;\n\t\tvar self = this;\n\t\tvar _stepCounter = 0;\t// Number of times step was called (number of rows parsed)\n\t\tvar _rowCounter = 0;\t// Number of rows that have been parsed so far\n\t\tvar _input;\t\t\t\t// The input being parsed\n\t\tvar _parser;\t\t\t// The core parser being used\n\t\tvar _paused = false;\t// Whether we are paused or not\n\t\tvar _aborted = false;\t// Whether the parser has aborted or not\n\t\tvar _delimiterError;\t// Temporary state between delimiter detection and processing results\n\t\tvar _fields = [];\t\t// Fields are from the header row of the input, if there is one\n\t\tvar _results = {\t\t// The last results returned from the parser\n\t\t\tdata: [],\n\t\t\terrors: [],\n\t\t\tmeta: {}\n\t\t};\n\n\t\tif (isFunction(_config.step))\n\t\t{\n\t\t\tvar userStep = _config.step;\n\t\t\t_config.step = function(results)\n\t\t\t{\n\t\t\t\t_results = results;\n\n\t\t\t\tif (needsHeaderRow())\n\t\t\t\t\tprocessResults();\n\t\t\t\telse\t// only call user's step function after header row\n\t\t\t\t{\n\t\t\t\t\tprocessResults();\n\n\t\t\t\t\t// It's possbile that this line was empty and there's no row here after all\n\t\t\t\t\tif (_results.data.length === 0)\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\t_stepCounter += results.data.length;\n\t\t\t\t\tif (_config.preview && _stepCounter > _config.preview)\n\t\t\t\t\t\t_parser.abort();\n\t\t\t\t\telse {\n\t\t\t\t\t\t_results.data = _results.data[0];\n\t\t\t\t\t\tuserStep(_results, self);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\n\t\t/**\n\t\t * Parses input. Most users won't need, and shouldn't mess with, the baseIndex\n\t\t * and ignoreLastRow parameters. They are used by streamers (wrapper functions)\n\t\t * when an input comes in multiple chunks, like from a file.\n\t\t */\n\t\tthis.parse = function(input, baseIndex, ignoreLastRow)\n\t\t{\n\t\t\tvar quoteChar = _config.quoteChar || '\"';\n\t\t\tif (!_config.newline)\n\t\t\t\t_config.newline = this.guessLineEndings(input, quoteChar);\n\n\t\t\t_delimiterError = false;\n\t\t\tif (!_config.delimiter)\n\t\t\t{\n\t\t\t\tvar delimGuess = guessDelimiter(input, _config.newline, _config.skipEmptyLines, _config.comments, _config.delimitersToGuess);\n\t\t\t\tif (delimGuess.successful)\n\t\t\t\t\t_config.delimiter = delimGuess.bestDelimiter;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t_delimiterError = true;\t// add error after parsing (otherwise it would be overwritten)\n\t\t\t\t\t_config.delimiter = Papa.DefaultDelimiter;\n\t\t\t\t}\n\t\t\t\t_results.meta.delimiter = _config.delimiter;\n\t\t\t}\n\t\t\telse if(isFunction(_config.delimiter))\n\t\t\t{\n\t\t\t\t_config.delimiter = _config.delimiter(input);\n\t\t\t\t_results.meta.delimiter = _config.delimiter;\n\t\t\t}\n\n\t\t\tvar parserConfig = copy(_config);\n\t\t\t// Tell the parser the header instead of reguessing on each chunk\n\t\t\tparserConfig.header = needsHeaderRow();\n\t\t\tif (_config.preview && _config.header)\n\t\t\t\tparserConfig.preview++;\t// to compensate for header row\n\n\t\t\t_input = input;\n\t\t\t_parser = new Parser(parserConfig);\n\t\t\t_results = _parser.parse(_input, baseIndex, ignoreLastRow);\n\t\t\tprocessResults();\n\t\t\treturn _paused ? { meta: { paused: true } } : (_results || { meta: { paused: false } });\n\t\t};\n\n\t\tthis.paused = function()\n\t\t{\n\t\t\treturn _paused;\n\t\t};\n\n\t\tthis.pause = function()\n\t\t{\n\t\t\t_paused = true;\n\t\t\t_parser.abort();\n\n\t\t\t// If it is streaming via \"chunking\", the reader will start appending correctly already so no need to substring,\n\t\t\t// otherwise we can get duplicate content within a row\n\t\t\t_input = isFunction(_config.chunk) ? \"\" : _input.substring(_parser.getCharIndex());\n\t\t};\n\n\t\tthis.resume = function()\n\t\t{\n\t\t\tif(self.streamer._halted) {\n\t\t\t\t_paused = false;\n\t\t\t\tself.streamer.parseChunk(_input, true);\n\t\t\t} else {\n\t\t\t\t// Bugfix: #636 In case the processing hasn't halted yet\n\t\t\t\t// wait for it to halt in order to resume\n\t\t\t\tsetTimeout(self.resume, 3);\n\t\t\t}\n\t\t};\n\n\t\tthis.aborted = function()\n\t\t{\n\t\t\treturn _aborted;\n\t\t};\n\n\t\tthis.abort = function()\n\t\t{\n\t\t\t_aborted = true;\n\t\t\t_parser.abort();\n\t\t\t_results.meta.aborted = true;\n\t\t\tif (isFunction(_config.complete))\n\t\t\t\t_config.complete(_results);\n\t\t\t_input = '';\n\t\t};\n\n\t\tthis.guessLineEndings = function(input, quoteChar)\n\t\t{\n\t\t\tinput = input.substring(0, 1024 * 1024);\t// max length 1 MB\n\t\t\t// Replace all the text inside quotes\n\t\t\tvar re = new RegExp(escapeRegExp(quoteChar) + '([^]*?)' + escapeRegExp(quoteChar), 'gm');\n\t\t\tinput = input.replace(re, '');\n\n\t\t\tvar r = input.split('\\r');\n\n\t\t\tvar n = input.split('\\n');\n\n\t\t\tvar nAppearsFirst = (n.length > 1 && n[0].length < r[0].length);\n\n\t\t\tif (r.length === 1 || nAppearsFirst)\n\t\t\t\treturn '\\n';\n\n\t\t\tvar numWithN = 0;\n\t\t\tfor (var i = 0; i < r.length; i++)\n\t\t\t{\n\t\t\t\tif (r[i][0] === '\\n')\n\t\t\t\t\tnumWithN++;\n\t\t\t}\n\n\t\t\treturn numWithN >= r.length / 2 ? '\\r\\n' : '\\r';\n\t\t};\n\n\t\tfunction testEmptyLine(s) {\n\t\t\treturn _config.skipEmptyLines === 'greedy' ? s.join('').trim() === '' : s.length === 1 && s[0].length === 0;\n\t\t}\n\n\t\tfunction testFloat(s) {\n\t\t\tif (FLOAT.test(s)) {\n\t\t\t\tvar floatValue = parseFloat(s);\n\t\t\t\tif (floatValue > MIN_FLOAT && floatValue < MAX_FLOAT) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tfunction processResults()\n\t\t{\n\t\t\tif (_results && _delimiterError)\n\t\t\t{\n\t\t\t\taddError('Delimiter', 'UndetectableDelimiter', 'Unable to auto-detect delimiting character; defaulted to \\'' + Papa.DefaultDelimiter + '\\'');\n\t\t\t\t_delimiterError = false;\n\t\t\t}\n\n\t\t\tif (_config.skipEmptyLines)\n\t\t\t{\n\t\t\t\t_results.data = _results.data.filter(function(d) {\n\t\t\t\t\treturn !testEmptyLine(d);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (needsHeaderRow())\n\t\t\t\tfillHeaderFields();\n\n\t\t\treturn applyHeaderAndDynamicTypingAndTransformation();\n\t\t}\n\n\t\tfunction needsHeaderRow()\n\t\t{\n\t\t\treturn _config.header && _fields.length === 0;\n\t\t}\n\n\t\tfunction fillHeaderFields()\n\t\t{\n\t\t\tif (!_results)\n\t\t\t\treturn;\n\n\t\t\tfunction addHeader(header)\n\t\t\t{\n\t\t\t\t_fields.push(header);\n\t\t\t}\n\n\t\t\tif (Array.isArray(_results.data[0]))\n\t\t\t{\n\t\t\t\tfor (var i = 0; needsHeaderRow() && i < _results.data.length; i++)\n\t\t\t\t\t_results.data[i].forEach(addHeader);\n\n\t\t\t\t_results.data.splice(0, 1);\n\t\t\t}\n\t\t\t// if _results.data[0] is not an array, we are in a step where _results.data is the row.\n\t\t\telse\n\t\t\t\t_results.data.forEach(addHeader);\n\t\t}\n\n\t\tfunction shouldApplyDynamicTyping(field) {\n\t\t\t// Cache function values to avoid calling it for each row\n\t\t\tif (_config.dynamicTypingFunction && _config.dynamicTyping[field] === undefined) {\n\t\t\t\t_config.dynamicTyping[field] = _config.dynamicTypingFunction(field);\n\t\t\t}\n\t\t\treturn (_config.dynamicTyping[field] || _config.dynamicTyping) === true;\n\t\t}\n\n\t\tfunction parseDynamic(field, value)\n\t\t{\n\t\t\tif (shouldApplyDynamicTyping(field))\n\t\t\t{\n\t\t\t\tif (value === 'true' || value === 'TRUE')\n\t\t\t\t\treturn true;\n\t\t\t\telse if (value === 'false' || value === 'FALSE')\n\t\t\t\t\treturn false;\n\t\t\t\telse if (testFloat(value))\n\t\t\t\t\treturn parseFloat(value);\n\t\t\t\telse if (ISO_DATE.test(value))\n\t\t\t\t\treturn new Date(value);\n\t\t\t\telse\n\t\t\t\t\treturn (value === '' ? null : value);\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\n\t\tfunction applyHeaderAndDynamicTypingAndTransformation()\n\t\t{\n\t\t\tif (!_results || (!_config.header && !_config.dynamicTyping && !_config.transform))\n\t\t\t\treturn _results;\n\n\t\t\tfunction processRow(rowSource, i)\n\t\t\t{\n\t\t\t\tvar row = _config.header ? {} : [];\n\n\t\t\t\tvar j;\n\t\t\t\tfor (j = 0; j < rowSource.length; j++)\n\t\t\t\t{\n\t\t\t\t\tvar field = j;\n\t\t\t\t\tvar value = rowSource[j];\n\n\t\t\t\t\tif (_config.header)\n\t\t\t\t\t\tfield = j >= _fields.length ? '__parsed_extra' : _fields[j];\n\n\t\t\t\t\tif (_config.transform)\n\t\t\t\t\t\tvalue = _config.transform(value,field);\n\n\t\t\t\t\tvalue = parseDynamic(field, value);\n\n\t\t\t\t\tif (field === '__parsed_extra')\n\t\t\t\t\t{\n\t\t\t\t\t\trow[field] = row[field] || [];\n\t\t\t\t\t\trow[field].push(value);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\trow[field] = value;\n\t\t\t\t}\n\n\n\t\t\t\tif (_config.header)\n\t\t\t\t{\n\t\t\t\t\tif (j > _fields.length)\n\t\t\t\t\t\taddError('FieldMismatch', 'TooManyFields', 'Too many fields: expected ' + _fields.length + ' fields but parsed ' + j, _rowCounter + i);\n\t\t\t\t\telse if (j < _fields.length)\n\t\t\t\t\t\taddError('FieldMismatch', 'TooFewFields', 'Too few fields: expected ' + _fields.length + ' fields but parsed ' + j, _rowCounter + i);\n\t\t\t\t}\n\n\t\t\t\treturn row;\n\t\t\t}\n\n\t\t\tvar incrementBy = 1;\n\t\t\tif (!_results.data.length || Array.isArray(_results.data[0]))\n\t\t\t{\n\t\t\t\t_results.data = _results.data.map(processRow);\n\t\t\t\tincrementBy = _results.data.length;\n\t\t\t}\n\t\t\telse\n\t\t\t\t_results.data = processRow(_results.data, 0);\n\n\n\t\t\tif (_config.header && _results.meta)\n\t\t\t\t_results.meta.fields = _fields;\n\n\t\t\t_rowCounter += incrementBy;\n\t\t\treturn _results;\n\t\t}\n\n\t\tfunction guessDelimiter(input, newline, skipEmptyLines, comments, delimitersToGuess) {\n\t\t\tvar bestDelim, bestDelta, fieldCountPrevRow, maxFieldCount;\n\n\t\t\tdelimitersToGuess = delimitersToGuess || [',', '\\t', '|', ';', Papa.RECORD_SEP, Papa.UNIT_SEP];\n\n\t\t\tfor (var i = 0; i < delimitersToGuess.length; i++) {\n\t\t\t\tvar delim = delimitersToGuess[i];\n\t\t\t\tvar delta = 0, avgFieldCount = 0, emptyLinesCount = 0;\n\t\t\t\tfieldCountPrevRow = undefined;\n\n\t\t\t\tvar preview = new Parser({\n\t\t\t\t\tcomments: comments,\n\t\t\t\t\tdelimiter: delim,\n\t\t\t\t\tnewline: newline,\n\t\t\t\t\tpreview: 10\n\t\t\t\t}).parse(input);\n\n\t\t\t\tfor (var j = 0; j < preview.data.length; j++) {\n\t\t\t\t\tif (skipEmptyLines && testEmptyLine(preview.data[j])) {\n\t\t\t\t\t\temptyLinesCount++;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tvar fieldCount = preview.data[j].length;\n\t\t\t\t\tavgFieldCount += fieldCount;\n\n\t\t\t\t\tif (typeof fieldCountPrevRow === 'undefined') {\n\t\t\t\t\t\tfieldCountPrevRow = fieldCount;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\telse if (fieldCount > 0) {\n\t\t\t\t\t\tdelta += Math.abs(fieldCount - fieldCountPrevRow);\n\t\t\t\t\t\tfieldCountPrevRow = fieldCount;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (preview.data.length > 0)\n\t\t\t\t\tavgFieldCount /= (preview.data.length - emptyLinesCount);\n\n\t\t\t\t// Lowest delta (most consistent field count across rows) wins; average\n\t\t\t\t// field count only breaks ties between equally consistent delimiters.\n\t\t\t\tif (avgFieldCount > 1.99 && (typeof bestDelta === 'undefined'\n\t\t\t\t\t|| delta < bestDelta\n\t\t\t\t\t|| (delta === bestDelta && avgFieldCount > maxFieldCount))) {\n\t\t\t\t\tbestDelta = delta;\n\t\t\t\t\tbestDelim = delim;\n\t\t\t\t\tmaxFieldCount = avgFieldCount;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t_config.delimiter = bestDelim;\n\n\t\t\treturn {\n\t\t\t\tsuccessful: !!bestDelim,\n\t\t\t\tbestDelimiter: bestDelim\n\t\t\t};\n\t\t}\n\n\t\tfunction addError(type, code, msg, row)\n\t\t{\n\t\t\tvar error = {\n\t\t\t\ttype: type,\n\t\t\t\tcode: code,\n\t\t\t\tmessage: msg\n\t\t\t};\n\t\t\tif(row !== undefined) {\n\t\t\t\terror.row = row;\n\t\t\t}\n\t\t\t_results.errors.push(error);\n\t\t}\n\t}\n\n\t/** https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions */\n\tfunction escapeRegExp(string)\n\t{\n\t\treturn string.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'); // $& means the whole matched string\n\t}\n\n\t/** The core parser implements speedy and correct CSV parsing */\n\tfunction Parser(config)\n\t{\n\t\t// Unpack the config object\n\t\tconfig = config || {};\n\t\tvar delim = config.delimiter;\n\t\tvar newline = config.newline;\n\t\tvar comments = config.comments;\n\t\tvar step = config.step;\n\t\tvar preview = config.preview;\n\t\tvar fastMode = config.fastMode;\n\t\tvar quoteChar;\n\t\tvar renamedHeaders = null;\n\t\tvar headerParsed = false;\n\n\t\tif (config.quoteChar === undefined || config.quoteChar === null) {\n\t\t\tquoteChar = '\"';\n\t\t} else {\n\t\t\tquoteChar = config.quoteChar;\n\t\t}\n\t\tvar escapeChar = quoteChar;\n\t\tif (config.escapeChar !== undefined) {\n\t\t\tescapeChar = config.escapeChar;\n\t\t}\n\n\t\t// Delimiter must be valid\n\t\tif (typeof delim !== 'string'\n\t\t\t|| Papa.BAD_DELIMITERS.indexOf(delim) > -1)\n\t\t\tdelim = ',';\n\n\t\t// Comment character must be valid\n\t\tif (comments === delim)\n\t\t\tthrow new Error('Comment character same as delimiter');\n\t\telse if (comments === true)\n\t\t\tcomments = '#';\n\t\telse if (typeof comments !== 'string'\n\t\t\t|| Papa.BAD_DELIMITERS.indexOf(comments) > -1)\n\t\t\tcomments = false;\n\n\t\t// Newline must be valid: \\r, \\n, or \\r\\n\n\t\tif (newline !== '\\n' && newline !== '\\r' && newline !== '\\r\\n')\n\t\t\tnewline = '\\n';\n\n\t\t// We're gonna need these at the Parser scope\n\t\tvar cursor = 0;\n\t\tvar aborted = false;\n\n\t\tthis.parse = function(input, baseIndex, ignoreLastRow)\n\t\t{\n\t\t\t// For some reason, in Chrome, this speeds things up (!?)\n\t\t\tif (typeof input !== 'string')\n\t\t\t\tthrow new Error('Input must be a string');\n\n\t\t\t// We don't need to compute some of these every time parse() is called,\n\t\t\t// but having them in a more local scope seems to perform better\n\t\t\tvar inputLen = input.length,\n\t\t\t\tdelimLen = delim.length,\n\t\t\t\tnewlineLen = newline.length,\n\t\t\t\tcommentsLen = comments.length;\n\t\t\tvar stepIsFunction = isFunction(step);\n\n\t\t\t// Establish starting state\n\t\t\tcursor = 0;\n\t\t\tvar data = [], errors = [], row = [], lastCursor = 0;\n\n\t\t\tif (!input)\n\t\t\t\treturn returnable();\n\n\t\t\tif (fastMode || (fastMode !== false && input.indexOf(quoteChar) === -1))\n\t\t\t{\n\t\t\t\tvar rows = input.split(newline);\n\t\t\t\tfor (var i = 0; i < rows.length; i++)\n\t\t\t\t{\n\t\t\t\t\trow = rows[i];\n\t\t\t\t\tcursor += row.length;\n\n\t\t\t\t\tif (i !== rows.length - 1)\n\t\t\t\t\t\tcursor += newline.length;\n\t\t\t\t\telse if (ignoreLastRow)\n\t\t\t\t\t\treturn returnable();\n\t\t\t\t\tif (comments && row.substring(0, commentsLen) === comments)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tif (stepIsFunction)\n\t\t\t\t\t{\n\t\t\t\t\t\tdata = [];\n\t\t\t\t\t\tpushRow(row.split(delim));\n\t\t\t\t\t\tdoStep();\n\t\t\t\t\t\tif (aborted)\n\t\t\t\t\t\t\treturn returnable();\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tpushRow(row.split(delim));\n\t\t\t\t\tif (preview && i >= preview)\n\t\t\t\t\t{\n\t\t\t\t\t\tdata = data.slice(0, preview);\n\t\t\t\t\t\treturn returnable(true);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn returnable();\n\t\t\t}\n\n\t\t\tvar nextDelim = input.indexOf(delim, cursor);\n\t\t\tvar nextNewline = input.indexOf(newline, cursor);\n\t\t\tvar quoteCharRegex = new RegExp(escapeRegExp(escapeChar) + escapeRegExp(quoteChar), 'g');\n\t\t\tvar quoteSearch = input.indexOf(quoteChar, cursor);\n\n\t\t\t// Parser loop\n\t\t\tfor (;;)\n\t\t\t{\n\t\t\t\t// Field has opening quote\n\t\t\t\tif (input[cursor] === quoteChar)\n\t\t\t\t{\n\t\t\t\t\t// Start our search for the closing quote where the cursor is\n\t\t\t\t\tquoteSearch = cursor;\n\n\t\t\t\t\t// Skip the opening quote\n\t\t\t\t\tcursor++;\n\n\t\t\t\t\tfor (;;)\n\t\t\t\t\t{\n\t\t\t\t\t\t// Find closing quote\n\t\t\t\t\t\tquoteSearch = input.indexOf(quoteChar, quoteSearch + 1);\n\n\t\t\t\t\t\t//No other quotes are found - no other delimiters\n\t\t\t\t\t\tif (quoteSearch === -1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (!ignoreLastRow) {\n\t\t\t\t\t\t\t\t// No closing quote... what a pity\n\t\t\t\t\t\t\t\terrors.push({\n\t\t\t\t\t\t\t\t\ttype: 'Quotes',\n\t\t\t\t\t\t\t\t\tcode: 'MissingQuotes',\n\t\t\t\t\t\t\t\t\tmessage: 'Quoted field unterminated',\n\t\t\t\t\t\t\t\t\trow: data.length,\t// row has yet to be inserted\n\t\t\t\t\t\t\t\t\tindex: cursor\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn finish();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Closing quote at EOF\n\t\t\t\t\t\tif (quoteSearch === inputLen - 1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvar value = input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar);\n\t\t\t\t\t\t\treturn finish(value);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// If this quote is escaped, it's part of the data; skip it\n\t\t\t\t\t\t// If the quote character is the escape character, then check if the next character is the escape character\n\t\t\t\t\t\tif (quoteChar === escapeChar && input[quoteSearch + 1] === escapeChar)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tquoteSearch++;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// If the quote character is not the escape character, then check if the previous character was the escape character\n\t\t\t\t\t\tif (quoteChar !== escapeChar && quoteSearch !== 0 && input[quoteSearch - 1] === escapeChar)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif(nextDelim !== -1 && nextDelim < (quoteSearch + 1)) {\n\t\t\t\t\t\t\tnextDelim = input.indexOf(delim, (quoteSearch + 1));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(nextNewline !== -1 && nextNewline < (quoteSearch + 1)) {\n\t\t\t\t\t\t\tnextNewline = input.indexOf(newline, (quoteSearch + 1));\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Check up to nextDelim or nextNewline, whichever is closest\n\t\t\t\t\t\tvar checkUpTo = nextNewline === -1 ? nextDelim : Math.min(nextDelim, nextNewline);\n\t\t\t\t\t\tvar spacesBetweenQuoteAndDelimiter = extraSpaces(checkUpTo);\n\n\t\t\t\t\t\t// Closing quote followed by delimiter or 'unnecessary spaces + delimiter'\n\t\t\t\t\t\tif (input.substr(quoteSearch + 1 + spacesBetweenQuoteAndDelimiter, delimLen) === delim)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\trow.push(input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar));\n\t\t\t\t\t\t\tcursor = quoteSearch + 1 + spacesBetweenQuoteAndDelimiter + delimLen;\n\n\t\t\t\t\t\t\t// If char after following delimiter is not quoteChar, we find next quote char position\n\t\t\t\t\t\t\tif (input[quoteSearch + 1 + spacesBetweenQuoteAndDelimiter + delimLen] !== quoteChar)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tquoteSearch = input.indexOf(quoteChar, cursor);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (nextDelim !== -1 && nextDelim < cursor)\n\t\t\t\t\t\t\t\tnextDelim = input.indexOf(delim, cursor);\n\t\t\t\t\t\t\tif (nextNewline !== -1 && nextNewline < cursor)\n\t\t\t\t\t\t\t\tnextNewline = input.indexOf(newline, cursor);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tvar spacesBetweenQuoteAndNewLine = extraSpaces(nextNewline);\n\n\t\t\t\t\t\t// Closing quote followed by newline or 'unnecessary spaces + newLine'\n\t\t\t\t\t\tif (input.substring(quoteSearch + 1 + spacesBetweenQuoteAndNewLine, quoteSearch + 1 + spacesBetweenQuoteAndNewLine + newlineLen) === newline)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\trow.push(input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar));\n\t\t\t\t\t\t\tsaveRow(quoteSearch + 1 + spacesBetweenQuoteAndNewLine + newlineLen);\n\t\t\t\t\t\t\t// Only search again if we skipped a delimiter in the quoted field.\n\t\t\t\t\t\t\tif (nextDelim !== -1 && nextDelim < cursor)\n\t\t\t\t\t\t\t\tnextDelim = input.indexOf(delim, cursor);\n\t\t\t\t\t\t\tquoteSearch = input.indexOf(quoteChar, cursor);\t// we search for first quote in next line\n\n\t\t\t\t\t\t\tif (stepIsFunction)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tdoStep();\n\t\t\t\t\t\t\t\tif (aborted)\n\t\t\t\t\t\t\t\t\treturn returnable();\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (preview && data.length >= preview)\n\t\t\t\t\t\t\t\treturn returnable(true);\n\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\n\t\t\t\t\t\t// Checks for valid closing quotes are complete (escaped quotes or quote followed by EOF/delimiter/newline) -- assume these quotes are part of an invalid text string\n\t\t\t\t\t\terrors.push({\n\t\t\t\t\t\t\ttype: 'Quotes',\n\t\t\t\t\t\t\tcode: 'InvalidQuotes',\n\t\t\t\t\t\t\tmessage: 'Trailing quote on quoted field is malformed',\n\t\t\t\t\t\t\trow: data.length,\t// row has yet to be inserted\n\t\t\t\t\t\t\tindex: cursor\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tquoteSearch++;\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Comment found at start of new line\n\t\t\t\tif (comments && row.length === 0 && input.substring(cursor, cursor + commentsLen) === comments)\n\t\t\t\t{\n\t\t\t\t\tif (nextNewline === -1)\t// Comment ends at EOF\n\t\t\t\t\t\treturn returnable();\n\t\t\t\t\tcursor = nextNewline + newlineLen;\n\t\t\t\t\tnextNewline = input.indexOf(newline, cursor);\n\t\t\t\t\tif (nextDelim !== -1 && nextDelim < cursor)\n\t\t\t\t\t\tnextDelim = input.indexOf(delim, cursor);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Next delimiter comes before next newline, so we've reached end of field\n\t\t\t\tif (nextDelim !== -1 && (nextDelim < nextNewline || nextNewline === -1))\n\t\t\t\t{\n\t\t\t\t\trow.push(input.substring(cursor, nextDelim));\n\t\t\t\t\tcursor = nextDelim + delimLen;\n\t\t\t\t\t// we look for next delimiter char\n\t\t\t\t\tnextDelim = input.indexOf(delim, cursor);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// End of row\n\t\t\t\tif (nextNewline !== -1)\n\t\t\t\t{\n\t\t\t\t\trow.push(input.substring(cursor, nextNewline));\n\t\t\t\t\tsaveRow(nextNewline + newlineLen);\n\n\t\t\t\t\tif (stepIsFunction)\n\t\t\t\t\t{\n\t\t\t\t\t\tdoStep();\n\t\t\t\t\t\tif (aborted)\n\t\t\t\t\t\t\treturn returnable();\n\t\t\t\t\t}\n\n\t\t\t\t\tif (preview && data.length >= preview)\n\t\t\t\t\t\treturn returnable(true);\n\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\treturn finish();\n\n\n\t\t\tfunction pushRow(row)\n\t\t\t{\n\t\t\t\tdata.push(row);\n\t\t\t\tlastCursor = cursor;\n\t\t\t}\n\n\t\t\t/**\n * checks if there are extra spaces after closing quote and given index without any text\n * if Yes, returns the number of spaces\n */\n\t\t\tfunction extraSpaces(index) {\n\t\t\t\tvar spaceLength = 0;\n\t\t\t\tif (index !== -1) {\n\t\t\t\t\tvar textBetweenClosingQuoteAndIndex = input.substring(quoteSearch + 1, index);\n\t\t\t\t\tif (textBetweenClosingQuoteAndIndex && textBetweenClosingQuoteAndIndex.trim() === '') {\n\t\t\t\t\t\tspaceLength = textBetweenClosingQuoteAndIndex.length;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn spaceLength;\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Appends the remaining input from cursor to the end into\n\t\t\t * row, saves the row, calls step, and returns the results.\n\t\t\t */\n\t\t\tfunction finish(value)\n\t\t\t{\n\t\t\t\tif (ignoreLastRow)\n\t\t\t\t\treturn returnable();\n\t\t\t\tif (typeof value === 'undefined')\n\t\t\t\t\tvalue = input.substring(cursor);\n\t\t\t\trow.push(value);\n\t\t\t\tcursor = inputLen;\t// important in case parsing is paused\n\t\t\t\tpushRow(row);\n\t\t\t\tif (stepIsFunction)\n\t\t\t\t\tdoStep();\n\t\t\t\treturn returnable();\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Appends the current row to the results. It sets the cursor\n\t\t\t * to newCursor and finds the nextNewline. The caller should\n\t\t\t * take care to execute user's step function and check for\n\t\t\t * preview and end parsing if necessary.\n\t\t\t */\n\t\t\tfunction saveRow(newCursor)\n\t\t\t{\n\t\t\t\tcursor = newCursor;\n\t\t\t\tpushRow(row);\n\t\t\t\trow = [];\n\t\t\t\tnextNewline = input.indexOf(newline, cursor);\n\t\t\t}\n\n\t\t\t/** Returns an object with the results, errors, and meta. */\n\t\t\tfunction returnable(stopped)\n\t\t\t{\n\t\t\t\tif (config.header && !baseIndex && data.length && !headerParsed)\n\t\t\t\t{\n\t\t\t\t\tconst result = data[0];\n\t\t\t\t\tconst headerCount = Object.create(null); // To track the count of each base header\n\t\t\t\t\tconst usedHeaders = new Set(result); // To track used headers and avoid duplicates\n\t\t\t\t\tlet duplicateHeaders = false;\n\n\t\t\t\t\tfor (let i = 0; i < result.length; i++) {\n\t\t\t\t\t\tlet header = stripBom(result[i]);\n\t\t\t\t\t\tif (isFunction(config.transformHeader))\n\t\t\t\t\t\t\theader = config.transformHeader(header, i);\n\n\t\t\t\t\t\tif (!headerCount[header]) {\n\t\t\t\t\t\t\theaderCount[header] = 1;\n\t\t\t\t\t\t\tresult[i] = header;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlet newHeader;\n\t\t\t\t\t\t\tlet suffixCount = headerCount[header];\n\n\t\t\t\t\t\t\t// Find a unique new header\n\t\t\t\t\t\t\tdo {\n\t\t\t\t\t\t\t\tnewHeader = `${header}_${suffixCount}`;\n\t\t\t\t\t\t\t\tsuffixCount++;\n\t\t\t\t\t\t\t} while (usedHeaders.has(newHeader));\n\n\t\t\t\t\t\t\tusedHeaders.add(newHeader); // Mark this new Header as used\n\t\t\t\t\t\t\tresult[i] = newHeader;\n\t\t\t\t\t\t\theaderCount[header]++;\n\t\t\t\t\t\t\tduplicateHeaders = true;\n\t\t\t\t\t\t\tif (renamedHeaders === null) {\n\t\t\t\t\t\t\t\trenamedHeaders = {};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\trenamedHeaders[newHeader] = header;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tusedHeaders.add(header); // Ensure the original header is marked as used\n\t\t\t\t\t}\n\t\t\t\t\tif (duplicateHeaders) {\n\t\t\t\t\t\tconsole.warn('Duplicate headers found and renamed.');\n\t\t\t\t\t}\n\t\t\t\t\theaderParsed = true;\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tdata: data,\n\t\t\t\t\terrors: errors,\n\t\t\t\t\tmeta: {\n\t\t\t\t\t\tdelimiter: delim,\n\t\t\t\t\t\tlinebreak: newline,\n\t\t\t\t\t\taborted: aborted,\n\t\t\t\t\t\ttruncated: !!stopped,\n\t\t\t\t\t\tcursor: lastCursor + (baseIndex || 0),\n\t\t\t\t\t\trenamedHeaders: renamedHeaders\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t/** Executes the user's step function and resets data & errors. */\n\t\t\tfunction doStep()\n\t\t\t{\n\t\t\t\tstep(returnable());\n\t\t\t\tdata = [];\n\t\t\t\terrors = [];\n\t\t\t}\n\t\t};\n\n\t\t/** Sets the abort flag */\n\t\tthis.abort = function()\n\t\t{\n\t\t\taborted = true;\n\t\t};\n\n\t\t/** Gets the cursor position */\n\t\tthis.getCharIndex = function()\n\t\t{\n\t\t\treturn cursor;\n\t\t};\n\t}\n\n\n\tfunction newWorker()\n\t{\n\t\tif (!Papa.WORKERS_SUPPORTED)\n\t\t\treturn false;\n\n\t\tvar workerUrl = getWorkerBlob();\n\t\tvar w = new global.Worker(workerUrl);\n\t\tw.onmessage = mainThreadReceivedMessage;\n\t\tw.id = workerIdCounter++;\n\t\tworkers[w.id] = w;\n\t\treturn w;\n\t}\n\n\t/** Callback when main thread receives a message */\n\tfunction mainThreadReceivedMessage(e)\n\t{\n\t\tvar msg = e.data;\n\t\tvar worker = workers[msg.workerId];\n\t\tvar aborted = false;\n\n\t\tif (msg.error)\n\t\t\tworker.userError(msg.error, msg.file);\n\t\telse if (msg.results && msg.results.data)\n\t\t{\n\t\t\tvar abort = function() {\n\t\t\t\taborted = true;\n\t\t\t\tcompleteWorker(msg.workerId, { data: [], errors: [], meta: { aborted: true } });\n\t\t\t};\n\n\t\t\tvar handle = {\n\t\t\t\tabort: abort,\n\t\t\t\tpause: notImplemented,\n\t\t\t\tresume: notImplemented\n\t\t\t};\n\n\t\t\tif (isFunction(worker.userStep))\n\t\t\t{\n\t\t\t\tfor (var i = 0; i < msg.results.data.length; i++)\n\t\t\t\t{\n\t\t\t\t\tworker.userStep({\n\t\t\t\t\t\tdata: msg.results.data[i],\n\t\t\t\t\t\terrors: msg.results.errors,\n\t\t\t\t\t\tmeta: msg.results.meta\n\t\t\t\t\t}, handle);\n\t\t\t\t\tif (aborted)\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdelete msg.results;\t// free memory ASAP\n\t\t\t}\n\t\t\telse if (isFunction(worker.userChunk))\n\t\t\t{\n\t\t\t\tworker.userChunk(msg.results, handle, msg.file);\n\t\t\t\tdelete msg.results;\n\t\t\t}\n\t\t}\n\n\t\tif (msg.finished && !aborted)\n\t\t\tcompleteWorker(msg.workerId, msg.results);\n\t}\n\n\tfunction completeWorker(workerId, results) {\n\t\tvar worker = workers[workerId];\n\t\tif (isFunction(worker.userComplete))\n\t\t\tworker.userComplete(results);\n\t\tworker.terminate();\n\t\tdelete workers[workerId];\n\t}\n\n\tfunction notImplemented() {\n\t\tthrow new Error('Not implemented.');\n\t}\n\n\t/** Callback when worker thread receives a message */\n\tfunction workerThreadReceivedMessage(e)\n\t{\n\t\tvar msg = e.data;\n\n\t\tif (typeof Papa.WORKER_ID === 'undefined' && msg)\n\t\t\tPapa.WORKER_ID = msg.workerId;\n\n\t\tif (typeof msg.input === 'string')\n\t\t{\n\t\t\tglobal.postMessage({\n\t\t\t\tworkerId: Papa.WORKER_ID,\n\t\t\t\tresults: Papa.parse(msg.input, msg.config),\n\t\t\t\tfinished: true\n\t\t\t});\n\t\t}\n\t\telse if ((global.File && msg.input instanceof File) || msg.input instanceof Object)\t// thank you, Safari (see issue #106)\n\t\t{\n\t\t\tvar results = Papa.parse(msg.input, msg.config);\n\t\t\tif (results)\n\t\t\t\tglobal.postMessage({\n\t\t\t\t\tworkerId: Papa.WORKER_ID,\n\t\t\t\t\tresults: results,\n\t\t\t\t\tfinished: true\n\t\t\t\t});\n\t\t}\n\t}\n\n\t/** Makes a deep copy of an array or object (mostly) */\n\tfunction copy(obj)\n\t{\n\t\tif (typeof obj !== 'object' || obj === null)\n\t\t\treturn obj;\n\t\tvar cpy = Array.isArray(obj) ? [] : {};\n\t\tfor (var key in obj)\n\t\t\tcpy[key] = copy(obj[key]);\n\t\treturn cpy;\n\t}\n\n\tfunction bindFunction(f, self)\n\t{\n\t\treturn function() { f.apply(self, arguments); };\n\t}\n\tfunction isFunction(func)\n\t{\n\t\treturn typeof func === 'function';\n\t}\n\n\treturn Papa;\n}));\n", "import path from \"node:path\";\nimport { config } from \"dotenv\";\n\n/** Load local CLI credentials without changing the application's environment files. */\nif (process.env.GO_LABS_CLI_SKIP_DOTENV !== \"1\") {\n\tconfig({ path: path.resolve(process.cwd(), \".env\"), quiet: true });\n}\n", "import { createHash, randomUUID } from \"node:crypto\";\nimport {\n\tchmod,\n\tlstat,\n\tmkdir,\n\topen,\n\treadFile,\n\tstat,\n\tunlink,\n} from \"node:fs/promises\";\nimport { userInfo } from \"node:os\";\nimport { join } from \"node:path\";\nimport type {\n\tCliProduct,\n\tStoredCliCredentials,\n} from \"@go-labs/cli-auth/protocol\";\nimport { storedCliCredentialsSchema } from \"@go-labs/cli-auth/protocol\";\nimport { createIsolatedBunSecrets } from \"./secret-backend\";\nimport {\n\tCliCredentialStoreUnavailableError,\n\ttype CredentialStoreFailure,\n\tclassifyCredentialStoreFailure,\n} from \"./storage-error\";\n\nexport { CliCredentialStoreUnavailableError } from \"./storage-error\";\n\nexport interface SecretsApi {\n\tdelete(input: { name: string; service: string }): Promise<boolean>;\n\tget(input: { name: string; service: string }): Promise<string | null>;\n\tset(input: { name: string; service: string; value: string }): Promise<void>;\n}\n\nexport interface CliCredentialStore {\n\tpreflight?(): Promise<void>;\n\tdelete(): Promise<void>;\n\tget(): Promise<StoredCliCredentials | null>;\n\tset(credentials: StoredCliCredentials): Promise<void>;\n\twithCredentialLock?<Result>(\n\t\toperation: () => Promise<Result>,\n\t): Promise<Result>;\n}\n\nconst runSecretOperation = async <Result>(\n\tproduct: CliProduct,\n\toperation: () => Promise<Result>,\n\tfallback: CredentialStoreFailure = \"read-failed\",\n): Promise<Result> => {\n\ttry {\n\t\treturn await operation();\n\t} catch (cause) {\n\t\tif (cause instanceof CliCredentialStoreUnavailableError) throw cause;\n\t\tthrow new CliCredentialStoreUnavailableError(\n\t\t\tproduct,\n\t\t\tclassifyCredentialStoreFailure(\n\t\t\t\tcause instanceof Error ? cause.message : \"\",\n\t\t\t\tfallback,\n\t\t\t),\n\t\t);\n\t}\n};\n\nconst refreshLockTimeoutMs = 5 * 60 * 1000;\nconst refreshLockRetryMs = 50;\n\nconst getCredentialLockDirectoryPath = (): string => {\n\treturn join(userInfo().homedir, \".cache\", \"go-labs-cli\", \"locks\");\n};\n\nconst ensurePrivateCredentialLockDirectory = async (): Promise<string> => {\n\tconst directory = getCredentialLockDirectoryPath();\n\tawait mkdir(directory, { mode: 0o700, recursive: true });\n\n\tconst inspectDirectory = async () => {\n\t\tconst directoryStat = await lstat(directory);\n\t\tif (directoryStat.isSymbolicLink() || !directoryStat.isDirectory()) {\n\t\t\tthrow new Error(\n\t\t\t\t\"The CLI credential lock path is not a private directory.\",\n\t\t\t);\n\t\t}\n\t\tconst uid = process.getuid?.();\n\t\tif (uid !== undefined && directoryStat.uid !== uid) {\n\t\t\tthrow new Error(\n\t\t\t\t\"The CLI credential lock directory belongs to another user.\",\n\t\t\t);\n\t\t}\n\t\treturn directoryStat;\n\t};\n\n\tconst directoryStat = await inspectDirectory();\n\t// Windows mode bits do not describe NTFS ACLs, and chmod cannot enforce 0700.\n\t// Lock files contain only random ownership markers; credentials stay in Bun.secrets.\n\tif (process.platform !== \"win32\" && (directoryStat.mode & 0o077) !== 0) {\n\t\tawait chmod(directory, 0o700);\n\t\tconst securedDirectoryStat = await inspectDirectory();\n\t\tif ((securedDirectoryStat.mode & 0o077) !== 0) {\n\t\t\tthrow new Error(\"Unable to secure the CLI credential lock directory.\");\n\t\t}\n\t}\n\n\treturn directory;\n};\n\nconst getCredentialLockPath = async (\n\tproduct: CliProduct,\n\taccount: string,\n): Promise<string> => {\n\tconst key = createHash(\"sha256\")\n\t\t.update(`${product}:${account}`)\n\t\t.digest(\"hex\");\n\treturn join(await ensurePrivateCredentialLockDirectory(), `${key}.lock`);\n};\n\nconst hasErrorCode = (cause: unknown, code: string): boolean =>\n\tcause instanceof Error && \"code\" in cause && cause.code === code;\n\nconst createRefreshLockFile = async (path: string) => {\n\tconst handle = await open(path, \"wx\");\n\tconst owner = randomUUID();\n\ttry {\n\t\tawait handle.writeFile(owner);\n\t} catch (cause) {\n\t\tawait handle.close().catch(() => undefined);\n\t\tawait unlink(path).catch(() => undefined);\n\t\tthrow cause;\n\t}\n\treturn { handle, owner };\n};\n\n/** Resolves true when the lock vanished (retry now); throws when stale. */\nconst refreshLockVanished = async (path: string): Promise<boolean> => {\n\ttry {\n\t\tconst lock = await stat(path);\n\t\tif (Date.now() - lock.mtimeMs > refreshLockTimeoutMs) {\n\t\t\tthrow new Error(\n\t\t\t\t`The CLI credential lock appears stale at ${path}. Ensure no CLI authentication command is running, remove that lock file, and retry.`,\n\t\t\t);\n\t\t}\n\t} catch (statCause) {\n\t\tif (hasErrorCode(statCause, \"ENOENT\")) {\n\t\t\treturn true;\n\t\t}\n\t\tthrow statCause;\n\t}\n\treturn false;\n};\n\nconst acquireRefreshLock = async (path: string) => {\n\tconst deadline = Date.now() + refreshLockTimeoutMs;\n\twhile (Date.now() < deadline) {\n\t\ttry {\n\t\t\treturn await createRefreshLockFile(path);\n\t\t} catch (cause) {\n\t\t\tif (!hasErrorCode(cause, \"EEXIST\")) {\n\t\t\t\tthrow cause;\n\t\t\t}\n\t\t\tif (await refreshLockVanished(path)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tawait Bun.sleep(refreshLockRetryMs);\n\t\t}\n\t}\n\tthrow new Error(\n\t\t\"Timed out waiting for another CLI process to refresh credentials. Retry the command.\",\n\t);\n};\n\n/** Select the native credential-store account; staging launchers set `staging`. */\nexport const resolveCliCredentialAccount = (\n\tenvironment: Readonly<Record<string, string | undefined>> = process.env,\n) => environment.GO_LABS_CLI_CREDENTIAL_ACCOUNT?.trim() || \"default\";\n\nexport const createBunCredentialStore = ({\n\taccount = resolveCliCredentialAccount(),\n\tproduct,\n\tsecrets = createIsolatedBunSecrets(product),\n}: {\n\taccount?: string;\n\tproduct: CliProduct;\n\tsecrets?: SecretsApi;\n}): CliCredentialStore => {\n\tconst service = `go-labs-cli:${product}`;\n\treturn {\n\t\tpreflight: async () => {\n\t\t\tconst input = { name: `probe-${randomUUID()}`, service };\n\t\t\tconst value = `go-labs-non-secret-probe:${randomUUID()}`;\n\t\t\ttry {\n\t\t\t\tawait runSecretOperation(\n\t\t\t\t\tproduct,\n\t\t\t\t\t() => secrets.set({ ...input, value }),\n\t\t\t\t\t\"write-failed\",\n\t\t\t\t);\n\t\t\t\tif (\n\t\t\t\t\t(await runSecretOperation(product, () => secrets.get(input))) !==\n\t\t\t\t\tvalue\n\t\t\t\t) {\n\t\t\t\t\tthrow new CliCredentialStoreUnavailableError(product, \"write-failed\");\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\t// Cleanup must not hide the original capability diagnosis.\n\t\t\t\tawait secrets.delete(input).catch(() => undefined);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tawait runSecretOperation(\n\t\t\t\tproduct,\n\t\t\t\t() => secrets.delete(input),\n\t\t\t\t\"delete-failed\",\n\t\t\t);\n\t\t\tif (\n\t\t\t\t(await runSecretOperation(product, () => secrets.get(input))) !== null\n\t\t\t) {\n\t\t\t\tthrow new CliCredentialStoreUnavailableError(product, \"delete-failed\");\n\t\t\t}\n\t\t},\n\t\tdelete: async () => {\n\t\t\tawait runSecretOperation(\n\t\t\t\tproduct,\n\t\t\t\t() => secrets.delete({ name: account, service }),\n\t\t\t\t\"delete-failed\",\n\t\t\t);\n\t\t},\n\t\tget: async () => {\n\t\t\tconst value = await runSecretOperation(product, () =>\n\t\t\t\tsecrets.get({ name: account, service }),\n\t\t\t);\n\t\t\tif (value === null) return null;\n\t\t\ttry {\n\t\t\t\treturn storedCliCredentialsSchema.parse(JSON.parse(value));\n\t\t\t} catch {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`The ${product} CLI credential-store entry contains invalid credentials. Run auth logout and sign in again.`,\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\t\tset: async (credentials) => {\n\t\t\tconst parsed = storedCliCredentialsSchema.parse(credentials);\n\t\t\tawait runSecretOperation(\n\t\t\t\tproduct,\n\t\t\t\t() =>\n\t\t\t\t\tsecrets.set({\n\t\t\t\t\t\tname: account,\n\t\t\t\t\t\tservice,\n\t\t\t\t\t\tvalue: JSON.stringify(parsed),\n\t\t\t\t\t}),\n\t\t\t\t\"write-failed\",\n\t\t\t);\n\t\t},\n\t\twithCredentialLock: async <Result>(operation: () => Promise<Result>) => {\n\t\t\tconst refreshLockPath = await getCredentialLockPath(product, account);\n\t\t\tconst lock = await acquireRefreshLock(refreshLockPath);\n\t\t\ttry {\n\t\t\t\treturn await operation();\n\t\t\t} finally {\n\t\t\t\tawait lock.handle.close();\n\t\t\t\tconst owner = await readFile(refreshLockPath, \"utf8\").catch(() => null);\n\t\t\t\tif (owner === lock.owner) {\n\t\t\t\t\tawait unlink(refreshLockPath).catch(() => undefined);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t};\n};\n", "export const CLI_ACCESS_TOKEN_TTL_MS = 15 * 60 * 1000;\nexport const CLI_DEVICE_AUTHORIZATION_TTL_MS = 10 * 60 * 1000;\nexport const CLI_DEVICE_POLL_INTERVAL_SECONDS = 5;\nexport const CLI_DEVICE_BOOTSTRAP_LIMIT_PER_SOURCE = 20;\nexport const CLI_REFRESH_ABSOLUTE_TTL_MS = 180 * 24 * 60 * 60 * 1000;\nexport const CLI_REFRESH_INACTIVITY_TTL_MS = 30 * 24 * 60 * 60 * 1000;\n\nexport const cliProducts = [\n\t\"budget-builder\",\n\t\"event-tech\",\n\t\"rsvp\",\n\t\"gosh\",\n] as const;\nexport type CliProduct = (typeof cliProducts)[number];\n", "import { createHash, randomBytes, timingSafeEqual } from \"node:crypto\";\n\nconst base64Url = (value: Uint8Array) =>\n\tBuffer.from(value).toString(\"base64url\");\nconst USER_CODE_ALPHABET = \"ABCDEFGHJKLMNPQRSTUVWXYZ23456789\";\n\nexport const generateOpaqueSecret = (prefix: string): string =>\n\t`${prefix}${base64Url(randomBytes(32))}`;\n\nexport const generateDeviceCode = (): string => generateOpaqueSecret(\"dc_\");\n\nexport const generateUserCode = (): string => {\n\tconst bytes = randomBytes(8);\n\tconst characters = Array.from(\n\t\tbytes,\n\t\t(byte) => USER_CODE_ALPHABET[byte % USER_CODE_ALPHABET.length],\n\t);\n\treturn `${characters.slice(0, 4).join(\"\")}-${characters.slice(4).join(\"\")}`;\n};\n\nexport const hashSecret = (value: string): string =>\n\tcreateHash(\"sha256\").update(value, \"utf8\").digest(\"hex\");\n\nexport interface PkcePair {\n\tchallenge: string;\n\tmethod: \"S256\";\n\tverifier: string;\n}\n\nexport const createPkcePair = (): PkcePair => {\n\tconst verifier = base64Url(randomBytes(32));\n\treturn {\n\t\tchallenge: base64Url(\n\t\t\tcreateHash(\"sha256\").update(verifier, \"ascii\").digest(),\n\t\t),\n\t\tmethod: \"S256\",\n\t\tverifier,\n\t};\n};\n\nexport const verifyPkce = (\n\tverifier: string,\n\texpectedChallenge: string,\n): boolean => {\n\tconst actual = base64Url(\n\t\tcreateHash(\"sha256\").update(verifier, \"ascii\").digest(),\n\t);\n\tconst actualBytes = Buffer.from(actual, \"utf8\");\n\tconst expectedBytes = Buffer.from(expectedChallenge, \"utf8\");\n\treturn (\n\t\tactualBytes.length === expectedBytes.length &&\n\t\ttimingSafeEqual(actualBytes, expectedBytes)\n\t);\n};\n", "import { globalConfig } from \"./core.js\";\n// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function toZod() {\n return (schema) => schema;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\n// the accessor lives on a shared prototype: an own accessor makes every box a dictionary-mode object (~360 B and a slow load per read against ~100 B and an inlined getter here)\nclass Cached {\n constructor(getter) {\n this._getter = getter;\n this._value = undefined;\n }\n get value() {\n const getter = this._getter;\n if (getter !== undefined) {\n this._value = getter();\n this._getter = undefined;\n }\n return this._value;\n }\n}\nexport function cached(getter) {\n return new Cached(getter);\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const ratio = val / step;\n const roundedRatio = Math.round(ratio);\n // `val` and `step` each round to a double before the division rounds again, so a true decimal multiple's quotient can sit up to 1.5 of these scaled epsilons from the integer. A 1x tolerance therefore rejected 2.03 as a multiple of 0.07; 4x covers the worst case with margin.\n const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1);\n if (Math.abs(ratio - roundedRatio) < tolerance)\n return 0;\n return ratio - roundedRatio;\n}\nconst EVALUATING = /* @__PURE__*/ Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\n/**\n * Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it.\n *\n * Its keys and descriptors read without invoking anything, which is what lets a discriminated union check its discriminator, and the cycle walk read a shape, without resolving a getter that references the schema being constructed. A def that answers `shape` from an accessor of its own has none.\n */\nexport function rawShape(def) {\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n return desc?.get ? desc.get.raw : desc?.value;\n}\n// where a builder reads its source's keys and descriptors, resolving only a shape a def answers for itself. A shape resolves by object spread, so only its enumerable keys are ever part of it.\nfunction sourceShape(schema) {\n return rawShape(schema._zod.def) ?? schema._zod.def.shape;\n}\n// a key whose value is not settled yet, self-caching so every read after the first gets the same one\nfunction deferProp(target, key, getter) {\n Object.defineProperty(target, key, {\n get() {\n const value = getter();\n assignProp(this, key, value);\n return value;\n },\n enumerable: true,\n configurable: true,\n });\n}\n// Writes a settled key. A plain assignment is much cheaper than `defineProperty` and produces the same descriptor, but it runs whatever setter already answers to the key — an accessor this shape deferred, or an inherited one, which `__proto__` has on every object and prototype pollution can add for any name.\nfunction putProp(target, key, value) {\n if (key in target)\n assignProp(target, key, value);\n else\n target[key] = value;\n}\n/**\n * Copies `keys` of `source`'s shape onto `target`, each value passed through `wrap`.\n *\n * A key the source has resolved is copied through now, so the derived shape states it outright and nothing has to resolve it to learn what it holds. A key the source still defers stays deferred, and reads back through the source's own `shape`, so it resolves once and both shapes get that one schema.\n */\nfunction mirrorShape(target, source, keys, wrap) {\n const raw = sourceShape(source);\n for (const key of keys) {\n const desc = Object.getOwnPropertyDescriptor(raw, key);\n if (!desc.enumerable)\n continue;\n if (desc.get) {\n deferProp(target, key, () => {\n const value = source._zod.def.shape[key];\n return wrap ? wrap(value, key) : value;\n });\n }\n else\n putProp(target, key, wrap ? wrap(desc.value, key) : desc.value);\n }\n}\n// same, for a plain shape a caller passed rather than a schema's\nfunction mirrorProps(target, source) {\n for (const key of Reflect.ownKeys(source)) {\n const desc = Object.getOwnPropertyDescriptor(source, key);\n if (!desc.enumerable)\n continue;\n if (desc.get)\n deferProp(target, key, () => source[key]);\n else\n putProp(target, key, desc.value);\n }\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = /* @__PURE__*/ cached(() => {\n // Skip the probe under `jitless`: strict CSPs report the caught `new Function` as a `securitypolicyviolation` even though the throw is swallowed.\n if (globalConfig.jitless) {\n return false;\n }\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n if (o instanceof Map)\n return new Map(o);\n if (o instanceof Set)\n return new Set(o);\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = /* @__PURE__*/ new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = /* @__PURE__*/ new Set([\n \"string\",\n \"number\",\n \"bigint\",\n \"boolean\",\n \"symbol\",\n \"undefined\",\n]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === \"optional\";\n });\n}\n// Wrapped in a `@__PURE__` IIFE: esbuild never tree-shakes a top-level initializer that contains a member access on `Number`, so the bare object literal survived into every bundle.\nexport const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n}))();\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const newShape = {};\n mirrorShape(newShape, schema, maskedKeys(schema, mask));\n return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));\n}\n// the mask keys that select something, checked against the source's shape without resolving it\nfunction maskedKeys(schema, mask) {\n const raw = sourceShape(schema);\n const keys = [];\n // `for...in` skips symbols, so a symbol in the mask would select nothing\n for (const key of Reflect.ownKeys(mask)) {\n if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) {\n throw new Error(`Unrecognized key: \"${String(key)}\"`);\n }\n if (mask[key])\n keys.push(key);\n }\n return keys;\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const omitted = new Set(maskedKeys(schema, mask));\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key)));\n return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape. Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = sourceShape(schema);\n for (const key of Reflect.ownKeys(shape)) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));\n}\n// the source's keys, then the caller's overlaid on top\nfunction extended(schema, shape) {\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)));\n mirrorProps(newShape, shape);\n return newShape;\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));\n}\nexport function merge(a, b) {\n if (!b?._zod?.def) {\n throw new Error(\"Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.\");\n }\n if (a._zod.def.checks?.length) {\n throw new Error(\".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.\");\n }\n const newShape = {};\n mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a)));\n mirrorShape(newShape, b, Reflect.ownKeys(sourceShape(b)));\n const def = mergeDefs(a._zod.def, {\n shape: newShape,\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: b._zod.def.checks ?? [],\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask, name = \"partial\") {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(`.${name}() cannot be used on object schemas containing refinements`);\n }\n const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class &&\n ((value, key) => (selected && !selected.has(key) ? value : new Class({ type: \"optional\", innerType: value }))));\n return clone(schema, mergeDefs(schema._zod.def, { shape: newShape, checks: [] }));\n}\nexport function required(Class, schema, mask) {\n const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => \n // overwrite with non-optional\n selected && !selected.has(key) ? value : new Class({ type: \"nonoptional\", innerType: value }));\n return clone(schema, mergeDefs(schema._zod.def, { shape: newShape }));\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\n// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined). Used to respect `abort: true` in .refine() even for checks that have a `when` function.\nexport function explicitlyAborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue === false) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\n/* A check holds no link back to the schema it is attached to — the same check instance is shared by every clone of that schema — so the owner is stamped onto the issues a check just raised, at the only point where both are in scope. Runs on the failure path only; `start` is the issue count from before the check ran. */\n/** The leading size checks of `defChecks` that set an upper bound, each paired with it. */\nexport function sizeCaps(defChecks) {\n const caps = [];\n for (const ch of defChecks ?? []) {\n const d = ch._zod.def;\n // a later check may rewrite the value\n if (!/_(length|size)$|_equals$/.test(d.check))\n break;\n const max = d.maximum ?? d.length ?? d.size;\n if (max >= 0)\n caps.push([max, ch]);\n }\n return caps;\n}\nexport function attachSchema(issues, start, inst) {\n var _a;\n for (let i = start; i < issues.length; i++) {\n (_a = issues[i]).schema ?? (_a.schema = inst);\n }\n}\nexport function finalizeIssue(iss, ctx, config) {\n var _a;\n // A schema that raised an issue itself owns it outright, and outranks any stamp an enclosing check left in `attachSchema`. String formats and z.custom() are schema and check at once, so when they act as a check they defer to that stamp instead.\n const traits = iss.inst?._zod?.traits;\n if (traits?.has(\"$ZodType\")) {\n if (traits.has(\"$ZodCheck\"))\n (_a = iss).schema ?? (_a.schema = iss.inst);\n else\n iss.schema = iss.inst;\n }\n // Decreasing specificity, first map to return a message wins. `inst` is whatever raised the issue, so a check's own map outranks the owning schema's.\n const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined;\n const message = iss.message\n ? iss.message\n : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(schemaError?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\");\n // an explicit own-key copy beats object rest with excluded keys, which v8 routes through a generic runtime call; Object.keys rather than for-in so an issue pushed with a prototype does not leak inherited keys, and an own __proto__ key is dropped rather than assigned through the setter\n const full = {};\n for (const k of Object.keys(iss)) {\n if (k === \"inst\" || k === \"schema\" || k === \"continue\" || k === \"input\" || k === \"__proto__\")\n continue;\n full[k] = iss[k];\n }\n full.path ?? (full.path = []);\n full.message = message;\n if (ctx?.reportInput) {\n full.input = iss.input;\n }\n return full;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nconst highSurrogate = /[\\uD800-\\uDBFF]/;\n// Code points in `str`: a surrogate pair counts once, a lone surrogate as itself. Hand-rolled because the string iterator allocates and runs ~250x slower on this path; the regex probe exits ~50x quicker for a string with no astral characters.\nexport function codePointLength(str) {\n const units = str.length;\n if (!highSurrogate.test(str))\n return units;\n let count = units;\n for (let i = 0; i < units - 1; i++) {\n if ((str.charCodeAt(i) & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n count--;\n i++;\n }\n }\n return count;\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": {\n return Number.isNaN(data) ? \"nan\" : \"number\";\n }\n case \"object\": {\n if (data === null) {\n return \"null\";\n }\n if (Array.isArray(data)) {\n return \"array\";\n }\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n return obj.constructor.name;\n }\n }\n }\n return t;\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n////////// PROTOTYPE INSTALLERS //////////\n//\n// Members live on the prototype and materialize per instance on first read, which keeps own-property count under the step where V8 stops using inline slots. Changing anything here means re-measuring runtime, memory and bundle size together — see \"The three axes\" in AGENTS.md.\n/**\n * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working.\n *\n * Call this from a `proto` initializer, which runs once per prototype — never per instance.\n */\nexport function members(proto, table) {\n for (const key in table) {\n const desc = Object.getOwnPropertyDescriptor(table, key);\n // a getter installs as written, so it stays live: `description` reads through to the registry on every access. not enumerable: an object literal's is, and a prototype member never was\n if (desc.get)\n Object.defineProperty(proto, key, { ...desc, enumerable: false });\n // a method materializes bound on first read, which is what keeps a detached member working: `const opt = schema.optional; opt()`\n else\n defineBound(proto, key, desc.value);\n }\n}\n/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */\nexport function own(inst, key, value, enumerable = true) {\n Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value });\n return value;\n}\n/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */\nexport function hide(inst, key, value) {\n return own(inst, key, value, false);\n}\n/** Adds members a table derives from the instance: each builds on first read and shadows as own data, and assignment shadows the same way, as when these were own properties. */\nexport /*@__NO_SIDE_EFFECTS__*/ function derived(computes, table) {\n for (const key in computes) {\n const compute = computes[key];\n // an object literal's accessor is configurable and enumerable, and `members` copies the descriptor as written\n Object.defineProperty(table, key, {\n configurable: true,\n enumerable: true,\n get() {\n return own(this, key, compute(this));\n },\n set(value) {\n own(this, key, value);\n },\n });\n }\n return table;\n}\nfunction defineBound(proto, key, fn) {\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // vitest's spyOn calls a prototype getter bare to find the function it wraps, so a nullish receiver answers the raw method\n return this == null ? fn : own(this, key, fn.bind(this));\n },\n set(value) {\n own(this, key, value);\n },\n });\n}\n/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */\nfunction claim(inst, sentinel) {\n const proto = Object.getPrototypeOf(inst);\n // Runs on every construction, so `in` rather than the costlier `hasOwnProperty.call`. Sentinels are keys the group itself defines.\n return sentinel in proto ? undefined : proto;\n}\n// The internals whose init chain is installing. A second call for the same one is a derived constructor overriding its base, so it must not construct another schema in between or the override is dropped.\nlet installing;\n// Set while a getter is running, so a value that resolved through a recursion break is not memoized. One shared descriptor shadows the key for the duration, which costs no per-key allocation.\nlet broke = false;\nconst breaker = {\n configurable: true,\n get() {\n broke = true;\n return undefined;\n },\n};\n/**\n * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s\n * constructor, computed from the internals object itself and cached there on\n * first read. One accessor per constructor rather than one per instance.\n */\nexport function defineLazyInternal(inst, key, compute) {\n const proto = Object.getPrototypeOf(inst._zod);\n if (key in proto && installing !== inst._zod) {\n // A repeat construction: everything is installed already. Cleared here so the reference is not held past the first construction of every type.\n installing = undefined;\n return;\n }\n installing = inst._zod;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // Shadowed before computing so a re-entrant read from a recursive schema resolves to undefined instead of running the getter again.\n Object.defineProperty(this, key, breaker);\n const outer = broke;\n broke = false;\n try {\n const value = compute(this);\n // A result that resolved through a recursion break is recomputed once the graph is complete; everything else memoizes, undefined included.\n if (broke)\n delete this[key];\n else\n Object.defineProperty(this, key, { configurable: true, writable: true, value });\n broke = broke || outer;\n return value;\n }\n catch (err) {\n // A compute that threw memoizes nothing, so a later read runs it again and fails the same way. The shadow goes with it, since leaving it installed would answer undefined for every later read.\n delete this[key];\n broke = broke || outer;\n throw err;\n }\n },\n set(value) {\n Object.defineProperty(this, key, { configurable: true, writable: true, value });\n },\n });\n}\n/**\n * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own\n * data property. One accessor per constructor rather than one per instance, because an own accessor\n * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel.\n */\nexport function installLazyProp(inst, key, make, enumerable) {\n const proto = claim(inst, key);\n if (!proto)\n return;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // Shadowed before computing, so a re-entrant read from a self-referential shape resolves to undefined instead of running the getter again. A data property rather than an accessor: an own accessor is the dictionary-mode transition this exists to avoid.\n const desc = { configurable: true, writable: true, enumerable, value: undefined };\n Object.defineProperty(this, key, desc);\n // a compute that throws leaves the shadow behind, so later reads answer undefined instead of re-throwing; `defineLazy` did the same, and `defineLazyInternal`'s delete-on-catch would cost bytes in every bundle for a case only a throwing user getter reaches\n desc.value = make(this);\n Object.defineProperty(this, key, desc);\n return desc.value;\n },\n set(value) {\n Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value });\n },\n });\n}\n/** Marks the thunk `_catch` synthesises for a constant catch value. `Function.length` cannot tell that thunk from a user callback — rest and defaulted parameters both report arity 0 — and a user callback reads `ctx.error`, whose issues only finalize correctly against the caller's per-parse error map. Provenance can say what arity cannot. A plain string key rather than `Symbol.for`, whose call at module scope no bundler can prove pure — the same shape that anchored `urlCanParse` into every build. */\nexport const CONSTANT_CATCH = \"~constantCatch\";\n/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */\nexport function constantCatch(value) {\n const fn = () => value;\n fn[CONSTANT_CATCH] = true;\n return fn;\n}\n", "var _a;\nimport { members as installMembers } from \"./util.js\";\n/** A special constant with type `never` */\nexport const NEVER = /*@__PURE__*/ Object.freeze({\n status: \"aborted\",\n});\n/* Shared descriptor for installing `_zod`; defineProperty reads it\n * synchronously, so reusing one object avoids a per-instance allocation. */\nconst _zodDesc = { value: undefined, enumerable: false };\n// null where suppressing the capture would be unrecoverable: `parse()` puts the frames back with `captureStackTrace`, so without it the throw would lose its stack. also latched to null once `stackTraceLimit` proves unassignable, which a realm can do at any point by hardening Error\nlet _E = \"captureStackTrace\" in Error ? Error : null;\n// v8 captures a stack trace inside the Error constructor, which dominates a failed parse; costs only the frames, and parse() restores those. the constructor must RUN: Object.create is cheaper and passes instanceof, but Error.isError and util.types.isNativeError check an internal slot\nfunction newError(Definition) {\n const E = _E;\n if (E) {\n const saved = E.stackTraceLimit;\n if (typeof saved === \"number\") {\n try {\n E.stackTraceLimit = 0;\n }\n catch {\n _E = null;\n return new Definition();\n }\n try {\n return new Definition();\n }\n finally {\n E.stackTraceLimit = saved;\n }\n }\n }\n return new Definition();\n}\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, \n/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */\nproto, params) {\n // Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance.\n const zodProto = {};\n // Assigning the fields in the constructor body is what gives instances in-object slots; building the object literally and reparenting it costs a second allocation and a generic property copy.\n function Internals(def) {\n this.def = def;\n this.constr = _;\n this.traits = new Set();\n }\n Internals.prototype = zodProto;\n const protoMembers = proto;\n // One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait.\n const initialized = protoMembers && new WeakSet();\n function init(inst, def) {\n if (!inst._zod) {\n _zodDesc.value = new Internals(def);\n try {\n Object.defineProperty(inst, \"_zod\", _zodDesc);\n }\n finally {\n // Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next.\n _zodDesc.value = undefined;\n }\n }\n else if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n if (initialized) {\n // `super(def)` from a user subclass gives `this` a prototype the subclass owns, and installing there would overwrite whatever the subclass declared. `constr` built the instance, so its prototype is the one below the subclass's that should carry the members. A receiver whose chain never reaches that prototype installs on its own, which for a plain object handed straight to `init` means `Object.prototype` — unchanged from before.\n const own = Object.getPrototypeOf(inst);\n const ctorProto = inst._zod.constr.prototype;\n let up = own;\n while (up && up !== ctorProto)\n up = Object.getPrototypeOf(up);\n const target = up ?? own;\n if (!initialized.has(target)) {\n initialized.add(target);\n installMembers(target, protoMembers);\n }\n }\n // support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype\n const proto = _.prototype;\n for (const k in proto) {\n if (!Object.prototype.hasOwnProperty.call(proto, k))\n continue;\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n const inst = params?.Parent ? newError(Definition) : this;\n init(inst, def);\n const deferred = inst._zod.deferred;\n if (deferred) {\n for (const fn of deferred) {\n fn();\n }\n // Released: initializers run once, and the list would otherwise be retained for the schema's lifetime.\n inst._zod.deferred = undefined;\n }\n // Global post-processor hook. Internal: installed by `import \"zod/compile\"` to enable AOT compilation for every constructed schema. Runs last, once the instance is fully built, because it hands the instance to compile(). The post-processor is expected to be reentrancy-guarded by its own implementation.\n const pp = globalThis.__zod_globalConfig?.postProcessor;\n if (pp)\n pp(inst);\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = /*@__PURE__*/ Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\n(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});\nexport const globalConfig = globalThis.__zod_globalConfig;\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n", "import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\n/* Computing the message eagerly is expensive (pretty-printed JSON of all\n * issues), so defer it until first read. The accessor functions and\n * descriptors are shared across instances to keep error construction\n * cheap; the computed message is cached on the internals object. The\n * setter preserves plain assignment semantics for consumers that\n * overwrite `message`. */\nfunction _getMessage() {\n const internals = this._zod;\n internals.message ?? (internals.message = JSON.stringify(internals.def, util.jsonStringifyReplacer, 2));\n return internals.message;\n}\nfunction _setMessage(value) {\n this._zod.message = value;\n}\nconst _messageDesc = {\n get: _getMessage,\n set: _setMessage,\n enumerable: true,\n configurable: true,\n};\nconst _issuesDesc = { value: undefined, enumerable: false };\n/* Prototypes that already carry the lazy `toString`. Seeded with the\n * intrinsics so that `init` on a foreign object — it accepts any object —\n * can never install an accessor onto a prototype we do not own. */\nconst _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n // `_zod` is already non-enumerable: $constructor's init defined it with this same descriptor\n _issuesDesc.value = def;\n Object.defineProperty(inst, \"issues\", _issuesDesc);\n // Clear the shared slot; a retained `value` pins the last error's issues.\n _issuesDesc.value = undefined;\n Object.defineProperty(inst, \"message\", _messageDesc);\n /* `toString` lives as a non-enumerable lazy getter on the shared\n * prototype; on first access it caches a per-instance closure so\n * detached usage still works. */\n const proto = Object.getPrototypeOf(inst);\n if (!_installedToString.has(proto)) {\n _installedToString.add(proto);\n Object.defineProperty(proto, \"toString\", {\n configurable: true,\n enumerable: false,\n get() {\n const value = () => this.message;\n Object.defineProperty(this, \"toString\", { value, configurable: true, writable: true });\n return value;\n },\n set(value) {\n Object.defineProperty(this, \"toString\", { value, configurable: true, writable: true });\n },\n });\n }\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, undefined, {\n Parent: Error,\n});\n/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member\n * (\"toString\", \"constructor\") would otherwise read through to the prototype, and assigning\n * \"__proto__\" would hit the setter instead of creating a key. */\nfunction node(obj, key, make) {\n if (!Object.prototype.hasOwnProperty.call(obj, key)) {\n if (key === \"__proto__\") {\n Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true });\n }\n else {\n obj[key] = make();\n }\n }\n return obj[key];\n}\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n node(fieldErrors, sub.path[0], () => []).push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n const fieldErrors = { _errors: [] };\n const processError = (error, path = []) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n // `_errors` is reserved by this legacy format, so merge a matching path segment into the current node instead of treating its array as a child.\n if (el === \"_errors\") {\n if (terminal)\n curr._errors.push(mapper(issue));\n i++;\n continue;\n }\n // A path element may collide with an inherited property name such as\n // \"__proto__\" or \"constructor\". Truthiness checks read the prototype\n // (so no node is created, then ._errors.push throws), and bracket\n // assignment of \"__proto__\" hits the setter instead of creating an\n // own key. Guard the read with hasOwnProperty and create the node\n // with defineProperty so any path element becomes a real own key.\n if (!Object.prototype.hasOwnProperty.call(curr, el)) {\n Object.defineProperty(curr, el, {\n value: { _errors: [] },\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n const node = curr[el];\n if (terminal) {\n node._errors.push(mapper(issue));\n }\n curr = node;\n i++;\n }\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n // el may collide with an inherited property name (\"__proto__\",\n // \"constructor\", ...); ??= reads the prototype so the node is never\n // created and curr.errors.push throws. Guard with hasOwnProperty and\n // create the node with defineProperty so \"__proto__\" becomes a real\n // own key rather than invoking the prototype setter.\n if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) {\n Object.defineProperty(curr.properties, el, {\n value: { errors: [] },\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_a = curr.items)[el] ?? (_a[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n * ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n const segs = [];\n const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`✖ ${issue.message}`);\n if (issue.path?.length)\n lines.push(` → at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n", "import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\n// Always both keys, so the `_params` read site in `_parse` sees one object shape rather than two.\nfunction finalizeParams(callee, params) {\n return { callee: params?.callee ?? callee, Err: params?.Err };\n}\nexport const _parse = (_Err) => {\n const fn = (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n if (result.issues.length) {\n const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, _params?.callee ?? fn);\n throw e;\n }\n return result.value;\n };\n return fn;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => {\n const fn = async (schema, value, _ctx, params) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n if (result.issues.length) {\n const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, params?.callee ?? fn);\n throw e;\n }\n return result.value;\n };\n return fn;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\n// the error is built on the first read of `error`: finalizing the issues and constructing the instance is most of a failing parse, and a caller that only branches on `success` never pays it. a getter in the literal keeps this small; the alternative, one shared accessor descriptor plus a hidden state slot, reads ~15% faster but costs ~75 B gzipped in every bundle\nfunction failure(Err, issues, ctx) {\n let error;\n return {\n success: false,\n get error() {\n if (!error) {\n error = new Err(issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n // finalizeIssue drops `input`, so the built error holds nothing; keeping the raw issues past this point pins the parsed value for the life of the result\n issues = undefined;\n ctx = undefined;\n }\n return error;\n },\n set error(e) {\n error = e;\n // a replacement makes the getter's branch unreachable, so the captures have to go here too\n issues = undefined;\n ctx = undefined;\n },\n };\n}\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\n// registry mirrors of the compiler's sentinels, so this module never imports the compiler\nconst COMPILE_INVALID = /* @__PURE__ */ Symbol.for(\"zod.compile.invalid\");\nconst COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for(\"zod.compile.fallback\");\n// Deliberately tiny, because v8 will not inline a body carrying the fallback's object literals and throw. Everything that is not the compiled happy path lives in validateFallback, and that split is worth ~35% on a compiled schema.\nexport const validate = ((schema, value, _ctx) => {\n const validator = schema._zod.bag.validator;\n if (validator !== undefined) {\n if (validator(value) !== COMPILE_INVALID)\n return true;\n // a definite sentinel means the runtime would reject, so skip the re-parse; a ctx can still change the answer\n if (validator.definite === true && _ctx === undefined)\n return false;\n }\n return validateFallback(schema, value, _ctx);\n});\nfunction validateFallback(schema, value, _ctx) {\n const ctx = _ctx\n ? { ..._ctx, async: false, abortEarly: true }\n : { async: false, abortEarly: true };\n const fallbackRun = schema._zod.bag.fallbackRun;\n let result;\n if (fallbackRun) {\n // skip nested fast paths on the fallback, so user callbacks keep the at-most-twice bound\n ctx[COMPILE_FALLBACK] = true;\n result = fallbackRun({ value, issues: [] }, ctx);\n }\n else {\n result = schema._zod.run({ value, issues: [] }, ctx);\n }\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length === 0;\n}\n// no fast path: the compiler keeps async parses on the runtime, because a promise-returning callback that is not declared async compiles to a throw\nexport const validateAsync = async (schema, value, _ctx) => {\n const ctx = _ctx\n ? { ..._ctx, async: true, abortEarly: true }\n : { async: true, abortEarly: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length === 0;\n};\nexport const _encode = (_Err) => {\n const parse = _parse(_Err);\n const fn = (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return parse(schema, value, ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => {\n const parse = _parse(_Err);\n const fn = (schema, value, _ctx, _params) => {\n return parse(schema, value, _ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => {\n const parseAsync = _parseAsync(_Err);\n const fn = async (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return (await parseAsync(schema, value, ctx, finalizeParams(fn, _params)));\n };\n return fn;\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => {\n const parseAsync = _parseAsync(_Err);\n const fn = async (schema, value, _ctx, _params) => {\n return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);\nexport const _safeEncode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParse(_Err)(schema, value, ctx);\n};\nexport const safeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);\nexport const _safeDecode = (_Err) => (schema, value, _ctx) => {\n return _safeParse(_Err)(schema, value, _ctx);\n};\nexport const safeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);\nexport const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParseAsync(_Err)(schema, value, ctx);\n};\nexport const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);\nexport const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _safeParseAsync(_Err)(schema, value, _ctx);\n};\nexport const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(errors.$ZodRealError);\n", "import * as util from \"./util.js\";\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const cuid = /^[cC][0-9a-z]{6,}$/;\nexport const cuid2 = /^[0-9a-z]+$/;\nexport const ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\nexport function nanoidOfLength(length) {\n return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`);\n}\n/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */\nexport const duration = /^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/;\n/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */\nexport const extendedDuration = /^[-+]?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)?)??$/;\n/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */\nexport const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;\n/** Returns a regex for validating an RFC 9562/4122 UUID.\n *\n * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */\nexport const uuid = (version) => {\n if (!version)\n return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;\n return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);\n};\nexport const uuid4 = /*@__PURE__*/ uuid(4);\nexport const uuid6 = /*@__PURE__*/ uuid(6);\nexport const uuid7 = /*@__PURE__*/ uuid(7);\n/** Practical email validation */\nexport const email = /^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/;\n/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */\nexport const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n/** The classic emailregex.com regex for RFC 5322-compliant emails */\nexport const rfc5322Email = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */\nexport const unicodeEmail = /^[^\\s@\"]{1,64}@[^\\s@]{1,255}$/u;\nexport const idnEmail = unicodeEmail;\nexport const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\n// Single character class, not an alternation: the two properties overlap (U+1F9B0-U+1F9B3), so `(A|B)+` backtracks exponentially on a failed match. The leading lookahead then demands one anchor — a pictograph, a regional indicator, or the enclosing keycap — because `\\p{Emoji_Component}` on its own covers ASCII digits, `#`, `*`, ZWJ, variation selectors and skin tone modifiers, none of which is an emoji without a base.\nconst _emoji = `^(?=[\\\\s\\\\S]*[\\\\p{Extended_Pictographic}\\\\p{Regional_Indicator}\\\\u20E3])[\\\\p{Extended_Pictographic}\\\\p{Emoji_Component}]+$`;\nexport function emoji() {\n return new RegExp(_emoji, \"u\");\n}\nexport const ipv4 = /^(?:(?: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])$/;\nexport const ipv6 = /^(([0-9a-fA-F]{1,4}:){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}|:))$/;\nexport const mac = (delimiter) => {\n const escapedDelim = util.escapeRegex(delimiter ?? \":\");\n return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);\n};\nexport const cidrv4 = /^((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])\\/([0-9]|[1-2][0-9]|3[0-2])$/;\nexport const cidrv6 = /^(([0-9a-fA-F]{1,4}:){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}|:))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nexport const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;\nexport const base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;\n// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address\n// export const hostname: RegExp = /^([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+$/;\nexport const hostname = /^(?=.{1,253}\\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\\.?$/;\nexport const domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,63}$/;\nexport const httpProtocol = /^https?$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// Credit card shape: 12–19 digits, optionally separated by single spaces or single hyphens. ISO/IEC 7812 caps the PAN at 19 digits; 12 is the shortest issued length (Maestro).\nexport const creditCard = /^\\d(?:[ -]?\\d){11,18}$/;\n// ISO 4217 alpha codes from the SIX list, regenerated by scripts/update-iso-4217.ts\nexport const currencyCode = /^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/;\n// iban electronic format: 2-letter country, check digits 02-98 (the only values `98 - remainder` can produce), 11-30 bban characters\nexport const iban = /^[A-Z]{2}(?!00|01|99)\\d{2}[A-Z0-9]{11,30}$/;\nconst 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])))`;\n/** Anchors a pattern source. The interpolation lives here rather than at the call site because\n * esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it\n * will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */\nfunction anchor(source) {\n return new RegExp(`^${source}$`);\n}\nexport const date = /*@__PURE__*/ anchor(dateSource);\nfunction timeSource(args) {\n const hhmm = `(?:[01]\\\\d|2[0-3]):[0-5]\\\\d`;\n const regex = typeof args.precision === \"number\"\n ? args.precision === -1\n ? `${hhmm}`\n : args.precision === 0\n ? `${hhmm}:[0-5]\\\\d`\n : `${hhmm}:[0-5]\\\\d\\\\.\\\\d{${args.precision}}`\n : args.seconds\n ? `${hhmm}:[0-5]\\\\d(?:\\\\.\\\\d+)?`\n : `${hhmm}(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?`;\n return regex;\n}\nexport function time(args) {\n return new RegExp(`^${timeSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetime(args) {\n const opts = [\"Z\"];\n // if (args.offset) opts.push(`([+-]\\\\d{2}:\\\\d{2})`);\n if (args.offset)\n opts.push(`([+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)`);\n // RFC 3339 mandates seconds wherever the time carries a `Z` or an offset, so only the unqualified form `local` adds may omit them\n const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join(\"|\")})`;\n const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified;\n return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\n// the unbounded form of `string()` as a literal, so every plain string shares one instance instead of building its own\nexport const anyString = /^[\\s\\S]{0,}$/;\nexport const string = (params) => {\n const regex = params ? `[\\\\s\\\\S]{${params?.minimum ?? 0},${params?.maximum ?? \"\"}}` : `[\\\\s\\\\S]*`;\n return new RegExp(`^${regex}$`);\n};\nexport const bigint = /^-?\\d+n?$/;\nexport const integer = /^-?\\d+$/;\nexport const number = /^-?\\d+(?:\\.\\d+)?$/;\nexport const boolean = /^(?:true|false)$/i;\nconst _null = /^null$/i;\nexport { _null as null };\nconst _undefined = /^undefined$/i;\nexport { _undefined as undefined };\n// regex for string with no uppercase letters\nexport const lowercase = /^[^A-Z]*$/;\n// regex for string with no lowercase letters\nexport const uppercase = /^[^a-z]*$/;\n// regex for hexadecimal strings (any length)\nexport const hex = /^[0-9a-fA-F]*$/;\n// Hash regexes for different algorithms and encodings\n// Helper function to create base64 regex with exact length and padding\nfunction fixedBase64(bodyLength, padding) {\n return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);\n}\n// Helper function to create base64url regex with exact length (no padding)\nfunction fixedBase64url(length) {\n return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);\n}\n// MD5 (16 bytes): base64 = 24 chars total (22 + \"==\")\nexport const md5_hex = /^[0-9a-fA-F]{32}$/;\nexport const md5_base64 = /*@__PURE__*/ fixedBase64(22, \"==\");\nexport const md5_base64url = /*@__PURE__*/ fixedBase64url(22);\n// SHA1 (20 bytes): base64 = 28 chars total (27 + \"=\")\nexport const sha1_hex = /^[0-9a-fA-F]{40}$/;\nexport const sha1_base64 = /*@__PURE__*/ fixedBase64(27, \"=\");\nexport const sha1_base64url = /*@__PURE__*/ fixedBase64url(27);\n// SHA256 (32 bytes): base64 = 44 chars total (43 + \"=\")\nexport const sha256_hex = /^[0-9a-fA-F]{64}$/;\nexport const sha256_base64 = /*@__PURE__*/ fixedBase64(43, \"=\");\nexport const sha256_base64url = /*@__PURE__*/ fixedBase64url(43);\n// SHA384 (48 bytes): base64 = 64 chars total (no padding)\nexport const sha384_hex = /^[0-9a-fA-F]{96}$/;\nexport const sha384_base64 = /*@__PURE__*/ fixedBase64(64, \"\");\nexport const sha384_base64url = /*@__PURE__*/ fixedBase64url(64);\n// SHA512 (64 bytes): base64 = 88 chars total (86 + \"==\")\nexport const sha512_hex = /^[0-9a-fA-F]{128}$/;\nexport const sha512_base64 = /*@__PURE__*/ fixedBase64(86, \"==\");\nexport const sha512_base64url = /*@__PURE__*/ fixedBase64url(86);\n", "// import { $ZodType } from \"./schemas.js\";\nimport * as core from \"./core.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nexport const $ZodCheck = /*@__PURE__*/ core.$constructor(\"$ZodCheck\", (inst, def) => {\n var _a;\n inst._zod ?? (inst._zod = {});\n inst._zod.def = def;\n (_a = inst._zod).onattach ?? (_a.onattach = []);\n});\n/** Default `when` for size-based checks: run only on non-nullish values with a `size`. */\nconst _whenHasSize = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n};\n/** Default `when` for length-based checks: run only on non-nullish values with a `length`. */\nconst _whenHasLength = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n};\nconst numericOriginMap = {\n number: \"number\",\n bigint: \"bigint\",\n object: \"date\",\n};\nexport const $ZodCheckLessThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckLessThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {\n return;\n }\n payload.issues.push({\n origin: numericOriginMap[typeof payload.value] ?? origin,\n code: \"too_big\",\n maximum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckGreaterThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckGreaterThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {\n return;\n }\n payload.issues.push({\n origin: numericOriginMap[typeof payload.value] ?? origin,\n code: \"too_small\",\n minimum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMultipleOf = \n/*@__PURE__*/ core.$constructor(\"$ZodCheckMultipleOf\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n if (typeof payload.value !== typeof def.value)\n throw new Error(\"Cannot mix number and bigint in multiple_of check.\");\n const isMultiple = typeof payload.value === \"bigint\"\n ? // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN\n def.value !== BigInt(0) && payload.value % def.value === BigInt(0)\n : util.floatSafeRemainder(payload.value, def.value) === 0;\n if (isMultiple)\n return;\n payload.issues.push({\n origin: typeof payload.value,\n code: \"not_multiple_of\",\n divisor: def.value,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckNumberFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n def.format = def.format || \"float64\";\n const isInt = def.format?.includes(\"int\");\n const origin = isInt ? \"int\" : \"number\";\n const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (isInt) {\n if (!Number.isInteger(input)) {\n // invalid_format issue\n // payload.issues.push({\n // expected: def.format,\n // format: def.format,\n // code: \"invalid_format\",\n // input,\n // inst,\n // });\n // invalid_type issue\n payload.issues.push({\n expected: origin,\n format: def.format,\n code: \"invalid_type\",\n continue: false,\n input,\n inst,\n });\n return;\n // not_multiple_of issue\n // payload.issues.push({\n // code: \"not_multiple_of\",\n // origin: \"number\",\n // input,\n // inst,\n // divisor: 1,\n // });\n }\n if (!Number.isSafeInteger(input)) {\n if (input > 0) {\n // too_big\n payload.issues.push({\n input,\n code: \"too_big\",\n maximum: Number.MAX_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n else {\n // too_small\n payload.issues.push({\n input,\n code: \"too_small\",\n minimum: Number.MIN_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n return;\n }\n }\n if (input < minimum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_small\",\n minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckBigIntFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (input < minimum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_small\",\n minimum: minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckMaxSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size <= def.maximum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size >= def.minimum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckSizeEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckSizeEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size === def.size)\n return;\n const tooBig = size > def.size;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n ...(tooBig ? { code: \"too_big\", maximum: def.size } : { code: \"too_small\", minimum: def.size }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMaxLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // Strings are measured in Unicode code points, not UTF-16 units. A code point is at most two units, so a string that already fits in units fits in code points; only an overflow has to be counted.\n const length = typeof input === \"string\" && units > def.maximum ? util.codePointLength(input) : units;\n if (length <= def.maximum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // A code point is one or two UTF-16 units, so fewer units than the floor can never reach it and twice the floor always clears it. Only in between is the exact count in doubt.\n const length = typeof input === \"string\" && units >= def.minimum && units < def.minimum * 2\n ? util.codePointLength(input)\n : units;\n if (length >= def.minimum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLengthEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckLengthEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // A code point is one or two UTF-16 units, so outside `[length, length * 2]` units the target is missed either way — and missed in the same direction in both measures.\n const length = typeof input === \"string\" && units >= def.length && units <= def.length * 2\n ? util.codePointLength(input)\n : units;\n if (length === def.length)\n return;\n const origin = util.getLengthableOrigin(input);\n const tooBig = length > def.length;\n payload.issues.push({\n origin,\n ...(tooBig ? { code: \"too_big\", maximum: def.length } : { code: \"too_small\", minimum: def.length }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckStringFormat\", (inst, def) => {\n var _a, _b;\n $ZodCheck.init(inst, def);\n if (def.pattern)\n (_a = inst._zod).check ?? (_a.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n ...(def.pattern ? { pattern: def.pattern.toString() } : {}),\n inst,\n continue: !def.abort,\n });\n });\n else\n (_b = inst._zod).check ?? (_b.check = () => { });\n});\nexport const $ZodCheckRegex = /*@__PURE__*/ core.$constructor(\"$ZodCheckRegex\", (inst, def) => {\n $ZodCheckStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"regex\",\n input: payload.value,\n pattern: def.pattern.toString(),\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLowerCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckLowerCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.lowercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckUpperCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckUpperCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.uppercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckIncludes = /*@__PURE__*/ core.$constructor(\"$ZodCheckIncludes\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const escapedRegex = util.escapeRegex(def.includes);\n // `String.prototype.includes(sub, position)` matches `sub` at `position`\n // OR LATER, so the pattern must allow at least `position` leading chars\n // (`{N,}`), not exactly `position` chars (`{N}`).\n const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position},}${escapedRegex}` : escapedRegex);\n def.pattern = pattern;\n inst._zod.check = (payload) => {\n if (payload.value.includes(def.includes, def.position))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"includes\",\n includes: def.includes,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStartsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckStartsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.check = (payload) => {\n if (payload.value.startsWith(def.prefix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"starts_with\",\n prefix: def.prefix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckEndsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckEndsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.check = (payload) => {\n if (payload.value.endsWith(def.suffix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"ends_with\",\n suffix: def.suffix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n///////////////////////////////////\n///// $ZodCheckProperty /////\n///////////////////////////////////\nfunction handleCheckPropertyResult(result, payload, property) {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(property, result.issues));\n }\n}\nexport const $ZodCheckProperty = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperty\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n const result = def.schema._zod.run({\n value: payload.value[def.property],\n issues: [],\n }, {});\n if (result instanceof Promise) {\n return result.then((result) => handleCheckPropertyResult(result, payload, def.property));\n }\n handleCheckPropertyResult(result, payload, def.property);\n return;\n };\n});\nexport const $ZodCheckProperties = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperties\", (inst, def) => {\n $ZodCheck.init(inst, def);\n util.hide(inst, Symbol.iterator, function* () {\n yield inst;\n });\n // key and schema snapshotted together: reading one live and the other cached lets a later mutation of the caller's shape object pair a stale key with a missing schema\n let entries;\n inst._zod.check = (payload) => {\n // the base schema already typed the value, so only a nullish one is rejected here: the properties read on a primitive too, matching z.property() on a string's length\n if (payload.value == null) {\n payload.issues.push({ expected: \"object\", code: \"invalid_type\", input: payload.value, inst });\n return undefined;\n }\n entries ?? (entries = Reflect.ownKeys(def.shape).map((key) => [key, def.shape[key]]));\n const input = payload.value;\n let proms;\n for (const [key, schema] of entries) {\n const result = schema._zod.run({ value: input[key], issues: [] }, {});\n if (result instanceof Promise) {\n proms ?? (proms = []);\n proms.push(result.then((result) => handleCheckPropertyResult(result, payload, key)));\n }\n else {\n handleCheckPropertyResult(result, payload, key);\n }\n }\n if (proms)\n return Promise.all(proms).then(() => undefined);\n return undefined;\n };\n});\nexport const $ZodCheckMimeType = /*@__PURE__*/ core.$constructor(\"$ZodCheckMimeType\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const mimeSet = new Set(def.mime);\n inst._zod.check = (payload) => {\n if (mimeSet.has(payload.value.type))\n return;\n payload.issues.push({\n code: \"invalid_value\",\n values: def.mime,\n input: payload.value.type,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckOverwrite = /*@__PURE__*/ core.$constructor(\"$ZodCheckOverwrite\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n payload.value = def.tx(payload.value);\n };\n});\n", "export class Doc {\n constructor(args = [], closed = {}) {\n this.content = [];\n this.indent = 0;\n this.args = args;\n this.closed = closed;\n }\n // the compiler catches a child's throw and keeps writing into this doc, so the indent has to unwind with it\n indented(fn) {\n this.indent += 1;\n try {\n fn(this);\n }\n finally {\n this.indent -= 1;\n }\n }\n write(arg) {\n if (typeof arg === \"function\") {\n arg(this, { execution: \"sync\" });\n arg(this, { execution: \"async\" });\n return;\n }\n const content = arg;\n const lines = content.split(\"\\n\").filter((x) => x);\n const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));\n const dedented = lines.map((x) => x.slice(minIndent)).map((x) => \" \".repeat(this.indent * 2) + x);\n for (const line of dedented) {\n this.content.push(line);\n }\n }\n compile() {\n const F = Function;\n const content = this?.content ?? [``];\n const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(\", \")}) {\\n${content.join(\"\\n\")}\\n};`);\n return factory(...Object.values(this.closed));\n }\n}\n", "export const version = {\n major: 4,\n minor: 6,\n patch: 7,\n};\n", "import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync } from \"./parse.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nimport { version } from \"./versions.js\";\nexport const $ZodType = /*@__PURE__*/ core.$constructor(\"$ZodType\", (inst, def) => {\n var _a;\n inst ?? (inst = {});\n inst._zod.def = def; // set _def property\n inst._zod.bag = inst._zod.bag || {}; // initialize _bag object\n inst._zod.version = version;\n const defChecks = inst._zod.def.checks;\n // if inst is itself a checks.$ZodCheck, run it as a check\n const checks = inst._zod.traits.has(\"$ZodCheck\")\n ? [inst, ...(defChecks ?? [])]\n : defChecks?.length\n ? [...defChecks]\n : [];\n for (const ch of checks) {\n for (const fn of ch._zod.onattach) {\n fn(inst);\n }\n }\n if (checks.length === 0) {\n // deferred initializer inst._zod.parse is not yet defined\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred?.push(() => {\n inst._zod.run = inst._zod.parse;\n });\n }\n else {\n const runChecks = (payload, checks, ctx) => {\n if (payload.memo)\n return payload;\n let isAborted = util.aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\n if (util.explicitlyAborted(payload))\n continue;\n const shouldRun = ch._zod.def.when(payload);\n if (!shouldRun)\n continue;\n }\n else if (isAborted) {\n continue;\n }\n const currLen = payload.issues.length;\n const _ = ch._zod.check(payload);\n if (_ instanceof Promise && ctx?.async === false) {\n throw new core.$ZodAsyncError();\n }\n if (asyncResult || _ instanceof Promise) {\n asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n await _;\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n return;\n util.attachSchema(payload.issues, currLen, inst);\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n });\n }\n else {\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n continue;\n util.attachSchema(payload.issues, currLen, inst);\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n }\n }\n if (asyncResult) {\n return asyncResult.then(() => {\n return payload;\n });\n }\n return payload;\n };\n const handleCanaryResult = (canary, payload, ctx) => {\n // abort if the canary is aborted\n if (util.aborted(canary)) {\n canary.aborted = true;\n return canary;\n }\n // run checks first, then\n const checkResult = runChecks(payload, checks, ctx);\n if (checkResult instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n }\n return inst._zod.parse(checkResult, ctx);\n };\n inst._zod.run = (payload, ctx) => {\n if (ctx.skipChecks) {\n return inst._zod.parse(payload, ctx);\n }\n if (ctx.direction === \"backward\") {\n // run canary initial pass (no checks)\n const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });\n if (canary instanceof Promise) {\n return canary.then((canary) => {\n return handleCanaryResult(canary, payload, ctx);\n });\n }\n return handleCanaryResult(canary, payload, ctx);\n }\n // forward\n const result = inst._zod.parse(payload, ctx);\n if (result instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return result.then((result) => runChecks(result, checks, ctx));\n }\n return runChecks(result, checks, ctx);\n };\n }\n}, {\n // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness.\n get \"~standard\"() {\n return util.hide(this, \"~standard\", standardProps(this));\n },\n set \"~standard\"(value) {\n util.own(this, \"~standard\", value);\n },\n});\n/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */\n// a Standard Schema result only reports issues, so a failure finalizes them straight off the raw payload: no ZodError, and no lazy result to read through\nconst toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())) } : { value: r.value };\nasync function validateAsync(inst, value) {\n const ctx = { async: true };\n return toStandardResult((await inst._zod.run({ value, issues: [] }, ctx)), ctx);\n}\nexport function standardProps(inst) {\n return {\n validate: (value) => {\n const ctx = { async: false };\n try {\n const r = inst._zod.run({ value, issues: [] }, ctx);\n if (!(r instanceof Promise))\n return toStandardResult(r, ctx);\n }\n catch (_) { }\n // async function so a synchronously throwing check rejects instead of escaping validate\n return validateAsync(inst, value);\n },\n vendor: \"zod\",\n version: 1,\n };\n}\nexport { clone } from \"./util.js\";\nexport const $ZodString = /*@__PURE__*/ core.$constructor(\"$ZodString\", (inst, def) => {\n $ZodType.init(inst, def);\n // a format's own pattern, else unbounded; a template literal derives the check-aware form itself\n inst._zod.pattern = def.pattern ?? regexes.anyString;\n inst._zod.parse = (payload, _) => {\n if (def.coerce)\n try {\n payload.value = String(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"string\")\n return payload;\n payload.issues.push({\n expected: \"string\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodStringFormat\", (inst, def) => {\n // check initialization must come first\n checks.$ZodCheckStringFormat.init(inst, def);\n $ZodString.init(inst, def);\n});\nexport const $ZodGUID = /*@__PURE__*/ core.$constructor(\"$ZodGUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.guid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodUUID = /*@__PURE__*/ core.$constructor(\"$ZodUUID\", (inst, def) => {\n if (def.version) {\n const versionMap = {\n v1: 1,\n v2: 2,\n v3: 3,\n v4: 4,\n v5: 5,\n v6: 6,\n v7: 7,\n v8: 8,\n };\n const v = versionMap[def.version];\n if (v === undefined)\n throw new Error(`Invalid UUID version: \"${def.version}\"`);\n def.pattern ?? (def.pattern = regexes.uuid(v));\n }\n else\n def.pattern ?? (def.pattern = regexes.uuid());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodEmail = /*@__PURE__*/ core.$constructor(\"$ZodEmail\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.email);\n $ZodStringFormat.init(inst, def);\n});\n/** The `://` guard rejected the input before the URL constructor saw it. */\nexport const URL_BAD_FORMAT = 1;\n/** The URL parser rejected the input. */\nexport const URL_UNPARSEABLE = 2;\nexport function canParseURL(input) {\n try {\n if (typeof URL !== \"undefined\" && typeof URL.canParse === \"function\")\n return URL.canParse(input);\n new URL(input);\n return true;\n }\n catch {\n return false;\n }\n}\nexport function validateURL(trimmed, def) {\n if (!(\"normalize\" in def) && !(\"hostname\" in def) && !(\"protocol\" in def)) {\n return canParseURL(trimmed) || URL_UNPARSEABLE;\n }\n return parseURLObject(trimmed, def);\n}\n/** Parses a URL while preserving the non-normalizing HTTP guard. */\nexport function parseURLObject(trimmed, def) {\n // When normalize is off, require :// for http/https URLs. This prevents strings like \"http:example.com\" or \"https:/path\" from being silently accepted\n if (!def.normalize && def.protocol?.source === regexes.httpProtocol.source && !/^https?:\\/\\//i.test(trimmed)) {\n return URL_BAD_FORMAT;\n }\n try {\n if (typeof URL !== \"undefined\") {\n const URLStatic = URL;\n if (typeof URLStatic.parse === \"function\")\n return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE;\n }\n // @ts-ignore\n return new URL(trimmed);\n }\n catch {\n return URL_UNPARSEABLE;\n }\n}\nconst asciiTabOrNewline = /[\\t\\n\\r]/g;\n/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL(\"https://exa\\nmple.com\")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */\nexport function stripTabAndNewline(value) {\n return value.replace(asciiTabOrNewline, \"\");\n}\nexport function urlHostnameOk(url, hostname) {\n hostname.lastIndex = 0;\n return hostname.test(url.hostname);\n}\nexport function urlProtocolOk(url, protocol) {\n protocol.lastIndex = 0;\n return protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol);\n}\nexport const $ZodURL = /*@__PURE__*/ core.$constructor(\"$ZodURL\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n try {\n // Trim whitespace from input\n const trimmed = payload.value.trim();\n const url = validateURL(trimmed, def);\n if (url === URL_BAD_FORMAT) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid URL format\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n if (url === URL_UNPARSEABLE) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n if (url === true) {\n payload.value = stripTabAndNewline(trimmed);\n return;\n }\n if (def.hostname && !urlHostnameOk(url, def.hostname)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid hostname\",\n pattern: def.hostname.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n if (def.protocol && !urlProtocolOk(url, def.protocol)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid protocol\",\n pattern: def.protocol.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n // Set the output value based on normalize flag\n payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed);\n return;\n }\n catch (_) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodEmoji = /*@__PURE__*/ core.$constructor(\"$ZodEmoji\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.emoji());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodNanoID = /*@__PURE__*/ core.$constructor(\"$ZodNanoID\", (inst, def) => {\n if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1))\n throw new Error(`Invalid nanoid length: ${def.length}`);\n def.pattern ?? (def.pattern = def.length === undefined ? regexes.nanoid : regexes.nanoidOfLength(def.length));\n $ZodStringFormat.init(inst, def);\n});\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link $ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const $ZodCUID = /*@__PURE__*/ core.$constructor(\"$ZodCUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID2 = /*@__PURE__*/ core.$constructor(\"$ZodCUID2\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid2);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodULID = /*@__PURE__*/ core.$constructor(\"$ZodULID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ulid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodXID = /*@__PURE__*/ core.$constructor(\"$ZodXID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.xid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodKSUID = /*@__PURE__*/ core.$constructor(\"$ZodKSUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ksuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.datetime(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.date);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.time(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.duration);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodIPv4 = /*@__PURE__*/ core.$constructor(\"$ZodIPv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv4);\n $ZodStringFormat.init(inst, def);\n});\n/** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL(\"http://[...]\")` parses an authority, not an address, so `@` and `\\` re-delimit it and `\"::@1\\\\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `\"::1\\n\"` validated as `::1`. */\nconst ipv6Alphabet = /^[0-9a-fA-F:.]+$/;\nexport function isValidIPv6(value) {\n if (!ipv6Alphabet.test(value))\n return false;\n return canParseURL(`http://[${value}]`);\n}\nexport const $ZodIPv6 = /*@__PURE__*/ core.$constructor(\"$ZodIPv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv6);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (!isValidIPv6(payload.value)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"ipv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodMAC = /*@__PURE__*/ core.$constructor(\"$ZodMAC\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.mac(def.delimiter));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\n});\nexport function isValidCIDRv6(value) {\n const parts = value.split(\"/\");\n if (parts.length !== 2)\n return false;\n const [address, prefix] = parts;\n if (!prefix)\n return false;\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n return false;\n if (prefixNum < 0 || prefixNum > 128)\n return false;\n return isValidIPv6(address);\n}\nexport const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (!isValidCIDRv6(payload.value)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"cidrv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64(data) {\n if (data === \"\")\n return true;\n // atob ignores whitespace, so reject it up front.\n if (/\\s/.test(data))\n return false;\n if (data.length % 4 !== 0)\n return false;\n try {\n // @ts-ignore\n atob(data);\n return true;\n }\n catch {\n return false;\n }\n}\n// lax on purpose: the quantified regexes.base64 overflows the regex stack on multi-MB input and its leading ^$| alternation leaks through template-literal composition; isValidBase64 enforces length and padding\nexport const base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/;\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = base64Charset);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidBase64(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodBase64URL //////////////////////////////\n// lax on purpose: the quantified regexes.base64url overflows the regex stack on multi-MB input; isValidBase64 enforces length on the padded string\nexport const base64urlCharset = /^[A-Za-z0-9_-]*$/;\nexport function isValidBase64URL(data) {\n if (!base64urlCharset.test(data))\n return false;\n const base64 = data.replace(/[-_]/g, (c) => (c === \"-\" ? \"+\" : \"/\"));\n const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n return isValidBase64(padded);\n}\nexport const $ZodBase64URL = /*@__PURE__*/ core.$constructor(\"$ZodBase64URL\", (inst, def) => {\n def.pattern ?? (def.pattern = base64urlCharset);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidBase64URL(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodE164 = /*@__PURE__*/ core.$constructor(\"$ZodE164\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.e164);\n $ZodStringFormat.init(inst, def);\n});\n////////////////////////////// ZodCreditCard //////////////////////////////\nconst CC_SANITIZE = /[- ]/g;\n/** Luhn checksum on a digit-only string. Adapted from valibot (MIT). */\nfunction isLuhnAlgo(digits) {\n let length = digits.length;\n let bit = 1;\n let sum = 0;\n while (length) {\n const value = digits.charCodeAt(--length) - 48;\n bit ^= 1;\n sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value;\n }\n return sum % 10 === 0;\n}\nexport function isValidCreditCard(input) {\n if (!regexes.creditCard.test(input))\n return false;\n return isLuhnAlgo(input.replace(CC_SANITIZE, \"\"));\n}\nexport const $ZodCreditCard = /*@__PURE__*/ core.$constructor(\"$ZodCreditCard\", (inst, def) => {\n // Shape only — the Luhn check below is not expressible as a pattern, so consumers of `pattern` (JSON Schema, template literals) get the length and separator rules alone.\n def.pattern ?? (def.pattern = regexes.creditCard);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidCreditCard(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"credit_card\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodIBAN //////////////////////////////\n// iso 7064 mod 97-10 checksum without BigInt\nfunction isIso7064Mod97(iban) {\n let remainder = 0;\n const len = iban.length;\n for (let i = 4; i < len; i++) {\n const code = iban.charCodeAt(i);\n remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;\n }\n for (let i = 0; i < 4; i++) {\n const code = iban.charCodeAt(i);\n remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;\n }\n return remainder === 1;\n}\nexport function isValidIBAN(input) {\n if (!regexes.iban.test(input))\n return false;\n return isIso7064Mod97(input);\n}\nexport const $ZodIBAN = /*@__PURE__*/ core.$constructor(\"$ZodIBAN\", (inst, def) => {\n // shape only — checksum is not expressible as a pattern\n def.pattern ?? (def.pattern = regexes.iban);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidIBAN(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"iban\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodJWT //////////////////////////////\nexport function isValidJWT(token, algorithm = null) {\n try {\n const tokensParts = token.split(\".\");\n if (tokensParts.length !== 3)\n return false;\n const [header] = tokensParts;\n if (!header)\n return false;\n // @ts-ignore\n const parsedHeader = JSON.parse(atob(header));\n if (\"typ\" in parsedHeader && parsedHeader?.typ !== \"JWT\")\n return false;\n if (!parsedHeader.alg)\n return false;\n if (algorithm && (!(\"alg\" in parsedHeader) || parsedHeader.alg !== algorithm))\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodJWT = /*@__PURE__*/ core.$constructor(\"$ZodJWT\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidJWT(payload.value, def.alg))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"jwt\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCustomStringFormat\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (def.fn(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodNumber = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.number;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Number(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"number\" && !Number.isNaN(input) && Number.isFinite(input)) {\n return payload;\n }\n const received = typeof input === \"number\"\n ? Number.isNaN(input)\n ? \"NaN\"\n : !Number.isFinite(input)\n ? String(input)\n : undefined\n : undefined;\n payload.issues.push({\n expected: \"number\",\n code: \"invalid_type\",\n input,\n inst,\n ...(received ? { received } : {}),\n });\n return payload;\n };\n});\nexport const $ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodNumberFormat\", (inst, def) => {\n checks.$ZodCheckNumberFormat.init(inst, def);\n $ZodNumber.init(inst, def); // no format checks\n});\nexport const $ZodBoolean = /*@__PURE__*/ core.$constructor(\"$ZodBoolean\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.boolean;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Boolean(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"boolean\")\n return payload;\n payload.issues.push({\n expected: \"boolean\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigInt = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.bigint;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = BigInt(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"bigint\")\n return payload;\n payload.issues.push({\n expected: \"bigint\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodBigIntFormat\", (inst, def) => {\n checks.$ZodCheckBigIntFormat.init(inst, def);\n $ZodBigInt.init(inst, def); // no format checks\n});\nexport const $ZodSymbol = /*@__PURE__*/ core.$constructor(\"$ZodSymbol\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"symbol\")\n return payload;\n payload.issues.push({\n expected: \"symbol\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodUndefined = /*@__PURE__*/ core.$constructor(\"$ZodUndefined\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.undefined;\n inst._zod.values = new Set([undefined]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"undefined\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodNull = /*@__PURE__*/ core.$constructor(\"$ZodNull\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.null;\n inst._zod.values = new Set([null]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (input === null)\n return payload;\n payload.issues.push({\n expected: \"null\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodAny = /*@__PURE__*/ core.$constructor(\"$ZodAny\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodUnknown = /*@__PURE__*/ core.$constructor(\"$ZodUnknown\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodNever = /*@__PURE__*/ core.$constructor(\"$ZodNever\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n payload.issues.push({\n expected: \"never\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodVoid = /*@__PURE__*/ core.$constructor(\"$ZodVoid\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"void\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodDate = /*@__PURE__*/ core.$constructor(\"$ZodDate\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce) {\n try {\n payload.value = new Date(payload.value);\n }\n catch (_err) { }\n }\n const input = payload.value;\n const isDate = input instanceof Date;\n const isValidDate = isDate && !Number.isNaN(input.getTime());\n if (isValidDate)\n return payload;\n payload.issues.push({\n expected: \"date\",\n code: \"invalid_type\",\n input,\n ...(isDate ? { received: \"Invalid Date\" } : {}),\n inst,\n });\n return payload;\n };\n});\n// an oversized container fails its leading size checks before any element is parsed\nfunction capSize(inst, size) {\n const caps = util.sizeCaps(inst._zod.def.checks);\n if (!caps.length)\n return;\n const cap = Math.min(...caps.map((c) => c[0]));\n const parse = inst._zod.parse;\n inst._zod.parse = (payload, ctx) => {\n const n = size(payload.value);\n if (n > cap && !ctx?.skipChecks && ctx?.direction !== \"backward\") {\n for (const [max, ch] of util.sizeCaps(inst._zod.def.checks)) {\n if (n > max && ch._zod.def.when(payload)) {\n const start = payload.issues.length;\n ch._zod.check(payload);\n // the value is still the raw input, so no later check may read it\n payload.issues[start].continue = false;\n util.attachSchema(payload.issues, start, inst);\n return payload;\n }\n }\n }\n return parse(payload, ctx);\n };\n}\nconst arraySize = (input) => (Array.isArray(input) ? input.length : -1);\nconst mapSize = (input) => (input instanceof Map ? input.size : -1);\nconst setSize = (input) => (input instanceof Set ? input.size : -1);\nfunction handleArrayResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodArray = /*@__PURE__*/ core.$constructor(\"$ZodArray\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n expected: \"array\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length);\n const proms = [];\n const abortEarly = ctx?.abortEarly;\n for (let i = 0; i < input.length; i++) {\n const item = input[i];\n const result = def.element._zod.run({\n value: item,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n }\n else {\n handleArrayResult(result, payload, i);\n // the element's payload is authoritative here, since handleArrayResult forwards every issue; an object's is not, because it drops a failed absent optional\n if (abortEarly && result.issues.length !== 0 && util.aborted(result))\n break;\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n capSize(inst, arraySize);\n});\nfunction handlePropertyResult(result, final, key, input, optin, optout) {\n const isPresent = key in input;\n const isOptionalOut = optout === \"optional\";\n // The middle rung means \"absence permitted, nothing supplied in its place\", so an absent key contributes nothing — whatever the schema made of `undefined` is invented, not substituted. Only `optional` reaches this with a value: `defaulted` substitutes, and a schema that isn't optional-out has to keep the key.\n if (!isPresent && isOptionalOut && optin === \"optional\") {\n return;\n }\n if (result.issues.length) {\n // For optional-in/out schemas, ignore errors on absent keys.\n if (optin !== undefined && isOptionalOut && !isPresent) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (!isPresent && optin === undefined) {\n if (!result.issues.length) {\n final.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [key],\n });\n }\n return;\n }\n if (result.value === undefined) {\n if (isPresent || (optin === \"defaulted\" && !isOptionalOut)) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\n// one shared instance; a fresh [] per schema cost 56 bytes retained\nconst NO_SYMBOL_KEYS = [];\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n const ownSymbols = Object.getOwnPropertySymbols(def.shape);\n const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS;\n // aliases `keys` when there are no symbols, so a string-only shape keeps one array\n const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys;\n for (const k of allKeys) {\n if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${String(k)}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n allKeys,\n symbolKeys,\n // string-only: handleCatchall matches it against `for...in`, which never yields a symbol\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst, abortEarly) {\n const unrecognized = [];\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const optin = _catchall.optin;\n const optout = _catchall.optout;\n // starts at 0, not the current length: the shape phase already ran and may have aborted\n let seen = 0;\n for (const key in input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n // Must precede the __proto__ branch: a declared key is not unrecognized, even though the shape loop deliberately strips __proto__ from the parsed output.\n if (keySet.has(key))\n continue;\n // Don't copy an undeclared __proto__ into the result; assignment to a plain {} would replace the result prototype. But in strict mode it is still an unknown key, so report it before skipping.\n if (key === \"__proto__\") {\n if (t === \"never\")\n unrecognized.push(key);\n continue;\n }\n if (t === \"never\") {\n unrecognized.push(key);\n continue;\n }\n const r = _catchall.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));\n }\n else {\n handlePropertyResult(r, payload, key, input, optin, optout);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand.\n continue: true,\n });\n }\n if (!proms.length)\n return payload;\n return Promise.all(proms).then(() => {\n return payload;\n });\n}\nexport const $ZodObject = /*@__PURE__*/ core.$constructor(\"$ZodObject\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodType.init(inst, def);\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n // a cloned def carries its source's accessor, which knows the shape it answers from; adopting that keeps the clone's keys readable without running it\n const sh = desc?.get ? desc.get.raw : (def.shape ?? {});\n if (sh) {\n // Freezes the shape on first read, so its getters resolve once and every later read sees the same schemas.\n const get = () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", { value: newSh });\n get.raw = newSh;\n return newSh;\n };\n get.raw = sh;\n Object.defineProperty(def, \"shape\", { get });\n }\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazyInternal(inst, \"propValues\", (zod) => {\n const shape = zod.def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n if (!Object.prototype.hasOwnProperty.call(propValues, key)) {\n util.assignProp(propValues, key, new Set());\n }\n for (const v of field.values)\n propValues[key].add(v);\n // An omittable slot reads back as undefined at a discriminator lookup, so it has to claim undefined: two options that can both omit the key are not discriminable on it.\n if (field.optin !== undefined)\n propValues[key].add(undefined);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\n const catchall = def.catchall;\n let value;\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n const proms = [];\n const shape = value.shape;\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const key of value.allKeys) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n if (key === \"__proto__\")\n continue;\n const el = shape[key];\n const optin = el._zod.optin;\n const optout = el._zod.optout;\n const r = el._zod.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));\n }\n else {\n handlePropertyResult(r, payload, key, input, optin, optout);\n }\n }\n if (!catchall) {\n return proms.length ? Promise.all(proms).then(() => payload) : payload;\n }\n return handleCatchall(proms, input, payload, ctx, _normalized.value, inst, abortEarly === true);\n };\n});\nexport const $ZodObjectJIT = /*@__PURE__*/ core.$constructor(\"$ZodObjectJIT\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodObject.init(inst, def);\n const superParse = inst._zod.parse;\n const _normalized = util.cached(() => normalizeDef(def));\n const memo = core.globalConfig.memoizer;\n const generateFastpass = (shape) => {\n const normalized = _normalized.value;\n const syms = normalized.symbolKeys;\n // a symbol has no source literal, so it is read as `syms[i]` off the closed-over scope\n const doc = new Doc([\"payload\", \"ctx\"], { shape, inst, memo, syms });\n const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n // prefixes in place, like util.prefixIssues. newResult must land before the early return: a catchall runs after this and would otherwise write onto the caller's input\n const prefixStr = (id, k) => `\n let ${id}_ab = false;\n for (let i = 0; i < ${id}.issues.length; i++) {\n const iss = ${id}.issues[i];\n iss.path = iss.path ? [${k}, ...iss.path] : [${k}];\n payload.issues.push(iss);\n if (iss.continue !== true) ${id}_ab = true;\n }\n if (${id}_ab && ctx && ctx.abortEarly) {\n payload.value = newResult;\n return payload;\n }`;\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.allKeys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`);\n for (const key of normalized.allKeys) {\n if (key === \"__proto__\")\n continue;\n const id = ids[key];\n const k = typeof key === \"symbol\" ? `syms[${syms.indexOf(key)}]` : util.esc(key);\n const isPresent = `${k} in input`;\n const schema = shape[key];\n const optin = schema?._zod?.optin;\n const isOptionalIn = optin !== undefined;\n const isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(k)};`);\n if (isOptionalIn && isOptionalOut) {\n // For optional-in/out schemas, ignore errors on absent keys — and, like the interpreted path, drop the value produced alongside them. The middle rung goes further: it permits absence without supplying anything in its place, so an absent key contributes nothing at all.\n const assign = optin === \"optional\" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`;\n doc.write(`\n const ${id}_present = ${isPresent};\n if (!${id}.issues.length || ${id}_present) {\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n\n if (${assign}) {\n newResult[${k}] = ${id}.value;\n }\n }\n\n `);\n }\n else if (!isOptionalIn) {\n doc.write(`\n const ${id}_present = ${isPresent};\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n if (!${id}_present && !${id}.issues.length) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [${k}]\n });\n if (ctx && ctx.abortEarly) {\n payload.value = newResult;\n return payload;\n }\n }\n\n if (${id}_present) {\n newResult[${k}] = ${id}.value;\n }\n\n `);\n }\n else {\n doc.write(`\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n `);\n if (optin === \"defaulted\") {\n doc.write(`newResult[${k}] = ${id}.value;`);\n }\n else {\n doc.write(`\n if (${id}.value !== undefined || ${isPresent}) {\n newResult[${k}] = ${id}.value;\n }\n `);\n }\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n // closing `shape` in is what pays: turbofan specializes the parser against that one shape object, so every `shape[k]._zod.run` folds to a known callee. as a parameter it stays a generic load and measures 13% slower even with the forwarding frame gone\n return doc.compile();\n };\n let fastpass;\n const isObject = util.isObject;\n const jit = !core.globalConfig.jitless;\n const allowsEval = util.allowsEval;\n const fastEnabled = jit && allowsEval.value; // && !def.catchall;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {\n // always synchronous\n if (!fastpass)\n fastpass = generateFastpass(def.shape);\n payload = fastpass(payload, ctx);\n if (!catchall)\n return payload;\n return handleCatchall([], input, payload, ctx, value, inst, ctx?.abortEarly === true);\n }\n return superParse(payload, ctx);\n };\n});\nfunction handleUnionResults(results, final, inst, ctx) {\n for (const result of results) {\n if (result.issues.length === 0) {\n final.value = result.value;\n return final;\n }\n }\n const nonaborted = results.filter((r) => !util.aborted(r));\n if (nonaborted.length === 1) {\n final.value = nonaborted[0].value;\n return nonaborted[0];\n }\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n return final;\n}\nexport const $ZodUnion = /*@__PURE__*/ core.$constructor(\"$ZodUnion\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.options.some((o) => o._zod.optin === \"defaulted\")\n ? \"defaulted\"\n : zod.def.options.some((o) => o._zod.optin !== undefined)\n ? \"optional\"\n : undefined);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazyInternal(inst, \"values\", (zod) => {\n if (zod.def.options.every((o) => o._zod.values)) {\n return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n if (zod.def.options.every((o) => o._zod.pattern)) {\n const patterns = zod.def.options.map((o) => o._zod.pattern);\n return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join(\"|\")})$`);\n }\n return undefined;\n });\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n if (result.issues.length === 0)\n return result;\n results.push(result);\n }\n }\n if (!async)\n return handleUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleUnionResults(results, payload, inst, ctx);\n });\n };\n});\nfunction handleExclusiveUnionResults(results, final, inst, ctx) {\n const matches = [];\n for (let i = 0; i < results.length; i++) {\n if (results[i].issues.length === 0)\n matches.push(i);\n }\n if (matches.length === 1) {\n final.value = results[matches[0]].value;\n return final;\n }\n if (matches.length === 0) {\n // No matches - same as regular union\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n }\n else {\n // Multiple matches - exclusive union failure\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: [],\n inclusive: false,\n matches,\n });\n }\n return final;\n}\nexport const $ZodXor = /*@__PURE__*/ core.$constructor(\"$ZodXor\", (inst, def) => {\n $ZodUnion.init(inst, def);\n def.inclusive = false;\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n results.push(result);\n }\n }\n if (!async)\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n });\n };\n});\n/** Returns the option whose discriminator claims `value`, or throws if ambiguous. */\nexport function getDiscriminatedOption(union, value) {\n const internals = union._zod;\n let map = internals.bag.optionsMap;\n if (!map) {\n map = discriminatorMap(internals.def);\n internals.bag.optionsMap = map;\n }\n const option = map.get(value);\n if (option === null)\n throw new Error(`Ambiguous discriminator value \"${String(value)}\"`);\n return option;\n}\nfunction discriminatorMap(def) {\n const map = new Map();\n for (const option of def.options) {\n const values = option._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n for (const value of values) {\n if (map.has(value)) {\n if (value !== undefined)\n throw new Error(`Duplicate discriminator value \"${String(value)}\"`);\n // keep the collision marked so a later member cannot reclaim it\n map.set(value, null);\n }\n else {\n map.set(value, option);\n }\n }\n }\n return map;\n}\nexport const $ZodDiscriminatedUnion = \n/*@__PURE__*/\ncore.$constructor(\"$ZodDiscriminatedUnion\", (inst, def) => {\n def.inclusive = false;\n $ZodUnion.init(inst, def);\n const _super = inst._zod.parse;\n util.defineLazyInternal(inst, \"propValues\", (zod) => {\n const propValues = {};\n let undefinedCount = 0;\n for (const option of zod.def.options) {\n const pv = option._zod.propValues;\n if (!pv || Object.keys(pv).length === 0)\n throw new Error(`Invalid discriminated union option at index \"${zod.def.options.indexOf(option)}\"`);\n if (pv[zod.def.discriminator]?.has(undefined))\n undefinedCount++;\n for (const [k, v] of Object.entries(pv)) {\n if (!Object.prototype.hasOwnProperty.call(propValues, k)) {\n util.assignProp(propValues, k, new Set());\n }\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n if (!zod.def.unionFallback && undefinedCount > 1)\n propValues[zod.def.discriminator]?.delete(undefined);\n return propValues;\n });\n // Checked now rather than in the lookup map below, so an option that lacks the discriminator fails at the `discriminatedUnion` call instead of on the first object parsed. Options whose shape cannot be enumerated without resolving it — pipes and lazies — are left to the map.\n def.options.forEach((option, i) => {\n const propShape = util.rawShape(option._zod.def);\n if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) {\n throw new Error(`Invalid discriminated union option at index \"${i}\"`);\n }\n });\n const disc = util.cached(() => discriminatorMap(def));\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isObject(input)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"object\",\n input,\n inst,\n });\n return payload;\n }\n const value = input?.[def.discriminator];\n const opt = disc.value.get(value);\n // forward metadata cannot choose an encoder for an absent tag\n if (opt && (value !== undefined || ctx.direction !== \"backward\")) {\n return opt._zod.run(payload, ctx);\n }\n // Fall back to union matching when the fast discriminator path fails:\n // - explicitly enabled via unionFallback, or\n // - during backward direction (encode), since codec-based discriminators have different values in forward vs backward directions\n if (def.unionFallback || ctx.direction === \"backward\") {\n return _super(payload, ctx);\n }\n // no matching discriminator\n payload.issues.push({\n code: \"invalid_union\",\n errors: [],\n note: \"No matching discriminator\",\n discriminator: def.discriminator,\n options: Array.from(disc.value.keys()).filter((value) => disc.value.get(value) !== null),\n input,\n path: [def.discriminator],\n inst,\n });\n return payload;\n };\n});\nexport const $ZodIntersection = /*@__PURE__*/ core.$constructor(\"$ZodIntersection\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n const left = def.left._zod.run({ value: input, issues: [] }, ctx);\n const right = def.right._zod.run({ value: input, issues: [] }, ctx);\n const async = left instanceof Promise || right instanceof Promise;\n if (async) {\n return Promise.all([left, right]).then(([left, right]) => {\n return handleIntersectionResults(payload, left, right);\n });\n }\n return handleIntersectionResults(payload, left, right);\n };\n});\nexport function mergeValues(a, b) {\n // const aType = parse.t(a);\n // const bType = parse.t(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n if (a instanceof Date && b instanceof Date && +a === +b) {\n return { valid: true, data: a };\n }\n if (util.isPlainObject(a) && util.isPlainObject(b)) {\n const bKeys = Object.keys(b);\n const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n if (Object.prototype.hasOwnProperty.call(newObj, \"__proto__\"))\n delete newObj.__proto__;\n for (const key of sharedKeys) {\n if (key === \"__proto__\")\n continue;\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [key, ...sharedValue.mergeErrorPath],\n };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return { valid: false, mergeErrorPath: [] };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [index, ...sharedValue.mergeErrorPath],\n };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n return { valid: false, mergeErrorPath: [] };\n}\nfunction handleIntersectionResults(result, left, right) {\n // Track which side(s) reject each key. A key rejection is reported only when BOTH sides reject it, so a key owned by one branch survives the other's key schema. strictObject reports these as unrecognized_keys; a record with an open key schema reports one invalid_key per key.\n const unrecKeys = new Map();\n let unrecIssue;\n const keyIssues = new Map();\n const collect = (iss, side) => {\n let keys;\n if (iss.code === \"unrecognized_keys\" && !iss.path?.length) {\n unrecIssue ?? (unrecIssue = iss);\n keys = iss.keys;\n }\n else if (iss.code === \"invalid_key\" && iss.origin === \"record\" && iss.path?.length === 1) {\n const k = String(iss.path[0]);\n if (!keyIssues.has(k))\n keyIssues.set(k, iss);\n keys = [k];\n }\n else {\n return false;\n }\n for (const k of keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k)[side] = true;\n }\n return true;\n };\n for (const iss of left.issues) {\n if (!collect(iss, \"l\"))\n result.issues.push(iss);\n }\n for (const iss of right.issues) {\n if (!collect(iss, \"r\"))\n result.issues.push(iss);\n }\n // Report only keys rejected by BOTH sides\n const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n if (bothKeys.length) {\n const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : [];\n if (aggregated.length)\n result.issues.push({ ...unrecIssue, keys: aggregated });\n for (const k of bothKeys) {\n if (!aggregated.includes(k) && keyIssues.has(k))\n result.issues.push(keyIssues.get(k));\n }\n }\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\n if (util.aborted(result))\n return result;\n throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);\n }\n result.value = merged.data;\n return result;\n}\nexport const $ZodTuple = /*@__PURE__*/ core.$constructor(\"$ZodTuple\", (inst, def) => {\n $ZodType.init(inst, def);\n const items = def.items;\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n input,\n inst,\n expected: \"tuple\",\n code: \"invalid_type\",\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, [], ctx) : [];\n const proms = [];\n const optinStart = getTupleOptStart(items, \"optin\");\n const optoutStart = getTupleOptStart(items, \"optout\");\n if (!def.rest) {\n if (input.length < optinStart) {\n payload.issues.push({\n code: \"too_small\",\n minimum: optinStart,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n return payload;\n }\n if (input.length > items.length) {\n payload.issues.push({\n code: \"too_big\",\n maximum: items.length,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n }\n }\n // Run every item in parallel, collecting results into an indexed array. The post-processing in `handleTupleResults` walks them in order so it can decide whether an absent optional-output error can truncate the tail or must be reported to preserve required output.\n const itemResults = new Array(items.length);\n // only tracked when there is a rest loop to skip\n const abortEarly = def.rest ? ctx?.abortEarly : undefined;\n let itemAborted = false;\n for (let i = 0; i < items.length; i++) {\n const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((rr) => {\n itemResults[i] = rr;\n }));\n }\n else {\n itemResults[i] = r;\n if (abortEarly && !itemAborted && r.issues.length)\n itemAborted = util.aborted(r);\n }\n }\n // sound because rest is non-empty exactly when every fixed index is present, the one case handleTupleResults cannot discard an item's issues\n if (def.rest && !itemAborted) {\n let i = items.length - 1;\n const rest = input.slice(items.length);\n let seen = payload.issues.length;\n for (const el of rest) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n i++;\n const result = def.rest._zod.run({ value: el, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((r) => handleTupleResult(r, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));\n }\n return handleTupleResults(itemResults, payload, items, input, optoutStart);\n };\n});\nfunction getTupleOptStart(items, key) {\n for (let i = items.length - 1; i >= 0; i--) {\n // optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued.\n const omittable = key === \"optin\" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === \"optional\";\n if (!omittable)\n return i + 1;\n }\n return 0;\n}\nfunction handleTupleResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nfunction handleTupleResults(itemResults, final, items, input, optoutStart) {\n // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional rule, but only after `optoutStart`: the first index where the output tuple tail can be absent.\n for (let i = 0; i < items.length; i++) {\n const r = itemResults[i];\n const isPresent = i < input.length;\n // The array analog of `handlePropertyResult`'s absent-key early return: the middle rung permits absence without supplying anything in its place, so the tail truncates here instead of materializing whatever the item made of `undefined`.\n if (!isPresent && i >= optoutStart && items[i]._zod.optin === \"optional\") {\n final.value.length = i;\n break;\n }\n if (r.issues.length) {\n if (!isPresent && i >= optoutStart) {\n final.value.length = i;\n break;\n }\n final.issues.push(...util.prefixIssues(i, r.issues));\n }\n final.value[i] = r.value;\n }\n // Drop trailing slots that produced `undefined` for absent input\n // (the array analog of an absent optional key on an object). The\n // `i >= input.length` floor is critical: an explicit `undefined`\n // *inside* the input must be preserved even when the schema is\n // optional-out (e.g. `z.string().or(z.undefined())` accepting an\n // explicit undefined value).\n for (let i = final.value.length - 1; i >= input.length; i--) {\n if (items[i]._zod.optout === \"optional\" && final.value[i] === undefined) {\n final.value.length = i;\n }\n else {\n break;\n }\n }\n return final;\n}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isPlainObject(input)) {\n payload.issues.push({\n expected: \"record\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n // no guard in either loop below: a record's invalid_key aborts but an enclosing intersection can reconcile it, so a stopped loop hides keys the sibling does not own and the intersection then rejects nothing\n const proms = [];\n const values = def.keyType._zod.values;\n if (values && !def.partial) {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n const recordKeys = new Set();\n for (const key of values) {\n if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n recordKeys.add(typeof key === \"number\" ? key.toString() : key);\n // A declared __proto__ is stripped but is not an unrecognized key.\n if (key === \"__proto__\")\n continue;\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (keyResult.issues.length) {\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n continue;\n }\n const outKey = keyResult.value;\n if (outKey === \"__proto__\")\n continue;\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }\n }\n }\n let unrecognized;\n for (const key in input) {\n if (!recordKeys.has(key)) {\n if (def.mode === \"loose\") {\n // skip __proto__ so it can't replace the result prototype via the assignment setter on the plain {} we build into\n if (key === \"__proto__\")\n continue;\n payload.value[key] = input[key];\n }\n else {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true,\n });\n }\n }\n else {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n // An enumerable key schema declares which keys the record owns, so a key outside the set is unrecognized. A non-enumerable one (regex, refine) is a constraint every key must satisfy, so a failing key is invalid. Only the former is reconcilable against the other side of an intersection.\n let unrecognized;\n // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object()\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\")\n continue;\n if (!Object.prototype.propertyIsEnumerable.call(input, key))\n continue;\n let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n // Numeric string fallback: if key is a numeric string and failed, retry with Number(key). This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals\n const checkNumericKey = typeof key === \"string\" && regexes.number.test(key) && keyResult.issues.length;\n if (checkNumericKey) {\n const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);\n if (retryResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (retryResult.issues.length === 0) {\n keyResult = retryResult;\n }\n }\n if (keyResult.issues.length) {\n if (def.mode === \"loose\") {\n // Pass through unchanged\n payload.value[key] = input[key];\n }\n else if (values) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n else {\n // Default \"strict\" behavior: error on invalid key\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n }\n continue;\n }\n // the guard above tests the raw input key, but the key schema can normalize an ordinary key into __proto__; re-check the key we actually write under\n const outKey = keyResult.value;\n if (outKey === \"__proto__\")\n continue;\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true,\n });\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload;\n };\n});\nexport const $ZodMap = /*@__PURE__*/ core.$constructor(\"$ZodMap\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Map)) {\n payload.issues.push({\n expected: \"map\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n payload.value = memo ? memo.alloc(inst, payload, new Map(), ctx) : new Map();\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const [key, value] of input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);\n if (keyResult instanceof Promise || valueResult instanceof Promise) {\n proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }));\n }\n else {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n capSize(inst, mapSize);\n});\nfunction handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {\n if (keyResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, keyResult.issues));\n }\n else {\n final.issues.push({\n code: \"invalid_key\",\n origin: \"map\",\n input,\n inst,\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n if (valueResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, valueResult.issues));\n }\n else {\n final.issues.push({\n origin: \"map\",\n code: \"invalid_element\",\n input,\n inst,\n key: key,\n issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n final.value.set(keyResult.value, valueResult.value);\n}\nexport const $ZodSet = /*@__PURE__*/ core.$constructor(\"$ZodSet\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Set)) {\n payload.issues.push({\n input,\n inst,\n expected: \"set\",\n code: \"invalid_type\",\n });\n return payload;\n }\n const proms = [];\n payload.value = memo ? memo.alloc(inst, payload, new Set(), ctx) : new Set();\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const item of input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleSetResult(result, payload)));\n }\n else\n handleSetResult(result, payload);\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n capSize(inst, setSize);\n});\nfunction handleSetResult(result, final) {\n if (result.issues.length) {\n final.issues.push(...result.issues);\n }\n final.value.add(result.value);\n}\nexport const $ZodEnum = /*@__PURE__*/ core.$constructor(\"$ZodEnum\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = util.getEnumValues(def.entries);\n const valuesSet = new Set(values);\n inst._zod.values = valuesSet;\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const patternValues = util.getEnumValues(zod.def.entries).filter((k) => util.propertyKeyTypes.has(typeof k));\n // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n return new RegExp(patternValues.length ? `^(${patternValues.map((o) => util.escapeRegex(o.toString())).join(\"|\")})$` : \"^[^\\\\s\\\\S]$\");\n });\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (valuesSet.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodLiteral = /*@__PURE__*/ core.$constructor(\"$ZodLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = new Set(def.values);\n inst._zod.values = values;\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const vals = zod.def.values;\n // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n return new RegExp(vals.length\n ? `^(${vals\n .map((o) => typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o))\n .join(\"|\")})$`\n : \"^[^\\\\s\\\\S]$\");\n });\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (values.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values: def.values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodFile = /*@__PURE__*/ core.$constructor(\"$ZodFile\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n // @ts-ignore\n if (input instanceof File)\n return payload;\n payload.issues.push({\n expected: \"file\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodTransform = /*@__PURE__*/ core.$constructor(\"$ZodTransform\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n core.globalConfig.memoizer?.guard(inst);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n const _out = def.transform(payload.value, payload);\n if (ctx.async) {\n const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n return payload;\n };\n});\nfunction handleOptionalResult(payload, result) {\n // A substituting schema that still failed has no usable answer; yield undefined. Its issues are simply dropped: it ran on a payload of its own, so there is no shared array to truncate and nothing of the caller's to lose with it.\n payload.value = result.issues.length ? undefined : result.value;\n return payload;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n // .optional() propagates absence rather than substituting for it, so a defaulted inner keeps its rung.\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n inst._zod.optout = \"optional\";\n util.defineLazyInternal(inst, \"values\", (zod) => {\n const values = zod.def.innerType._zod.values;\n return values ? new Set([...values, undefined]) : undefined;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const pattern = zod.def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (payload.value === undefined) {\n // Only the top rung substitutes a value for absence; everything else leaves it intact, which is what .optional() means.\n if (def.innerType._zod.optin !== \"defaulted\")\n return payload;\n // Its own payload, for the same reason $ZodCatch gets one: a pipe forwards an unrecognized key through the caller's issues array, and this must not read that as the substituting schema failing and drop it.\n const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);\n if (result instanceof Promise)\n return result.then((result) => handleOptionalResult(payload, result));\n return handleOptionalResult(payload, result);\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodExactOptional = /*@__PURE__*/ core.$constructor(\"$ZodExactOptional\", (inst, def) => {\n // Call parent init - inherits optin/optout = \"optional\"\n $ZodOptional.init(inst, def);\n // Override values/pattern to NOT add undefined\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n util.defineLazyInternal(inst, \"pattern\", (zod) => zod.def.innerType._zod.pattern);\n // Override parse to just delegate (no undefined handling)\n inst._zod.parse = (payload, ctx) => {\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNullable = /*@__PURE__*/ core.$constructor(\"$ZodNullable\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const pattern = zod.def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazyInternal(inst, \"values\", (zod) => {\n return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n // Forward direction (decode): allow null to pass through\n if (payload.value === null)\n return payload;\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodDefault = /*@__PURE__*/ core.$constructor(\"$ZodDefault\", (inst, def) => {\n $ZodType.init(inst, def);\n // inst._zod.qin = \"true\";\n inst._zod.optin = \"defaulted\";\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply defaults for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n /**\n * $ZodDefault returns the default value immediately in forward direction.\n * It doesn't pass the default value into the validator (\"prefault\"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a \"prefault\" for the pipe. */\n return payload;\n }\n // Forward direction: continue with default handling\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleDefaultResult(result, def));\n }\n return handleDefaultResult(result, def);\n };\n});\nfunction handleDefaultResult(payload, def) {\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return payload;\n}\nexport const $ZodPrefault = /*@__PURE__*/ core.$constructor(\"$ZodPrefault\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"defaulted\";\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply prefault for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNonOptional = /*@__PURE__*/ core.$constructor(\"$ZodNonOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => {\n const v = zod.def.innerType._zod.values;\n return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleNonOptionalResult(result, inst));\n }\n return handleNonOptionalResult(result, inst);\n };\n});\nfunction handleNonOptionalResult(payload, inst) {\n if (!payload.issues.length && payload.value === undefined) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: payload.value,\n inst,\n });\n }\n return payload;\n}\nexport const $ZodSuccess = /*@__PURE__*/ core.$constructor(\"$ZodSuccess\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(\"ZodSuccess\");\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.issues.length === 0;\n return payload;\n });\n }\n payload.value = result.issues.length === 0;\n return payload;\n };\n});\nfunction handleCatchResult(payload, result, def, ctx) {\n if (!result.issues.length) {\n payload.value = result.value;\n // The value carries up, so the flag describing it has to carry with it: a back-edge into a node still being parsed must not be frozen by an enclosing readonly, and its checks belong to the node itself. Guarded so the ordinary case adds no own property.\n if (result.memo)\n payload.memo = true;\n return payload;\n }\n // Spread the inner's own payload, not ours: `value` has to stay the input the catch was handed, and the inner ran on a payload of its own so its issues are already private to this call.\n payload.value = def.catchValue({\n ...result,\n value: payload.value,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n return payload;\n}\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply catch logic\n const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleCatchResult(payload, result, def, ctx));\n }\n return handleCatchResult(payload, result, def, ctx);\n };\n});\nexport const $ZodNaN = /*@__PURE__*/ core.$constructor(\"$ZodNaN\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"number\" || !Number.isNaN(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"nan\",\n code: \"invalid_type\",\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodPipe = /*@__PURE__*/ core.$constructor(\"$ZodPipe\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handlePipeResult(right, def.in, ctx));\n }\n return handlePipeResult(right, def.in, ctx);\n }\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handlePipeResult(left, def.out, ctx));\n }\n return handlePipeResult(left, def.out, ctx);\n };\n});\nfunction handlePipeResult(left, next, ctx) {\n // Any issue stops the pipe, so a failing refinement never feeds its transform. An unrecognized key is the exception: it describes the input's extra properties, not the value being piped, and an enclosing intersection may yet reconcile it.\n if (left.issues.some((iss) => iss.code !== \"unrecognized_keys\")) {\n // prevent further checks\n left.aborted = true;\n return left;\n }\n return next._zod.run({ value: left.value, issues: left.issues }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handleCodecAResult(left, def, ctx));\n }\n return handleCodecAResult(left, def, ctx);\n }\n else {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handleCodecAResult(right, def, ctx));\n }\n return handleCodecAResult(right, def, ctx);\n }\n };\n});\nfunction handleCodecAResult(result, def, ctx) {\n if (result.issues.length) {\n // prevent further checks\n result.aborted = true;\n return result;\n }\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const transformed = def.transform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));\n }\n return handleCodecTxResult(result, transformed, def.out, ctx);\n }\n else {\n const transformed = def.reverseTransform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));\n }\n return handleCodecTxResult(result, transformed, def.in, ctx);\n }\n}\nfunction handleCodecTxResult(left, value, nextSchema, ctx) {\n // Check if transform added any issues\n if (left.issues.length) {\n left.aborted = true;\n return left;\n }\n return nextSchema._zod.run({ value, issues: left.issues }, ctx);\n}\nexport const $ZodPreprocess = /*@__PURE__*/ core.$constructor(\"$ZodPreprocess\", (inst, def) => {\n $ZodPipe.init(inst, def);\n});\nexport const $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.innerType._zod.propValues);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType?._zod?.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType?._zod?.optout);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then(handleReadonlyResult);\n }\n return handleReadonlyResult(result);\n };\n});\nfunction handleReadonlyResult(payload) {\n // A repeat visit hands back a node that is still being built; freezing it here would make the rest of its keys fail to assign.\n if (!payload.memo)\n payload.value = Object.freeze(payload.value);\n return payload;\n}\n// a leaf's pattern source with its own checks folded in: the last pattern-carrying check wins, else length bounds narrow the catch-all, else an integer format narrows the number form. the fold lives here instead of on `_zod.pattern` so a bundle without template literals never pays for it\nfunction leafPattern(schema) {\n const def = schema._zod.def;\n let pattern = def.pattern;\n let isInt = !!def.format?.includes(\"int\");\n let minimum;\n let maximum;\n for (const ch of def.checks ?? []) {\n const d = ch._zod.def;\n if (d.pattern)\n pattern = d.pattern;\n isInt || (isInt = !!d.format?.includes(\"int\"));\n const lo = d.minimum ?? d.length;\n const hi = d.maximum ?? d.length;\n if (lo !== undefined && (minimum === undefined || lo > minimum))\n minimum = lo;\n if (hi !== undefined && (maximum === undefined || hi < maximum))\n maximum = hi;\n }\n if (pattern)\n return pattern.source;\n // an empty range matches nothing at runtime, and `{8,5}` is not a legal quantifier\n if (minimum !== undefined && maximum !== undefined && minimum > maximum)\n return \"(?!)\";\n if (minimum !== undefined || maximum !== undefined)\n return regexes.string({ minimum, maximum }).source;\n const own = schema._zod.pattern;\n return (isInt && own === regexes.number ? regexes.integer : own)?.source;\n}\n// a part's pattern source. a wrapper's pattern embeds its inner pattern's source verbatim, so the folded form is substituted in place without knowing the wrapper's own composition; a union's options are joined the way the union builds its own pattern\nfunction partPattern(schema) {\n const def = schema._zod.def;\n const own = schema._zod.pattern?.source;\n // lazy resolves its inner on the internals, not the def\n const inner = def.innerType ?? schema._zod.innerType;\n if (inner) {\n const before = inner._zod.pattern?.source;\n const after = partPattern(inner);\n if (own && before && after && after !== before) {\n return own.replace(util.cleanRegex(before), () => util.cleanRegex(after));\n }\n return own;\n }\n if (def.options) {\n const sources = def.options.map(partPattern);\n if (sources.every(Boolean))\n return `^(${sources.map((s) => util.cleanRegex(s)).join(\"|\")})$`;\n }\n return leafPattern(schema);\n}\nexport const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"$ZodTemplateLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const regexParts = [];\n for (const part of def.parts) {\n if (typeof part === \"object\" && part !== null) {\n // is Zod schema\n const source = partPattern(part);\n if (!source) {\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n regexParts.push(util.cleanRegex(source));\n }\n else if (part === null || util.primitiveTypes.has(typeof part)) {\n regexParts.push(util.escapeRegex(`${part}`));\n }\n else {\n throw new Error(`Invalid template literal part: ${part}`);\n }\n }\n inst._zod.pattern = new RegExp(`^${regexParts.join(\"\")}$`);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"string\") {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"string\",\n code: \"invalid_type\",\n });\n return payload;\n }\n inst._zod.pattern.lastIndex = 0;\n if (!inst._zod.pattern.test(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n code: \"invalid_format\",\n format: def.format ?? \"template_literal\",\n pattern: inst._zod.pattern.source,\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodFunction = /*@__PURE__*/ core.$constructor(\"$ZodFunction\", (inst, def) => {\n $ZodType.init(inst, def);\n // Defined, not assigned: the classic prototype exposes `_def` as a getter with no setter.\n Object.defineProperty(inst, \"_def\", { value: def });\n inst._zod.def = def;\n inst.implement = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implement() must be called with a function\");\n }\n // Defined inline so the closure stays anonymous: binding it to a `const` first names it, which costs 256 bytes per implemented function.\n return Object.defineProperty(function (...args) {\n const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;\n const result = Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return parse(inst._def.output, result);\n }\n return result;\n }, \"_zod\", { value: inst._zod, enumerable: false });\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return Object.defineProperty(async function (...args) {\n const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;\n const result = await Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return await parseAsync(inst._def.output, result);\n }\n return result;\n }, \"_zod\", { value: inst._zod, enumerable: false });\n };\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"function\") {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"function\",\n input: payload.value,\n inst,\n });\n return payload;\n }\n // Check if output is a promise type to determine if we should use async implementation\n const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === \"promise\";\n if (hasPromiseOutput) {\n payload.value = inst.implementAsync(payload.value);\n }\n else {\n payload.value = inst.implement(payload.value);\n }\n return payload;\n };\n inst.input = (...args) => {\n const F = inst.constructor;\n if (Array.isArray(args[0])) {\n return new F({\n type: \"function\",\n input: new $ZodTuple({\n type: \"tuple\",\n items: args[0],\n rest: args[1],\n }),\n output: inst._def.output,\n });\n }\n return new F({\n type: \"function\",\n input: args[0],\n output: inst._def.output,\n });\n };\n inst.output = (output) => {\n const F = inst.constructor;\n return new F({\n type: \"function\",\n input: inst._def.input,\n output,\n });\n };\n return inst;\n});\nexport const $ZodPromise = /*@__PURE__*/ core.$constructor(\"$ZodPromise\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));\n };\n});\nexport const $ZodLazy = /*@__PURE__*/ core.$constructor(\"$ZodLazy\", (inst, def) => {\n $ZodType.init(inst, def);\n // Cache the resolved inner type on the shared `def` so all clones of this lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance, preserving identity for cycle detection on recursive schemas.\n util.defineLazy(inst._zod, \"innerType\", () => {\n const d = def;\n if (!d._cachedInner)\n d._cachedInner = def.getter();\n return d._cachedInner;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => zod.innerType?._zod?.pattern);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.innerType?._zod?.propValues);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.innerType?._zod?.optin ?? undefined);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.innerType?._zod?.optout ?? undefined);\n inst._zod.parse = (payload, ctx) => {\n const inner = inst._zod.innerType;\n return inner._zod.run(payload, ctx);\n };\n});\nexport const $ZodCustom = /*@__PURE__*/ core.$constructor(\"$ZodCustom\", (inst, def) => {\n checks.$ZodCheck.init(inst, def);\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _) => {\n return payload;\n };\n inst._zod.check = (payload) => {\n const input = payload.value;\n const r = def.fn(input);\n if (r instanceof Promise) {\n return r.then((r) => handleRefineResult(r, payload, input, inst));\n }\n handleRefineResult(r, payload, input, inst);\n return;\n };\n});\nfunction handleRefineResult(result, payload, input, inst) {\n if (!result) {\n const _iss = {\n code: \"custom\",\n input,\n inst, // incorporates params.error into issue reporting\n path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting\n continue: !inst._zod.def.abort,\n // params: inst._zod.def.params,\n };\n if (inst._zod.def.params)\n _iss.params = inst._zod.def.params;\n payload.issues.push(util.issue(_iss));\n }\n}\n", "import * as util from \"./util.js\";\nexport class $ZodCyclicError extends Error {\n constructor() {\n super(`Cannot parse a reference cycle that closes through a transform`);\n this.name = \"ZodCyclicError\";\n }\n}\n/** Keyed off the context object every schema in one parse call already shares. */\nconst STATE = \"~memo\";\nconst NO_ISSUES = [];\n// a value a cycle can close through\nfunction isRef(value) {\n return value !== null && typeof value === \"object\";\n}\n// Receivers prefix paths in place, so the cache and every hand-out need their own copies.\nfunction cloneIssues(issues) {\n return issues.map((iss) => (iss.path ? { ...iss, path: iss.path.slice() } : { ...iss }));\n}\nconst recursive = /*@__PURE__*/ new WeakMap();\n/** What the walk established, in order of certainty: ordered so the strongest answer among children wins. */\nconst NONE = 0;\nconst ASSUMED = 1;\nconst PROVEN = 2;\n/** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */\nfunction isRecursive(inst, stack, resolve) {\n const cached = recursive.get(inst);\n if (cached !== undefined)\n return cached ? PROVEN : NONE;\n // Relative to the walk in progress, so not cached.\n if (stack.has(inst))\n return PROVEN;\n stack.add(inst);\n let result = NONE;\n const check = (child) => {\n if (result !== PROVEN && child?._zod) {\n const answer = isRecursive(child, stack, resolve);\n if (answer > result)\n result = answer;\n }\n };\n // `Reflect.ownKeys` rather than `Object.keys`, so a cycle through a declared symbol key is still seen\n const shape = (sh, spread) => {\n let answer = NONE;\n for (const key of Reflect.ownKeys(sh)) {\n const desc = Object.getOwnPropertyDescriptor(sh, key);\n // an object resolves its shape by spread, so a key it does not enumerate is never parsed; `z.properties` reads every own key and so keeps them all\n if (spread && !desc.enumerable)\n continue;\n // resolving runs user code, and a factory mints a fresh subtree per read, so an edge the walk can't follow counts as a cycle\n const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve) : NONE;\n if (child > answer)\n answer = child;\n }\n return answer;\n };\n const merge = (answer) => {\n if (answer > result)\n result = answer;\n };\n const def = inst._zod.def;\n const kind = def.type;\n switch (kind) {\n case \"object\": {\n const raw = util.rawShape(def);\n // a def with no raw shape answers `shape` from an accessor of its own, and running that can mint a whole fresh subtree\n merge(raw ? shape(raw, true) : ASSUMED);\n check(def.catchall);\n break;\n }\n case \"array\":\n check(def.element);\n break;\n case \"tuple\":\n for (const el of def.items)\n check(el);\n check(def.rest);\n break;\n case \"record\":\n case \"map\":\n check(def.keyType);\n check(def.valueType);\n break;\n case \"set\":\n check(def.valueType);\n break;\n case \"union\":\n for (const el of def.options)\n check(el);\n break;\n case \"intersection\":\n check(def.left);\n check(def.right);\n break;\n case \"optional\":\n case \"nullable\":\n case \"default\":\n case \"prefault\":\n case \"catch\":\n case \"readonly\":\n case \"nonoptional\":\n case \"promise\":\n case \"success\":\n check(def.innerType);\n break;\n case \"pipe\":\n check(def.in);\n check(def.out);\n break;\n case \"function\":\n check(def.input);\n check(def.output);\n break;\n // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly\n case \"lazy\": {\n const inner = def._cachedInner ?? (resolve ? inst._zod.innerType : undefined);\n // walked with resolution off: one hop sees past the deferral, and a lazy that yields only another unresolved lazy is generative, so it stops there\n merge(inner ? isRecursive(inner, stack, false) : ASSUMED);\n break;\n }\n // a leaf by choice: `parts` are regex fragments, not data positions\n case \"template_literal\":\n // leaves\n case \"string\":\n case \"number\":\n case \"int\":\n case \"boolean\":\n case \"bigint\":\n case \"symbol\":\n case \"undefined\":\n case \"null\":\n case \"void\":\n case \"never\":\n case \"any\":\n case \"unknown\":\n case \"date\":\n case \"nan\":\n case \"enum\":\n case \"literal\":\n case \"file\":\n case \"transform\":\n case \"custom\":\n break;\n default: {\n // a new built-in kind becomes a compile error here\n kind;\n // a user-defined kind can still hold children, and only its author knows where, so fall back to scanning the def — skipping accessors, since reading one can run user code\n for (const key in def) {\n const desc = Object.getOwnPropertyDescriptor(def, key);\n if (!desc || desc.get)\n continue;\n const value = desc.value;\n if (!value || typeof value !== \"object\")\n continue;\n if (value._zod)\n check(value);\n else if (Array.isArray(value))\n for (const el of value)\n check(el);\n }\n }\n }\n stack.delete(inst);\n return settle(inst, result);\n}\n/** An assumed answer must not outlive the resolution that settles it, so only a certain one is cached. */\nfunction settle(inst, answer) {\n if (answer !== ASSUMED)\n recursive.set(inst, answer === PROVEN);\n return answer;\n}\n/**\n * Whether one parse can re-enter this schema, i.e. its subtree contains a cycle.\n * Exported for `z.compile`, which refuses to compile such a schema: cycle\n * breaking is driven from here off state keyed on the parse context, and a\n * generated fast path has no context to key on.\n */\nexport function isRecursiveSchema(inst) {\n // z.compile never parses, so nothing would ever resolve a lazy for it; it runs once and already treats a throw here as recursive\n return isRecursive(inst, new Set(), true) !== NONE;\n}\nfunction bucketFor(state, inst) {\n let bucket = state.buckets.get(inst);\n if (!bucket) {\n bucket = new WeakMap();\n state.buckets.set(inst, bucket);\n }\n return bucket;\n}\n// Set immediately before delegating to core and cleared immediately after, so `alloc` registers only for a visit this module is driving.\nlet handoff;\n// Allocated but unfinished entries. `alloc` and the matching pop both happen in the synchronous part of a parse, so they nest even when children are async, and one stack serves every schema.\nconst open = [];\nconst memo = {\n alloc(_inst, payload, empty) {\n const bucket = handoff;\n if (!bucket)\n return empty;\n handoff = undefined;\n const entry = { value: empty, issues: null };\n bucket.set(payload.value, entry);\n open.push(entry);\n return empty;\n },\n guard(inst) {\n var _a;\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred.push(() => {\n const base = inst._zod.parse;\n const wrapped = (payload, ctx) => {\n // The value is a placeholder a back-edge is still waiting on, so the cycle closes through this transform. Its output can't exist in time to bind.\n if (ctx.direction !== \"backward\" && isBackEdge(ctx, payload.value))\n throw new $ZodCyclicError();\n return base(payload, ctx);\n };\n inst._zod.parse = wrapped;\n if (inst._zod.run === base)\n inst._zod.run = wrapped;\n });\n },\n attach(inst) {\n var _a;\n let isRecursiveInst;\n let rechecked = false;\n // a recursive schema is re-entered many times per parse and its bucket never changes\n let lastCtx;\n let lastBucket;\n // Wraps `parse` in a deferred so it sees the container's final parse. Core's own deferred copies `parse` into `run` when there are no checks, and it ran first, so `run` is patched to match; with checks, `run` reads `parse` dynamically.\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred.push(() => {\n const base = inst._zod.parse;\n const wrapped = (payload, ctx) => {\n if (isRecursiveInst === undefined) {\n const walked = isRecursive(inst, new Set(), false);\n if (walked === NONE) {\n // Nothing here can ever fire, so take it back out.\n inst._zod.parse = base;\n if (inst._zod.run === wrapped)\n inst._zod.run = base;\n return base(payload, ctx);\n }\n // this parse resolves the deferred edges on its own path, so ask once more before latching\n if (walked === PROVEN || rechecked)\n isRecursiveInst = true;\n else\n rechecked = true;\n }\n const input = payload.value;\n if (!isRef(input))\n return base(payload, ctx);\n let state = ctx[STATE];\n if (!state) {\n state = { buckets: new WeakMap(), backEdges: undefined };\n ctx[STATE] = state;\n }\n let bucket;\n if (lastCtx === ctx) {\n bucket = lastBucket;\n }\n else {\n bucket = bucketFor(state, inst);\n lastCtx = ctx;\n lastBucket = bucket;\n }\n const hit = bucket.get(input);\n if (hit) {\n payload.value = hit.value;\n if (hit.issues) {\n if (hit.issues.length)\n payload.issues.push(...cloneIssues(hit.issues));\n }\n else {\n // Still being parsed: its own checks cover it, so skip them here.\n payload.memo = true;\n state.backEdges ?? (state.backEdges = new WeakSet());\n state.backEdges.add(hit.value);\n }\n return payload;\n }\n handoff = bucket;\n const depth = open.length;\n const result = base(payload, ctx);\n handoff = undefined;\n // A container that rejected its input outright allocated nothing.\n const entry = open.length > depth ? open.pop() : undefined;\n // Both paths written out so the sync one allocates no closure. It runs once per node, and capturing here cost more than everything else combined.\n if (result instanceof Promise) {\n return result.then((r) => {\n if (entry)\n entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES;\n return r;\n });\n }\n if (entry)\n entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES;\n return result;\n };\n inst._zod.parse = wrapped;\n if (inst._zod.run === base)\n inst._zod.run = wrapped;\n });\n },\n};\n/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */\nexport function memoizer() {\n return memo;\n}\n/** Whether this value is a node a back-edge resolved to before it finished. */\nexport function isBackEdge(ctx, value) {\n const backEdges = ctx[STATE]?.backEdges;\n return backEdges !== undefined && isRef(value) && backEdges.has(value);\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"characters\", verb: \"to have\" },\n file: { unit: \"bytes\", verb: \"to have\" },\n array: { unit: \"items\", verb: \"to have\" },\n set: { unit: \"items\", verb: \"to have\" },\n map: { unit: \"entries\", verb: \"to have\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"input\",\n email: \"email address\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO datetime\",\n date: \"ISO date\",\n time: \"ISO time\",\n duration: \"ISO duration\",\n ipv4: \"IPv4 address\",\n ipv6: \"IPv6 address\",\n mac: \"MAC address\",\n cidrv4: \"IPv4 range\",\n cidrv6: \"IPv6 range\",\n base64: \"base64-encoded string\",\n base64url: \"base64url-encoded string\",\n json_string: \"JSON string\",\n e164: \"E.164 number\",\n currency_code: \"currency code\",\n credit_card: \"credit card number\",\n iban: \"IBAN\",\n jwt: \"JWT\",\n template_literal: \"input\",\n };\n // type names: missing keys = do not translate (use raw value via ?? fallback)\n const TypeDictionary = {\n // Compatibility: \"nan\" -> \"NaN\" for display\n nan: \"NaN\",\n // All other type names omitted - they fall back to raw values via ?? operator\n };\n function getTypeName(type, input) {\n if (type === \"number\" && typeof input === \"number\" && !Number.isFinite(input)) {\n return String(input);\n }\n return TypeDictionary[type] ?? type;\n }\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = getTypeName(issue.expected);\n const receivedType = util.parsedType(issue.input);\n const received = getTypeName(receivedType, issue.input);\n return `Invalid input: expected ${expected}, received ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Invalid input: expected ${util.stringifyPrimitive(issue.values[0])}`;\n return `Invalid option: expected one of ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.exact ? \"exactly \" : issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Too big: expected ${issue.origin ?? \"value\"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elements\"}`;\n return `Too big: expected ${issue.origin ?? \"value\"} to be ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.exact ? \"exactly \" : issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `Invalid string: must start with \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `Invalid string: must end with \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Invalid string: must include \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Invalid string: must match pattern ${_issue.pattern}`;\n return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Invalid number: must be a multiple of ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Unrecognized key${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Invalid key in ${issue.origin}`;\n case \"invalid_union\":\n if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) {\n const opts = issue.options.map((o) => `'${o}'`).join(\" | \");\n return `Invalid discriminator value. Expected ${opts}`;\n }\n if (issue.inclusive === false) {\n return \"Invalid input: more than one option matched\";\n }\n return \"Invalid input\";\n case \"invalid_element\":\n return `Invalid value in ${issue.origin}`;\n default:\n return `Invalid input`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "var _a;\nexport const $output = /*@__PURE__*/ Symbol(\"ZodOutput\");\nexport const $input = /*@__PURE__*/ Symbol(\"ZodInput\");\nexport class $ZodRegistry {\n constructor() {\n this._map = new WeakMap();\n this._idmap = new Map();\n }\n add(schema, ..._meta) {\n const meta = _meta[0];\n this._map.set(schema, meta);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.set(meta.id, schema);\n }\n return this;\n }\n clear() {\n this._map = new WeakMap();\n this._idmap = new Map();\n return this;\n }\n remove(schema) {\n const meta = this._map.get(schema);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.delete(meta.id);\n }\n this._map.delete(schema);\n return this;\n }\n get(schema) {\n // return this._map.get(schema) as any;\n // inherit metadata\n const p = schema._zod.parent;\n if (p) {\n const pm = { ...(this.get(p) ?? {}) };\n delete pm.id; // do not inherit id\n const f = { ...pm, ...this._map.get(schema) };\n return Object.keys(f).length ? f : undefined;\n }\n return this._map.get(schema);\n }\n has(schema) {\n return this._map.has(schema);\n }\n}\n// registries\nexport function registry() {\n return new $ZodRegistry();\n}\n(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());\nexport const globalRegistry = globalThis.__zod_globalRegistry;\n", "import * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\nfunction snapshotChecks(def) {\n if (def.checks)\n def.checks = [...def.checks];\n return def;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n return new Class(snapshotChecks({ type: \"string\", ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n return new Class(snapshotChecks({ type: \"string\", coerce: true, ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _email(Class, params) {\n return new Class({\n type: \"string\",\n format: \"email\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _guid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"guid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v4\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v6\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv7(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v7\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _emoji(Class, params) {\n return new Class({\n type: \"string\",\n format: \"emoji\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nanoid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"nanoid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link _cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\n// @__NO_SIDE_EFFECTS__\nexport function _cuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid2(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid2\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ulid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ulid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _xid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"xid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ksuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ksuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mac(Class, params) {\n return new Class({\n type: \"string\",\n format: \"mac\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _e164(Class, params) {\n return new Class({\n type: \"string\",\n format: \"e164\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _creditCard(Class, params) {\n return new Class({\n type: \"string\",\n format: \"credit_card\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _iban(Class, params) {\n return new Class({\n type: \"string\",\n format: \"iban\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _jwt(Class, params) {\n return new Class({\n type: \"string\",\n format: \"jwt\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport const TimePrecision = {\n Any: null,\n Minute: -1,\n Second: 0,\n Millisecond: 3,\n Microsecond: 6,\n};\n// @__NO_SIDE_EFFECTS__\nexport function _isoDateTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"datetime\",\n check: \"string_format\",\n offset: false,\n local: false,\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDate(Class, params) {\n return new Class({\n type: \"string\",\n format: \"date\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"time\",\n check: \"string_format\",\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDuration(Class, params) {\n return new Class({\n type: \"string\",\n format: \"duration\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _number(Class, params) {\n return new Class(snapshotChecks({ type: \"number\", checks: [], ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n return new Class(snapshotChecks({ type: \"number\", coerce: true, checks: [], ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"safeint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float64(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"int32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"uint32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _boolean(Class, params) {\n return new Class({\n type: \"boolean\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBoolean(Class, params) {\n return new Class({\n type: \"boolean\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _bigint(Class, params) {\n return new Class({\n type: \"bigint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBigint(Class, params) {\n return new Class({\n type: \"bigint\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"int64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"uint64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _symbol(Class, params) {\n return new Class({\n type: \"symbol\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _undefined(Class, params) {\n return new Class({\n type: \"undefined\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _null(Class, params) {\n return new Class({\n type: \"null\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _any(Class) {\n return new Class({\n type: \"any\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _unknown(Class) {\n return new Class({\n type: \"unknown\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _never(Class, params) {\n return new Class({\n type: \"never\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _void(Class, params) {\n return new Class({\n type: \"void\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _date(Class, params) {\n return new Class({\n type: \"date\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedDate(Class, params) {\n return new Class({\n type: \"date\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nan(Class, params) {\n return new Class({\n type: \"nan\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lt(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lte(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.lte()` instead. */\n_lte as _max, };\n// @__NO_SIDE_EFFECTS__\nexport function _gt(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _gte(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.gte()` instead. */\n_gte as _min, };\n// @__NO_SIDE_EFFECTS__\nexport function _positive(params) {\n return _gt(0, params);\n}\n// negative\n// @__NO_SIDE_EFFECTS__\nexport function _negative(params) {\n return _lt(0, params);\n}\n// nonpositive\n// @__NO_SIDE_EFFECTS__\nexport function _nonpositive(params) {\n return _lte(0, params);\n}\n// nonnegative\n// @__NO_SIDE_EFFECTS__\nexport function _nonnegative(params) {\n return _gte(0, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function _multipleOf(value, params) {\n return new checks.$ZodCheckMultipleOf({\n check: \"multiple_of\",\n ...util.normalizeParams(params),\n value,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxSize(maximum, params) {\n return new checks.$ZodCheckMaxSize({\n check: \"max_size\",\n ...util.normalizeParams(params),\n maximum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minSize(minimum, params) {\n return new checks.$ZodCheckMinSize({\n check: \"min_size\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _size(size, params) {\n return new checks.$ZodCheckSizeEquals({\n check: \"size_equals\",\n ...util.normalizeParams(params),\n size,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxLength(maximum, params) {\n const ch = new checks.$ZodCheckMaxLength({\n check: \"max_length\",\n ...util.normalizeParams(params),\n maximum,\n });\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minLength(minimum, params) {\n return new checks.$ZodCheckMinLength({\n check: \"min_length\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _length(length, params) {\n return new checks.$ZodCheckLengthEquals({\n check: \"length_equals\",\n ...util.normalizeParams(params),\n length,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _regex(pattern, params) {\n return new checks.$ZodCheckRegex({\n check: \"string_format\",\n format: \"regex\",\n ...util.normalizeParams(params),\n pattern,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lowercase(params) {\n return new checks.$ZodCheckLowerCase({\n check: \"string_format\",\n format: \"lowercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uppercase(params) {\n return new checks.$ZodCheckUpperCase({\n check: \"string_format\",\n format: \"uppercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _includes(includes, params) {\n return new checks.$ZodCheckIncludes({\n check: \"string_format\",\n format: \"includes\",\n ...util.normalizeParams(params),\n includes,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _startsWith(prefix, params) {\n return new checks.$ZodCheckStartsWith({\n check: \"string_format\",\n format: \"starts_with\",\n ...util.normalizeParams(params),\n prefix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _endsWith(suffix, params) {\n return new checks.$ZodCheckEndsWith({\n check: \"string_format\",\n format: \"ends_with\",\n ...util.normalizeParams(params),\n suffix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _property(property, schema, params) {\n return new checks.$ZodCheckProperty({\n check: \"property\",\n property,\n schema,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _properties(shape, params) {\n return new checks.$ZodCheckProperties({\n check: \"properties\",\n shape,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mime(types, params) {\n return new checks.$ZodCheckMimeType({\n check: \"mime_type\",\n mime: types,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _overwrite(tx) {\n return new checks.$ZodCheckOverwrite({\n check: \"overwrite\",\n tx,\n });\n}\n// normalize\n// @__NO_SIDE_EFFECTS__\nexport function _normalize(form) {\n return _overwrite((input) => input.normalize(form));\n}\n// trim\n// @__NO_SIDE_EFFECTS__\nexport function _trim() {\n return _overwrite((input) => input.trim());\n}\n// toLowerCase\n// @__NO_SIDE_EFFECTS__\nexport function _toLowerCase() {\n return _overwrite((input) => input.toLowerCase());\n}\n// toUpperCase\n// @__NO_SIDE_EFFECTS__\nexport function _toUpperCase() {\n return _overwrite((input) => input.toUpperCase());\n}\n// slugify\n// @__NO_SIDE_EFFECTS__\nexport function _slugify() {\n return _overwrite((input) => util.slugify(input));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _array(Class, element, params) {\n return new Class({\n type: \"array\",\n element,\n // get element() {\n // return element;\n // },\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _union(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n ...util.normalizeParams(params),\n });\n}\nexport function _xor(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _discriminatedUnion(Class, discriminator, options, params) {\n return new Class({\n type: \"union\",\n options: options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _intersection(Class, left, right) {\n return new Class({\n type: \"intersection\",\n left,\n right,\n });\n}\n// export function _tuple(\n// Class: util.SchemaClass<schemas.$ZodTuple>,\n// items: [],\n// params?: string | $ZodTupleParams\n// ): schemas.$ZodTuple<[], null>;\n// @__NO_SIDE_EFFECTS__\nexport function _tuple(Class, items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof schemas.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new Class({\n type: \"tuple\",\n items,\n rest,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _record(Class, keyType, valueType, params) {\n return new Class({\n type: \"record\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _map(Class, keyType, valueType, params) {\n return new Class({\n type: \"map\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _set(Class, valueType, params) {\n return new Class({\n type: \"set\",\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _enum(Class, values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n // if (Array.isArray(values)) {\n // for (const value of values) {\n // entries[value] = value;\n // }\n // } else {\n // Object.assign(entries, values);\n // }\n // const entries: util.EnumLike = {};\n // for (const val of values) {\n // entries[val] = val;\n // }\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function _nativeEnum(Class, entries, params) {\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _literal(Class, value, params) {\n return new Class({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _file(Class, params) {\n return new Class({\n type: \"file\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _transform(Class, fn) {\n return new Class({\n type: \"transform\",\n transform: fn,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _optional(Class, innerType) {\n return new Class({\n type: \"optional\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nullable(Class, innerType) {\n return new Class({\n type: \"nullable\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _default(Class, innerType, defaultValue) {\n return new Class({\n type: \"default\",\n innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nonoptional(Class, innerType, params) {\n return new Class({\n type: \"nonoptional\",\n innerType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _success(Class, innerType) {\n return new Class({\n type: \"success\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _catch(Class, innerType, catchValue) {\n return new Class({\n type: \"catch\",\n innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : util.constantCatch(catchValue)),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _pipe(Class, in_, out) {\n return new Class({\n type: \"pipe\",\n in: in_,\n out,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _readonly(Class, innerType) {\n return new Class({\n type: \"readonly\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _templateLiteral(Class, parts, params) {\n return new Class({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lazy(Class, getter) {\n return new Class({\n type: \"lazy\",\n getter,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _promise(Class, innerType) {\n return new Class({\n type: \"promise\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _custom(Class, fn, _params) {\n const norm = util.normalizeParams(_params);\n norm.abort ?? (norm.abort = true); // default to abort:false\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...norm,\n });\n return schema;\n}\n// same as _custom but defaults to abort:false\n// @__NO_SIDE_EFFECTS__\nexport function _refine(Class, fn, _params) {\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...util.normalizeParams(_params),\n });\n return schema;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _superRefine(fn, params) {\n const ch = _check((payload) => {\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, ch._zod.def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n if (!(\"input\" in _issue))\n _issue.input = payload.value;\n _issue.inst ?? (_issue.inst = ch);\n _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...\n payload.issues.push(util.issue(_issue));\n }\n };\n return fn(payload.value, payload);\n }, params);\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _check(fn, params) {\n const ch = new checks.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function describe(description) {\n const ch = new checks.$ZodCheck({ check: \"describe\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, description });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function meta(metadata) {\n const ch = new checks.$ZodCheck({ check: \"meta\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, ...metadata });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringbool(Classes, _params) {\n const params = util.normalizeParams(_params);\n let truthyArray = params.truthy ?? [\"true\", \"1\", \"yes\", \"on\", \"y\", \"enabled\"];\n let falsyArray = params.falsy ?? [\"false\", \"0\", \"no\", \"off\", \"n\", \"disabled\"];\n if (params.case !== \"sensitive\") {\n truthyArray = truthyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n falsyArray = falsyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n }\n const truthySet = new Set(truthyArray);\n const falsySet = new Set(falsyArray);\n const _Codec = Classes.Codec ?? schemas.$ZodCodec;\n const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;\n const _String = Classes.String ?? schemas.$ZodString;\n const stringSchema = new _String({ type: \"string\", error: params.error });\n const booleanSchema = new _Boolean({ type: \"boolean\", error: params.error });\n const codec = new _Codec({\n type: \"pipe\",\n in: stringSchema,\n out: booleanSchema,\n transform: ((input, payload) => {\n let data = input;\n if (params.case !== \"sensitive\")\n data = data.toLowerCase();\n if (truthySet.has(data)) {\n return true;\n }\n else if (falsySet.has(data)) {\n return false;\n }\n else {\n payload.issues.push({\n code: \"invalid_value\",\n expected: \"stringbool\",\n values: [...truthySet, ...falsySet],\n input: payload.value,\n inst: codec,\n continue: false,\n });\n return {};\n }\n }),\n reverseTransform: ((input, _payload) => {\n if (input === true) {\n return truthyArray[0] || \"true\";\n }\n else {\n return falsyArray[0] || \"false\";\n }\n }),\n error: params.error,\n });\n codec._zod.bag.truthy = truthyArray;\n codec._zod.bag.falsy = falsyArray;\n codec._zod.bag.case = params.case ?? \"insensitive\";\n return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n const params = util.normalizeParams(_params);\n const def = {\n check: \"string_format\",\n type: \"string\",\n format,\n fn: typeof fnOrRegex === \"function\" ? fnOrRegex : (val) => fnOrRegex.test(val),\n ...params,\n };\n if (fnOrRegex instanceof RegExp) {\n def.pattern = fnOrRegex;\n }\n const inst = new Class(def);\n return inst;\n}\n", "import { globalRegistry } from \"./registries.js\";\nimport { assignProp } from \"./util.js\";\nfunction assignProps(target, ...sources) {\n for (const source of sources) {\n for (const key of Reflect.ownKeys(source)) {\n if (Object.prototype.propertyIsEnumerable.call(source, key)) {\n assignProp(target, key, source[key]);\n }\n }\n }\n return target;\n}\n// function initializeContext<T extends schemas.$ZodType>(inputs: JSONSchemaGeneratorParams<T>): ToJSONSchemaContext<T> {\n// return {\n// processor: inputs.processor,\n// metadataRegistry: inputs.metadata ?? globalRegistry,\n// target: inputs.target ?? \"draft-2020-12\",\n// unrepresentable: inputs.unrepresentable ?? \"throw\",\n// };\n// }\nexport function initializeContext(params) {\n // Normalize target: convert old non-hyphenated versions to hyphenated versions\n let target = params?.target ?? \"draft-2020-12\";\n if (target === \"draft-4\")\n target = \"draft-04\";\n if (target === \"draft-7\")\n target = \"draft-07\";\n return {\n processors: params.processors ?? {},\n metadataRegistry: params?.metadata ?? globalRegistry,\n target,\n unrepresentable: params?.unrepresentable ?? \"throw\",\n override: params?.override ?? (() => { }),\n io: params?.io ?? \"output\",\n counter: 0,\n seen: new Map(),\n sharedDefsExtractedFor: undefined,\n sharedEmitDoneFor: undefined,\n cycles: params?.cycles ?? \"ref\",\n reused: params?.reused ?? \"inline\",\n intersections: [],\n deferred: [],\n external: params?.external ?? undefined,\n };\n}\n/**\n * Applies the `unrepresentable` setting at a site that has no JSON Schema equivalent. Throws\n * `message` unless the setting (or the handler's return value) says otherwise. Returns `true` if a\n * custom JSON Schema was written into `json`, in which case the caller must not write its own.\n */\nexport function handleUnrepresentable(schema, ctx, json, params, message) {\n const result = typeof ctx.unrepresentable === \"function\"\n ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message })\n : ctx.unrepresentable;\n if (result === \"any\")\n return false;\n if (result === undefined || result === \"throw\")\n throw new Error(message);\n Object.assign(json, result);\n return true;\n}\n// never rename this back to `process`: bundler polyfills inject a top-level `const process` that a lexical declaration of the same name collides with (#6397)\nexport function processSchema(schema, ctx, _params = { path: [], schemaPath: [] }) {\n var _a;\n const def = schema._zod.def;\n // check for schema in seens\n const seen = ctx.seen.get(schema);\n if (seen) {\n seen.count++;\n // check if cycle\n const isCycle = _params.schemaPath.includes(schema);\n if (isCycle) {\n seen.cycle = _params.path;\n }\n return seen.schema;\n }\n // initialize\n const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };\n ctx.seen.set(schema, result);\n ctx.sharedDefsExtractedFor = undefined;\n ctx.sharedEmitDoneFor = undefined;\n // custom method overrides default behavior\n const overrideSchema = schema._zod.toJSONSchema?.();\n if (overrideSchema) {\n result.schema = overrideSchema;\n }\n else {\n const params = {\n ..._params,\n schemaPath: [..._params.schemaPath, schema],\n path: _params.path,\n };\n if (schema._zod.processJSONSchema) {\n schema._zod.processJSONSchema(ctx, result.schema, params);\n }\n else {\n const _json = result.schema;\n const processor = ctx.processors[def.type];\n if (!processor) {\n throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);\n }\n processor(schema, ctx, _json, params);\n }\n const parent = schema._zod.parent;\n if (parent) {\n // Also set ref if processor didn't (for inheritance)\n if (!result.ref)\n result.ref = parent;\n processSchema(parent, ctx, params);\n ctx.seen.get(parent).isParent = true;\n }\n }\n // metadata\n const meta = ctx.metadataRegistry.get(schema);\n if (meta)\n assignProps(result.schema, meta);\n if (ctx.io === \"input\" && isTransforming(schema)) {\n // examples/defaults only apply to output type of pipe\n delete result.schema.examples;\n delete result.schema.default;\n }\n // set prefault as default\n if (ctx.io === \"input\" && \"_prefault\" in result.schema)\n (_a = result.schema).default ?? (_a.default = result.schema._prefault);\n delete result.schema._prefault;\n // pulling fresh from ctx.seen in case it was overwritten\n const _result = ctx.seen.get(schema);\n return _result.schema;\n}\n/** @deprecated Renamed to `processSchema`. An export alias declares no binding, so it is safe to keep. */\nexport { processSchema as process };\n// Escape a reference token for use in a JSON Pointer fragment (RFC 6901): `~` becomes `~0` and `/` becomes `~1`. The `~` replacement must run first.\nfunction encodeJSONPointerSegment(segment) {\n return segment.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n}\nexport function extractDefs(ctx, schema\n// params: EmitParams\n) {\n // iterate over seen map;\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // With `external` set, every registered schema resolves through the external branch of `makeURI`, so the root branch below produces the same ref the external branch would — this pass is identical whichever schema it is called with, and only needs to run once.\n if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external)\n return;\n // Track ids to detect duplicates across different schemas\n const idToSchema = new Map();\n for (const entry of ctx.seen.entries()) {\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n const existing = idToSchema.get(id);\n if (existing && existing !== entry[0]) {\n throw new Error(`Duplicate schema id \"${id}\" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);\n }\n idToSchema.set(id, entry[0]);\n }\n }\n // returns a ref to the schema defId will be empty if the ref points to an external schema (or #)\n const makeURI = (entry) => {\n // comparing the seen objects because sometimes multiple schemas map to the same seen object. e.g. lazy\n // external is configured\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n if (ctx.external) {\n const externalId = ctx.external.registry.get(entry[0])?.id; // ?? \"__shared\";// `__schema${ctx.counter++}`;\n // check if schema is in the external registry\n const uriGenerator = ctx.external.uri ?? ((id) => id);\n if (externalId) {\n return { ref: uriGenerator(externalId) };\n }\n // otherwise, add to __shared\n const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;\n entry[1].defId = id; // set defId so it will be reused if needed\n return { defId: id, ref: `${uriGenerator(\"__shared\")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` };\n }\n const uriPrefix = `#`;\n const defUriPrefix = `${uriPrefix}/${defsSegment}/`;\n // an id-less root has nowhere to be extracted to, so it stays inline and self-references as `#`\n if (entry[1] === root && !entry[1].schema.id) {\n return { ref: uriPrefix };\n }\n // self-contained schema\n const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;\n return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) };\n };\n // stored cached version in `def` property remove all properties, set $ref\n const extractToDef = (entry) => {\n // if the schema is already a reference, do not extract it\n if (entry[1].schema.$ref) {\n return;\n }\n const seen = entry[1];\n const { ref, defId } = makeURI(entry);\n seen.def = { ...seen.schema };\n // defId won't be set if the schema is a reference to an external schema or if the schema is the root schema\n if (defId)\n seen.defId = defId;\n // wipe away all properties except $ref\n const schema = seen.schema;\n for (const key in schema) {\n delete schema[key];\n }\n schema.$ref = ref;\n };\n // throw on cycles\n // break cycles\n if (ctx.cycles === \"throw\") {\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.cycle) {\n throw new Error(\"Cycle detected: \" +\n `#/${seen.cycle?.join(\"/\")}/<root>` +\n '\\n\\nSet the `cycles` parameter to `\"ref\"` to resolve cyclical schemas with defs.');\n }\n }\n }\n // extract schemas into $defs\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n // convert root schema to # $ref\n if (schema === entry[0]) {\n extractToDef(entry); // this has special handling for the root schema\n continue;\n }\n // extract schemas that are in the external registry\n if (ctx.external) {\n const ext = ctx.external.registry.get(entry[0])?.id;\n if (schema !== entry[0] && ext) {\n extractToDef(entry);\n continue;\n }\n }\n // extract schemas with `id` meta\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n extractToDef(entry);\n continue;\n }\n // break cycles\n if (seen.cycle) {\n // any\n extractToDef(entry);\n continue;\n }\n // extract reused schemas\n if (seen.count > 1) {\n if (ctx.reused === \"ref\") {\n extractToDef(entry);\n }\n }\n }\n if (ctx.external)\n ctx.sharedDefsExtractedFor = ctx.external;\n}\n/** Rewrites `anyOf: [{type: \"a\"}, {type: \"b\"}]` to `type: [\"a\", \"b\"]`, which every JSON Schema draft treats as equivalent and most consumers render far better for the nullable case. Only branches that are a bare type assertion qualify — anything carrying a constraint, `$ref`, `const` or metadata is left alone. Runs after `flattenRef`, so a branch an override decorated or `$defs` extraction turned into a `$ref` is no longer bare and correctly stays in `anyOf`. `oneOf` is excluded: `integer` and `number` overlap, so \"exactly one\" and \"at least one\" are not the same there. OpenAPI 3.0 is excluded: its `type` must be a single string. */\nfunction compactTypeUnion(schema) {\n const options = schema.anyOf;\n if (!Array.isArray(options) || options.length === 0 || schema.type !== undefined)\n return;\n const types = [];\n for (const option of options) {\n if (!option || typeof option !== \"object\")\n return;\n // A branch that is itself a compactible union folds into this one — nested `anyOf` and a flat `type` array say the same thing. Compacting it first also makes the result independent of the order this pass walks the seen map in.\n compactTypeUnion(option);\n const keys = Object.keys(option);\n if (keys.length !== 1 || keys[0] !== \"type\")\n return;\n const type = option.type;\n for (const member of Array.isArray(type) ? type : [type]) {\n if (typeof member !== \"string\")\n return;\n if (!types.includes(member))\n types.push(member);\n }\n }\n delete schema.anyOf;\n // A `type` array must be non-empty and unique (metaschema); a single member is spelled as a bare string.\n schema.type = types.length === 1 ? types[0] : types;\n}\n/** Keywords `foldIntersection` knows how to combine. Anything else — `$ref`, `patternProperties`,\n * an annotation like `description` — makes a member unfoldable, so a constraint this does not\n * understand leaves the `allOf` alone instead of being silently dropped or misattributed. */\nconst FOLDABLE_KEYS = new Set([\"type\", \"properties\", \"required\", \"additionalProperties\"]);\nconst UNION_KEYS = [\"oneOf\", \"anyOf\"];\n/** A member's constraint on a key it does not declare itself. A `catchall` states one; `false`, an absent `additionalProperties`, and the empty schema a loose object emits state nothing. */\nfunction undeclaredConstraint(member) {\n const extra = member.additionalProperties;\n if (extra === undefined || extra === false || typeof extra !== \"object\" || extra === null)\n return null;\n return Object.keys(extra).length ? extra : null;\n}\n/** Combines object members into the single object they describe together, or returns `null` if any of them carries a keyword outside {@link FOLDABLE_KEYS}. */\nfunction foldObjects(members) {\n const objects = [];\n for (const member of members) {\n // A boolean subschema is legal JSON Schema and carries no keywords to fold.\n if (typeof member !== \"object\" || member.type !== \"object\")\n return null;\n for (const key in member) {\n if (!FOLDABLE_KEYS.has(key))\n return null;\n }\n objects.push(member);\n }\n const properties = {};\n const required = new Set();\n for (const object of objects) {\n for (const key in object.properties) {\n // `in` would report a `__proto__` key as already present via the prototype chain and skip it.\n if (Object.prototype.hasOwnProperty.call(properties, key))\n continue;\n // Every member constrains this key: the ones that declare it say how, and a `catchall` member constrains it too even though it does not name it. The key has to satisfy all of them, which is the same intersection one level down.\n const parts = [];\n for (const other of objects) {\n const part = other.properties?.[key] ?? undeclaredConstraint(other);\n if (part === null || part === undefined)\n continue;\n if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part)))\n parts.push(part);\n }\n const merged = parts.length === 1\n ? parts[0]\n : (foldObjects(parts) ?? { allOf: parts });\n assignProp(properties, key, merged);\n }\n for (const key of object.required ?? [])\n required.add(key);\n }\n const folded = { type: \"object\", properties };\n if (required.size)\n folded.required = [...required];\n // A key no member declares is rejected only when every member rejects it, so the fold is closed only when every member is. Otherwise it carries whatever the `catchall` members demand of such a key.\n if (objects.every((object) => object.additionalProperties === false)) {\n folded.additionalProperties = false;\n }\n else {\n const constraints = [];\n for (const object of objects) {\n const constraint = undeclaredConstraint(object);\n if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint)))\n constraints.push(constraint);\n }\n if (constraints.length === 1)\n folded.additionalProperties = constraints[0];\n else if (constraints.length > 1)\n folded.additionalProperties = { allOf: constraints };\n }\n return folded;\n}\n/** `additionalProperties` in an `allOf` member sees only that member's own `properties`, so two\n * closed object members reject each other's keys and the schema validates nothing. Zod's parser\n * pools the key sets instead — `handleIntersectionResults` reports a key as unrecognized only when\n * *every* side rejects it — so the emitted schema has to pool them too, and folding the members\n * into one object is the encoding that says so on every target.\n *\n * This runs from `finalize`, after `extractDefs`, which is what keeps it clear of the `$ref`\n * machinery: a member extracted into `$defs` is already a `$ref` by now and declines to fold, so it\n * keeps its reference and its own closedness rather than being inlined as a stale copy. */\nfunction foldIntersection(json) {\n const allOf = json.allOf;\n if (!Array.isArray(allOf) || allOf.length < 2)\n return;\n // An `override` runs before this pass and may have written object keywords onto the intersection itself. Those are deliberate, so decline rather than overwrite them.\n for (const key of FOLDABLE_KEYS)\n if (key in json)\n return;\n // An intersection distributes over a union: `A & (X | Y)` is `(A & X) | (A & Y)`. Only the first union is distributed over; a second one stays among the members every branch folds against, where it fails the object check and declines the whole intersection rather than multiplying out.\n const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k])));\n let folded = null;\n if (!unions.length) {\n folded = foldObjects(allOf);\n }\n else {\n const union = unions[0];\n const keyword = UNION_KEYS.find((k) => Array.isArray(union[k]));\n if (Object.keys(union).length !== 1)\n return;\n const rest = allOf.filter((m) => m !== union);\n const branches = union[keyword].map((branch) => foldObjects([...rest, branch]));\n if (branches.some((b) => !b))\n return;\n folded = { [keyword]: branches };\n }\n if (!folded)\n return;\n delete json.allOf;\n assignProps(json, folded);\n}\nexport function finalize(ctx, schema) {\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // flatten refs - inherit properties from parent schemas\n const flattenRef = (zodSchema) => {\n const seen = ctx.seen.get(zodSchema);\n // already processed\n if (seen.ref === null)\n return;\n const schema = seen.def ?? seen.schema;\n const _cached = { ...schema };\n const ref = seen.ref;\n seen.ref = null; // prevent infinite recursion\n if (ref) {\n flattenRef(ref);\n const refSeen = ctx.seen.get(ref);\n const refSchema = refSeen.schema;\n // merge referenced schema into current\n if (refSchema.$ref && (ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\")) {\n // older drafts can't combine $ref with other properties\n schema.allOf = schema.allOf ?? [];\n schema.allOf.push(refSchema);\n }\n else {\n assignProps(schema, refSchema);\n }\n // restore child's own properties (child wins)\n assignProps(schema, _cached);\n const isParentRef = zodSchema._zod.parent === ref;\n // For parent chain, child is a refinement - remove parent-only properties\n if (isParentRef) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (!(key in _cached)) {\n delete schema[key];\n }\n }\n }\n // When ref was extracted to $defs, remove properties that match the definition\n if (refSchema.$ref && refSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n // If parent was extracted (has $ref), propagate $ref to this schema. This handles cases like: readonly().meta({id}).describe() where processor sets ref to innerType but parent should be referenced\n const parent = zodSchema._zod.parent;\n if (parent && parent !== ref) {\n // Ensure parent is processed first so its def has inherited properties\n flattenRef(parent);\n const parentSeen = ctx.seen.get(parent);\n if (parentSeen?.schema.$ref) {\n schema.$ref = parentSeen.schema.$ref;\n // De-duplicate with parent's definition\n if (parentSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n }\n // execute overrides\n ctx.override({\n zodSchema: zodSchema,\n jsonSchema: schema,\n path: seen.path ?? [],\n });\n };\n // Flattening walks the whole map and clears each `ref` as it goes, so a second call over the same map is a no-op scan. Skip it outright once it has run for a registry conversion.\n if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {\n for (const entry of [...ctx.seen.entries()].reverse()) {\n flattenRef(entry[0]);\n }\n if (ctx.target !== \"openapi-3.0\") {\n for (const entry of ctx.seen.entries()) {\n compactTypeUnion(entry[1].def ?? entry[1].schema);\n }\n }\n for (const rewrite of ctx.deferred)\n rewrite();\n // After flattening, every member that was extracted is a `$ref`, so the fold sees the final shape. A schema that inherits an intersection — through `z.lazy`, or any `ref` chain — holds the same `allOf` array, so fold by array identity to catch every copy.\n if (ctx.intersections.length) {\n const carriers = new Map();\n for (const seen of ctx.seen.values()) {\n for (const json of [seen.schema, seen.def]) {\n const allOf = json?.allOf;\n if (!Array.isArray(allOf))\n continue;\n const existing = carriers.get(allOf);\n if (existing)\n existing.push(json);\n else\n carriers.set(allOf, [json]);\n }\n }\n for (const allOf of ctx.intersections) {\n for (const json of carriers.get(allOf) ?? [])\n foldIntersection(json);\n }\n }\n }\n const result = {};\n if (ctx.target === \"draft-2020-12\") {\n result.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n }\n else if (ctx.target === \"draft-07\") {\n result.$schema = \"http://json-schema.org/draft-07/schema#\";\n }\n else if (ctx.target === \"draft-04\") {\n result.$schema = \"http://json-schema.org/draft-04/schema#\";\n }\n else if (ctx.target === \"openapi-3.0\") {\n // OpenAPI 3.0 schema objects should not include a $schema property\n }\n else {\n // Arbitrary string values are allowed but won't have a $schema property set\n }\n if (ctx.external?.uri) {\n const id = ctx.external.registry.get(schema)?.id;\n if (!id)\n throw new Error(\"Schema is missing an `id` property\");\n result.$id = ctx.external.uri(id);\n }\n // when the root was extracted into $defs, `root.schema` is the `$ref` wrapper and `root.def` is the body that now lives under $defs\n assignProps(result, root.defId ? root.schema : (root.def ?? root.schema));\n // The `id` in `.meta()` is a Zod-specific registration tag used to extract schemas into $defs — it is not user-facing JSON Schema metadata. Strip it from the output body where it would otherwise leak. The id is preserved implicitly via the $defs key (and via $ref paths).\n const rootMetaId = ctx.metadataRegistry.get(schema)?.id;\n if (rootMetaId !== undefined && result.id === rootMetaId)\n delete result.id;\n // build defs object. With `external`, `defs` is the shared object every schema writes into, so the same entries are reassigned on every call. Without it, `defs` is fresh per call and must be rebuilt.\n const defs = ctx.external?.defs ?? {};\n if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.def && seen.defId) {\n if (seen.def.id === seen.defId)\n delete seen.def.id;\n assignProp(defs, seen.defId, seen.def);\n }\n }\n }\n if (ctx.external)\n ctx.sharedEmitDoneFor = ctx.external;\n // set definitions in result\n if (ctx.external) {\n }\n else {\n if (Object.keys(defs).length > 0) {\n if (ctx.target === \"draft-2020-12\") {\n result.$defs = defs;\n }\n else {\n result.definitions = defs;\n }\n }\n }\n try {\n // this \"finalizes\" this schema and ensures all cycles are removed each call to finalize() is functionally independent though the seen map is shared\n const finalized = JSON.parse(JSON.stringify(result));\n Object.defineProperty(finalized, \"~standard\", {\n value: {\n ...schema[\"~standard\"],\n jsonSchema: {\n input: createStandardJSONSchemaMethod(schema, \"input\", ctx.processors),\n output: createStandardJSONSchemaMethod(schema, \"output\", ctx.processors),\n },\n },\n enumerable: false,\n writable: false,\n });\n return finalized;\n }\n catch (_err) {\n throw new Error(\"Error converting schema to JSON.\");\n }\n}\nfunction isTransforming(_schema, _ctx) {\n const ctx = _ctx ?? { seen: new Set() };\n if (ctx.seen.has(_schema))\n return false;\n ctx.seen.add(_schema);\n const def = _schema._zod.def;\n if (def.type === \"transform\")\n return true;\n if (def.type === \"array\")\n return isTransforming(def.element, ctx);\n if (def.type === \"set\")\n return isTransforming(def.valueType, ctx);\n if (def.type === \"lazy\")\n return isTransforming(def.getter(), ctx);\n if (def.type === \"promise\" ||\n def.type === \"optional\" ||\n def.type === \"nonoptional\" ||\n def.type === \"nullable\" ||\n def.type === \"readonly\" ||\n def.type === \"default\" ||\n def.type === \"prefault\" ||\n def.type === \"catch\") {\n return isTransforming(def.innerType, ctx);\n }\n if (def.type === \"intersection\") {\n return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);\n }\n if (def.type === \"record\" || def.type === \"map\") {\n return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);\n }\n if (def.type === \"pipe\") {\n if (_schema._zod.traits.has(\"$ZodCodec\"))\n return true;\n return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);\n }\n if (def.type === \"object\") {\n for (const key in def.shape) {\n if (isTransforming(def.shape[key], ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"union\") {\n for (const option of def.options) {\n if (isTransforming(option, ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"tuple\") {\n for (const item of def.items) {\n if (isTransforming(item, ctx))\n return true;\n }\n if (def.rest && isTransforming(def.rest, ctx))\n return true;\n return false;\n }\n return false;\n}\n/**\n * Creates a toJSONSchema method for a schema instance.\n * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.\n */\nexport const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {\n const ctx = initializeContext({ ...params, processors });\n processSchema(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\nexport const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {\n const { libraryOptions, target } = params ?? {};\n const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors });\n processSchema(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\n", "import * as regexes from \"./regexes.js\";\nimport { base64Charset, base64urlCharset } from \"./schemas.js\";\nimport { extractDefs, finalize, handleUnrepresentable, initializeContext, processSchema, } from \"./to-json-schema.js\";\nimport { BIGINT_FORMAT_RANGES, NUMBER_FORMAT_RANGES, assignProp, getEnumValues } from \"./util.js\";\nconst narrowMin = (agg, key, value) => {\n if (agg[key] === undefined || value > agg[key])\n agg[key] = value;\n};\nconst narrowMax = (agg, key, value) => {\n if (agg[key] === undefined || value < agg[key])\n agg[key] = value;\n};\nconst narrowBoth = (agg, value) => {\n narrowMin(agg, \"minimum\", value);\n narrowMax(agg, \"maximum\", value);\n};\nconst addDivisor = (agg, value) => {\n agg.multipleOf ?? (agg.multipleOf = []);\n if (!agg.multipleOf.includes(value))\n agg.multipleOf.push(value);\n};\nconst addPattern = (agg, pattern) => {\n agg.patterns ?? (agg.patterns = new Set());\n agg.patterns.add(pattern);\n};\nconst intersectMime = (agg, mime) => {\n agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime];\n};\n// last-wins, matching the bag's historical write order; the flag keeps an integer format from being lost to a later float one\nconst setFormat = (agg, format) => {\n agg.format = format;\n if (format.includes(\"int\"))\n agg.isInt = true;\n};\nconst minContributor = (agg, def) => narrowMin(agg, \"minimum\", def.minimum);\nconst maxContributor = (agg, def) => narrowMax(agg, \"maximum\", def.maximum);\nconst formatContributor = (ranges) => (agg, def) => {\n setFormat(agg, def.format);\n const [minimum, maximum] = ranges[def.format];\n narrowMin(agg, \"minimum\", minimum);\n narrowMax(agg, \"maximum\", maximum);\n};\nconst contributors = {\n greater_than: (agg, def) => narrowMin(agg, def.inclusive ? \"minimum\" : \"exclusiveMinimum\", def.value),\n less_than: (agg, def) => narrowMax(agg, def.inclusive ? \"maximum\" : \"exclusiveMaximum\", def.value),\n multiple_of: (agg, def) => addDivisor(agg, def.value),\n number_format: formatContributor(NUMBER_FORMAT_RANGES),\n bigint_format: formatContributor(BIGINT_FORMAT_RANGES),\n min_length: minContributor,\n max_length: maxContributor,\n length_equals: (agg, def) => narrowBoth(agg, def.length),\n min_size: minContributor,\n max_size: maxContributor,\n size_equals: (agg, def) => narrowBoth(agg, def.size),\n string_format: (agg, def) => {\n setFormat(agg, def.format);\n if (def.pattern)\n addPattern(agg, def.pattern);\n if (def.format === \"base64\" || def.format === \"base64url\")\n agg.contentEncoding = def.format;\n if (def.local || def.precision === -1)\n agg.laxFormat = true;\n },\n mime_type: (agg, def) => intersectMime(agg, def.mime),\n};\nexport function aggregateChecks(schema) {\n const agg = {};\n const def = schema._zod.def;\n // a format schema is its own first check, same rule as $ZodType init\n const list = schema._zod.traits.has(\"$ZodCheck\")\n ? [schema, ...(def.checks ?? [])]\n : (def.checks ?? []);\n for (const ch of list)\n contributors[ch._zod.def.check]?.(agg, ch._zod.def);\n // reconcile with the bag so third-party onattach contributions still land; first-party residue is never tighter than the fold, so merging it back is idempotent for one and additive for the other\n const bag = schema._zod.bag;\n if (bag.minimum !== undefined)\n narrowMin(agg, \"minimum\", bag.minimum);\n if (bag.exclusiveMinimum !== undefined)\n narrowMin(agg, \"exclusiveMinimum\", bag.exclusiveMinimum);\n if (bag.maximum !== undefined)\n narrowMax(agg, \"maximum\", bag.maximum);\n if (bag.exclusiveMaximum !== undefined)\n narrowMax(agg, \"exclusiveMaximum\", bag.exclusiveMaximum);\n if (bag.multipleOf !== undefined)\n addDivisor(agg, bag.multipleOf);\n if (bag.format !== undefined) {\n agg.format ?? (agg.format = bag.format);\n if (bag.format.includes(\"int\"))\n agg.isInt = true;\n }\n if (bag.mime)\n intersectMime(agg, bag.mime);\n for (const pattern of bag.patterns ?? [])\n addPattern(agg, pattern);\n return agg;\n}\nconst formatMap = {\n guid: \"uuid\",\n url: \"uri\",\n datetime: \"date-time\",\n json_string: \"json-string\",\n regex: \"\", // do not set\n};\n// ==================== SIMPLE TYPE PROCESSORS ====================\n// the runtime patterns are lax so parse paths never overflow the regex stack; the emitted schema swaps in the exact block forms, which zod itself never executes\nconst exactPatterns = new Map([\n [base64Charset, regexes.base64],\n [base64urlCharset, regexes.base64url],\n]);\nconst exactPattern = (p) => exactPatterns.get(p) ?? p;\nexport const stringProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n json.type = \"string\";\n const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema);\n if (typeof minimum === \"number\")\n json.minLength = minimum;\n if (typeof maximum === \"number\")\n json.maxLength = maximum;\n // custom pattern overrides format\n if (format) {\n json.format = formatMap[format] ?? format;\n if (json.format === \"\")\n delete json.format; // empty format is not valid\n // `z.iso.time()` is never full-time, and `laxFormat` carries the datetime shapes that also accept what their keyword forbids\n if (format === \"time\" || laxFormat) {\n delete json.format;\n }\n }\n if (contentEncoding)\n json.contentEncoding = contentEncoding;\n if (patterns && patterns.size > 0) {\n const patternList = [...patterns].map(exactPattern);\n if (patternList.length === 1)\n json.pattern = patternList[0].source;\n else if (patternList.length > 1) {\n json.allOf = [\n ...patternList.map((regex) => ({\n ...(ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\"\n ? { type: \"string\" }\n : {}),\n pattern: regex.source,\n })),\n ];\n }\n }\n};\nexport const numberProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const { minimum, maximum, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema);\n json.type = isInt ? \"integer\" : \"number\";\n // when both minimum and exclusiveMinimum exist, pick the more restrictive one\n const exMin = typeof exclusiveMinimum === \"number\" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);\n const exMax = typeof exclusiveMaximum === \"number\" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);\n const legacy = ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\";\n if (exMin) {\n if (legacy) {\n json.minimum = exclusiveMinimum;\n json.exclusiveMinimum = true;\n }\n else {\n json.exclusiveMinimum = exclusiveMinimum;\n }\n }\n else if (typeof minimum === \"number\") {\n json.minimum = minimum;\n }\n if (exMax) {\n if (legacy) {\n json.maximum = exclusiveMaximum;\n json.exclusiveMaximum = true;\n }\n else {\n json.exclusiveMaximum = exclusiveMaximum;\n }\n }\n else if (typeof maximum === \"number\") {\n json.maximum = maximum;\n }\n if (multipleOf) {\n // JSON Schema requires a divisor strictly greater than zero, and a non-finite one does not survive JSON at all. A negative divisor accepts exactly what its absolute value accepts, so it still maps; zero, NaN and Infinity have no keyword form.\n const divisors = new Set();\n for (const divisor of multipleOf) {\n if (Number.isFinite(divisor) && divisor !== 0)\n divisors.add(Math.abs(divisor));\n else\n handleUnrepresentable(schema, ctx, json, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`);\n }\n // chained divisors are a conjunction the keyword cannot carry alone, so extras ride an allOf, same as stacked patterns\n const [first, ...rest] = divisors;\n if (first !== undefined)\n json.multipleOf = first;\n if (rest.length)\n json.allOf = [...(json.allOf ?? []), ...rest.map((m) => ({ multipleOf: m }))];\n }\n};\nexport const booleanProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const bigintProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"BigInt cannot be represented in JSON Schema\");\n};\nexport const symbolProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Symbols cannot be represented in JSON Schema\");\n};\nexport const nullProcessor = (_schema, ctx, json, _params) => {\n if (ctx.target === \"openapi-3.0\") {\n json.type = \"string\";\n json.nullable = true;\n json.enum = [null];\n }\n else {\n json.type = \"null\";\n }\n};\nexport const undefinedProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Undefined cannot be represented in JSON Schema\");\n};\nexport const voidProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Void cannot be represented in JSON Schema\");\n};\nexport const neverProcessor = (_schema, _ctx, json, _params) => {\n json.not = {};\n};\nexport const anyProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const unknownProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const dateProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Date cannot be represented in JSON Schema\");\n};\nexport const enumProcessor = (schema, _ctx, json, _params) => {\n const def = schema._zod.def;\n const values = getEnumValues(def.entries);\n // an empty enum accepts nothing, same as z.never()\n if (values.length === 0) {\n json.not = {};\n return;\n }\n // Number enums can have both string and number values\n if (values.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (values.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n json.enum = values;\n};\nexport const literalProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n // a literal with no values accepts nothing, same as z.never()\n if (def.values.length === 0) {\n json.not = {};\n return;\n }\n const vals = [];\n for (const val of def.values) {\n if (val === undefined) {\n // a custom schema replaces the whole literal, so there is nothing left to accumulate\n if (handleUnrepresentable(schema, ctx, json, params, \"Literal `undefined` cannot be represented in JSON Schema\"))\n return;\n // otherwise do not add to vals\n }\n else if (typeof val === \"bigint\") {\n if (handleUnrepresentable(schema, ctx, json, params, \"BigInt literals cannot be represented in JSON Schema\"))\n return;\n vals.push(Number(val));\n }\n else {\n vals.push(val);\n }\n }\n if (vals.length === 0) {\n // do nothing (an undefined literal was stripped)\n }\n else if (vals.length === 1) {\n const val = vals[0];\n json.type = val === null ? \"null\" : typeof val;\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.enum = [val];\n }\n else {\n json.const = val;\n }\n }\n else {\n if (vals.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (vals.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n if (vals.every((v) => typeof v === \"boolean\"))\n json.type = \"boolean\";\n if (vals.every((v) => v === null))\n json.type = \"null\";\n json.enum = vals;\n }\n};\nexport const nanProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"NaN cannot be represented in JSON Schema\");\n};\nexport const templateLiteralProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const pattern = schema._zod.pattern;\n if (!pattern)\n throw new Error(\"Pattern not found in template literal\");\n _json.type = \"string\";\n _json.pattern = pattern.source;\n};\nexport const fileProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n _json.type = \"string\";\n _json.format = \"binary\";\n _json.contentEncoding = \"binary\";\n const { minimum, maximum, mime } = aggregateChecks(schema);\n if (minimum !== undefined)\n _json.minLength = minimum;\n if (maximum !== undefined)\n _json.maxLength = maximum;\n if (!mime)\n return;\n // an empty intersection means the mime checks share no value, so nothing passes at runtime; `anyOf` must be non-empty, so the false schema is `not: {}`\n if (mime.length === 0)\n _json.not = {};\n else if (mime.length === 1)\n _json.contentMediaType = mime[0];\n // only contentMediaType differs, so the shared props stay at the root\n else\n _json.anyOf = mime.map((m) => ({ contentMediaType: m }));\n};\nexport const successProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const customProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Custom types cannot be represented in JSON Schema\");\n};\nexport const functionProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Function types cannot be represented in JSON Schema\");\n};\nexport const transformProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Transforms cannot be represented in JSON Schema\");\n};\nexport const mapProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Map cannot be represented in JSON Schema\");\n};\nexport const setProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Set cannot be represented in JSON Schema\");\n};\n// ==================== COMPOSITE TYPE PROCESSORS ====================\nexport const arrayProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const { minimum, maximum } = aggregateChecks(schema);\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n json.type = \"array\";\n json.items = processSchema(def.element, ctx, {\n ...params,\n path: [...params.path, \"items\"],\n });\n};\n// Transform and catch set `optin = \"optional\"` at runtime so the parser lets them observe an\n// absent key, but their declared input type stays required. An input JSON Schema describes the\n// declared type, so resolve past them to the schema that actually carries the optionality.\n// Used by both `objectProcessor` (for `required`) and `tupleProcessor` (for `minItems`); see\n// wiki/optionality.md, \"The JSON Schema emitter reads the *static* value\".\nfunction inputOptin(schema) {\n const def = schema._zod.def;\n if (def.type === \"pipe\" && def.in._zod.traits.has(\"$ZodTransform\")) {\n return inputOptin(def.out);\n }\n if (def.type === \"catch\") {\n return inputOptin(def.innerType);\n }\n return schema._zod.optin;\n}\nexport const objectProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const shape = def.shape;\n // dropping it while still emitting `additionalProperties: false` would emit a schema that rejects data this one requires\n const symbolKeys = Object.getOwnPropertySymbols(shape);\n if (symbolKeys.length &&\n handleUnrepresentable(schema, ctx, json, params, \"Symbol keys cannot be represented in JSON Schema\")) {\n return;\n }\n json.type = \"object\";\n json.properties = {};\n for (const key in shape) {\n // assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter on the plain {} we build into\n assignProp(json.properties, key, processSchema(shape[key], ctx, {\n ...params,\n path: [...params.path, \"properties\", key],\n }));\n }\n // required keys\n const requiredKeys = [];\n for (const key of Object.keys(shape)) {\n const field = def.shape[key];\n if (ctx.io === \"input\" ? inputOptin(field) === undefined : field._zod.optout === undefined) {\n requiredKeys.push(key);\n }\n }\n if (requiredKeys.length > 0) {\n json.required = requiredKeys;\n }\n // catchall\n if (def.catchall?._zod.def.type === \"never\") {\n // strict\n json.additionalProperties = false;\n }\n else if (!def.catchall) {\n // regular\n if (ctx.io === \"output\")\n json.additionalProperties = false;\n }\n else if (def.catchall) {\n json.additionalProperties = processSchema(def.catchall, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n};\nexport const unionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches). This includes both z.xor() and discriminated unions\n const isExclusive = def.inclusive === false;\n const options = def.options.map((x, i) => processSchema(x, ctx, {\n ...params,\n path: [...params.path, isExclusive ? \"oneOf\" : \"anyOf\", i],\n }));\n if (isExclusive) {\n json.oneOf = options;\n }\n else {\n json.anyOf = options;\n }\n};\nexport const intersectionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const a = processSchema(def.left, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 0],\n });\n const b = processSchema(def.right, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 1],\n });\n const isSimpleIntersection = (val) => \"allOf\" in val && Object.keys(val).length === 1;\n const allOf = [\n ...(isSimpleIntersection(a) ? a.allOf : [a]),\n ...(isSimpleIntersection(b) ? b.allOf : [b]),\n ];\n json.allOf = allOf;\n // Recorded innermost first, so a nested intersection has already folded by the time this one is considered. The array is the handle rather than the schema, because a wrapper that inherits this schema shares the same array; `finalize` folds every object holding it. See `foldIntersection`.\n ctx.intersections.push(allOf);\n};\nexport const tupleProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"array\";\n const prefixPath = ctx.target === \"draft-2020-12\" ? \"prefixItems\" : \"items\";\n const restPath = ctx.target === \"draft-2020-12\" ? \"items\" : ctx.target === \"openapi-3.0\" ? \"items\" : \"additionalItems\";\n const prefixItems = def.items.map((x, i) => processSchema(x, ctx, {\n ...params,\n path: [...params.path, prefixPath, i],\n }));\n const rest = def.rest\n ? processSchema(def.rest, ctx, {\n ...params,\n path: [...params.path, restPath, ...(ctx.target === \"openapi-3.0\" ? [def.items.length] : [])],\n })\n : null;\n let minItems = def.items.length;\n while (minItems > 0) {\n const item = def.items[minItems - 1];\n const optional = ctx.io === \"input\" ? inputOptin(item) !== undefined : item._zod.optout === \"optional\";\n if (!optional)\n break;\n minItems--;\n }\n const maxItems = def.items.length;\n const isClosed = !def.rest;\n if (ctx.target === \"draft-2020-12\") {\n json.prefixItems = prefixItems;\n if (isClosed) {\n json.items = false;\n }\n else if (rest) {\n json.items = rest;\n }\n if (minItems > 0)\n json.minItems = minItems;\n if (isClosed)\n json.maxItems = maxItems;\n }\n else if (ctx.target === \"openapi-3.0\") {\n json.items = {\n anyOf: prefixItems,\n };\n if (rest) {\n json.items.anyOf.push(rest);\n }\n if (minItems > 0)\n json.minItems = minItems;\n if (isClosed)\n json.maxItems = maxItems;\n }\n else {\n json.items = prefixItems;\n if (isClosed) {\n json.additionalItems = false;\n }\n else if (rest) {\n json.additionalItems = rest;\n }\n if (minItems > 0)\n json.minItems = minItems;\n if (isClosed)\n json.maxItems = maxItems;\n }\n // explicit user-defined length checks take precedence\n const { minimum, maximum } = aggregateChecks(schema);\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n};\n/** JSON object keys are always strings, so a numeric record key schema is re-expressed over the\n * numeric-string form the record parser matches. Deferred to `finalize`, after the flatten: a key\n * behind a wrapper only carries its own `type` before then, and a union key only has its branches.\n *\n * A numeric bound cannot apply to a property name, so `minimum` and its siblings are dropped rather\n * than carried over: keeping them beside `type: \"string\"` reproduces the match-nothing schema this\n * exists to fix. A key that carries one therefore emits wider than the record parses — `z.record(z.number().min(5), V)`\n * accepts `\"3\"` — which is the deliberate trade, since throwing on it would reject an ordinary schema\n * outright. */\nfunction stringifyKeyNames(bySchema, json, visited) {\n // an extracted key that rewrites cannot go on sharing its definition — the string form a key position needs is not the number form every other reference wants — so it inlines. One that does not rewrite keeps the `$ref`.\n if (json.$ref) {\n // a recursive key holds its own reference inside its definition, so a node already on the path is left alone rather than resolved again\n if (visited.has(json))\n return json;\n visited.add(json);\n const def = bySchema.get(json)?.def;\n if (!def)\n return json;\n const inlined = stringifyKeyNames(bySchema, def, visited);\n return inlined === def ? json : inlined;\n }\n for (const keyword of [\"anyOf\", \"oneOf\"]) {\n const branches = json[keyword];\n if (!Array.isArray(branches))\n continue;\n const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited));\n // rebuilding regardless would detach a key that had nothing to re-express, dropping its `$ref` and leaking the internal `id`\n if (mapped.some((branch, i) => branch !== branches[i]))\n json = { ...json, [keyword]: mapped };\n }\n // a member that already admits a string leaves the key unconstrained, so the node's own type re-expresses only when every member is numeric\n const types = Array.isArray(json.type) ? json.type : [json.type];\n const numericType = !types.includes(\"string\") && types.some((t) => t === \"number\" || t === \"integer\");\n // a heterogeneous key carries no type at all, so its numeric members are caught here instead\n const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined);\n if (!numericType && !values?.some((v) => typeof v === \"number\"))\n return json;\n const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json;\n if (rest.enum)\n rest.enum = rest.enum.map((v) => (typeof v === \"number\" ? String(v) : v));\n else if (typeof rest.const === \"number\")\n rest.const = String(rest.const);\n // a heterogeneous key keeps its absent type: the stringified members already say what a key may be\n if (!numericType)\n return rest;\n rest.type = \"string\";\n if (!values)\n rest.pattern = (types.includes(\"number\") ? regexes.number : regexes.integer).source;\n return rest;\n}\n/** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */\nconst pendingRecords = new WeakMap();\nfunction rewriteKeyNames(ctx) {\n // an extracted key is resolved by the object `extractToDef` left in its place, so the map is built once rather than searched per reference. `_zod.toJSONSchema` can hand the same object to two schemas, so the first entry carrying a body wins, as a search would have found it.\n const bySchema = new Map();\n for (const entry of ctx.seen.values()) {\n if (entry.def && !bySchema.has(entry.schema))\n bySchema.set(entry.schema, entry);\n }\n const rewrites = new Map();\n for (const record of pendingRecords.get(ctx) ?? []) {\n const seen = ctx.seen.get(record);\n const names = (seen?.def ?? seen?.schema)?.propertyNames;\n if (!names || names === true || rewrites.has(names))\n continue;\n const rewritten = stringifyKeyNames(bySchema, names, new Set());\n if (rewritten !== names)\n rewrites.set(names, rewritten);\n }\n if (!rewrites.size)\n return;\n // the flatten has already copied each record's own properties onto every wrapper by reference, and an extracted body is another such copy, so every carrier holding a rewritten key is updated together\n for (const entry of ctx.seen.values()) {\n for (const carrier of [entry.schema, entry.def]) {\n const rewritten = carrier && rewrites.get(carrier.propertyNames);\n if (rewritten)\n carrier.propertyNames = rewritten;\n }\n }\n}\nexport const recordProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n // For looseRecord with regex patterns, use patternProperties. This correctly represents \"only validate keys matching the pattern\" semantics and composes well with allOf (intersections)\n const keyType = def.keyType;\n const patterns = aggregateChecks(keyType).patterns;\n if (def.mode === \"loose\" && patterns && patterns.size > 0) {\n // Use patternProperties for looseRecord with regex patterns\n const valueSchema = processSchema(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"patternProperties\", \"*\"],\n });\n json.patternProperties = {};\n for (const pattern of patterns) {\n assignProp(json.patternProperties, exactPattern(pattern).source, valueSchema);\n }\n }\n else {\n // Default behavior: use propertyNames + additionalProperties\n if (ctx.target === \"draft-07\" || ctx.target === \"draft-2020-12\") {\n json.propertyNames = processSchema(def.keyType, ctx, {\n ...params,\n path: [...params.path, \"propertyNames\"],\n });\n let pending = pendingRecords.get(ctx);\n if (!pending) {\n pending = [];\n pendingRecords.set(ctx, pending);\n ctx.deferred.push(() => rewriteKeyNames(ctx));\n }\n pending.push(schema);\n }\n json.additionalProperties = processSchema(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n // Add required for keys with discrete values (enum, literal, etc.)\n const keyValues = keyType._zod.values;\n // Every key shares one value schema, so an optional-in value makes the whole key set omittable on input. Output keeps them: the exhaustive branch assigns every key, even one whose value came back undefined.\n const omittableOnInput = ctx.io === \"input\" && inputOptin(def.valueType) !== undefined;\n if (keyValues && !def.partial && !omittableOnInput) {\n const validKeyValues = [...keyValues].filter((v) => typeof v === \"string\" || typeof v === \"number\");\n if (validKeyValues.length > 0) {\n json.required = validKeyValues.map(String);\n }\n }\n};\nexport const nullableProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const inner = processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n if (ctx.target === \"openapi-3.0\") {\n seen.ref = def.innerType;\n json.nullable = true;\n }\n else {\n json.anyOf = [inner, { type: \"null\" }];\n }\n};\nexport const nonoptionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\n/** Round-trips a default value through JSON so the emitted schema is guaranteed to be valid JSON.\n * A BigInt has no reliable encoding, so it goes through `unrepresentable` like any other\n * unrepresentable value. Returns a sentinel when the caller must not write a default of its own. */\nconst UNREPRESENTABLE_DEFAULT = Symbol();\nfunction serializeDefaultValue(value, schema, ctx, json, params) {\n let unrepresentable = false;\n const serialized = JSON.stringify(value, (_, val) => {\n if (typeof val !== \"bigint\")\n return val;\n unrepresentable = true;\n return null;\n });\n if (!unrepresentable)\n return JSON.parse(serialized);\n handleUnrepresentable(schema, ctx, json, params, \"BigInt defaults cannot be represented in JSON Schema\");\n return UNREPRESENTABLE_DEFAULT;\n}\nexport const defaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);\n if (value !== UNREPRESENTABLE_DEFAULT)\n json.default = value;\n};\nexport const prefaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n if (ctx.io !== \"input\")\n return;\n const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);\n if (value !== UNREPRESENTABLE_DEFAULT)\n json._prefault = value;\n};\nexport const catchProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n let catchValue;\n try {\n catchValue = def.catchValue(undefined);\n }\n catch {\n handleUnrepresentable(schema, ctx, json, params, \"Dynamic catch values are not supported in JSON Schema\");\n return;\n }\n json.default = catchValue;\n};\nexport const pipeProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n const inIsTransform = def.in._zod.traits.has(\"$ZodTransform\");\n const innerType = ctx.io === \"input\" ? (inIsTransform ? def.out : def.in) : def.out;\n processSchema(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\nexport const readonlyProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.readOnly = true;\n};\nexport const promiseProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const optionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const lazyProcessor = (schema, ctx, _json, params) => {\n const innerType = schema._zod.innerType;\n processSchema(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\n// ==================== ALL PROCESSORS ====================\nexport const allProcessors = {\n string: stringProcessor,\n number: numberProcessor,\n boolean: booleanProcessor,\n bigint: bigintProcessor,\n symbol: symbolProcessor,\n null: nullProcessor,\n undefined: undefinedProcessor,\n void: voidProcessor,\n never: neverProcessor,\n any: anyProcessor,\n unknown: unknownProcessor,\n date: dateProcessor,\n enum: enumProcessor,\n literal: literalProcessor,\n nan: nanProcessor,\n template_literal: templateLiteralProcessor,\n file: fileProcessor,\n success: successProcessor,\n custom: customProcessor,\n function: functionProcessor,\n transform: transformProcessor,\n map: mapProcessor,\n set: setProcessor,\n array: arrayProcessor,\n object: objectProcessor,\n union: unionProcessor,\n intersection: intersectionProcessor,\n tuple: tupleProcessor,\n record: recordProcessor,\n nullable: nullableProcessor,\n nonoptional: nonoptionalProcessor,\n default: defaultProcessor,\n prefault: prefaultProcessor,\n catch: catchProcessor,\n pipe: pipeProcessor,\n readonly: readonlyProcessor,\n promise: promiseProcessor,\n optional: optionalProcessor,\n lazy: lazyProcessor,\n};\nexport function toJSONSchema(input, params) {\n if (\"_idmap\" in input) {\n // Registry case\n const registry = input;\n const ctx = initializeContext({ ...params, processors: allProcessors });\n const defs = {};\n // First pass: process all schemas to build the seen map\n for (const entry of registry._idmap.entries()) {\n const [_, schema] = entry;\n processSchema(schema, ctx);\n }\n const schemas = {};\n const external = {\n registry,\n uri: params?.uri,\n defs,\n };\n // Update the context with external configuration\n ctx.external = external;\n // Second pass: emit each schema\n for (const entry of registry._idmap.entries()) {\n const [key, schema] = entry;\n extractDefs(ctx, schema);\n assignProp(schemas, key, finalize(ctx, schema));\n }\n if (Object.keys(defs).length > 0) {\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n schemas.__shared = {\n [defsSegment]: defs,\n };\n }\n return { schemas };\n }\n // Single schema case\n const ctx = initializeContext({ ...params, processors: allProcessors });\n processSchema(input, ctx);\n extractDefs(ctx, input);\n return finalize(ctx, input);\n}\n", "import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\n/* Prototypes that already carry the lazy helper methods. Seeded with the\n * intrinsics so that `init` on a foreign object — it accepts any object —\n * can never install an accessor onto a prototype we do not own. */\nconst _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);\n/* Helper methods live as non-enumerable lazy getters on the shared\n * prototype instead of own properties on every instance. On first\n * access the getter allocates the per-instance closure and caches it\n * as a non-enumerable own property, so detached usage still works and\n * the allocation only happens for methods actually touched. */\nfunction _lazyMethod(proto, key, make) {\n Object.defineProperty(proto, key, {\n configurable: true,\n enumerable: false,\n get() {\n const value = make(this);\n Object.defineProperty(this, key, { value, configurable: true, writable: true });\n return value;\n },\n set(value) {\n Object.defineProperty(this, key, { value, configurable: true, writable: true });\n },\n });\n}\nconst initializer = (inst, issues) => {\n $ZodError.init(inst, issues);\n inst.name = \"ZodError\";\n const proto = Object.getPrototypeOf(inst);\n if (_installedErrorProtos.has(proto))\n return;\n _installedErrorProtos.add(proto);\n _lazyMethod(proto, \"format\", (self) => (mapper) => core.formatError(self, mapper));\n _lazyMethod(proto, \"flatten\", (self) => (mapper) => core.flattenError(self, mapper));\n _lazyMethod(proto, \"addIssue\", (self) => (issue) => {\n self.issues.push(issue);\n self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);\n });\n _lazyMethod(proto, \"addIssues\", (self) => (issues) => {\n self.issues.push(...issues);\n self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);\n });\n Object.defineProperty(proto, \"isEmpty\", {\n configurable: true,\n enumerable: false,\n get() {\n return this.issues.length === 0;\n },\n });\n};\nexport const ZodError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer, undefined, {\n Parent: Error,\n});\n// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */\n// export type ErrorMapCtx = core.$ZodErrorMapCtx;\n", "import * as core from \"../core/index.js\";\nimport { ZodRealError } from \"./errors.js\";\nexport const parse = /* @__PURE__ */ core._parse(ZodRealError);\nexport const parseAsync = /* @__PURE__ */ core._parseAsync(ZodRealError);\nexport const safeParse = /* @__PURE__ */ core._safeParse(ZodRealError);\nexport const safeParseAsync = /* @__PURE__ */ core._safeParseAsync(ZodRealError);\nexport { validate, validateAsync } from \"../core/index.js\";\n// Codec functions\nexport const encode = /* @__PURE__ */ core._encode(ZodRealError);\nexport const decode = /* @__PURE__ */ core._decode(ZodRealError);\nexport const encodeAsync = /* @__PURE__ */ core._encodeAsync(ZodRealError);\nexport const decodeAsync = /* @__PURE__ */ core._decodeAsync(ZodRealError);\nexport const safeEncode = /* @__PURE__ */ core._safeEncode(ZodRealError);\nexport const safeDecode = /* @__PURE__ */ core._safeDecode(ZodRealError);\nexport const safeEncodeAsync = /* @__PURE__ */ core._safeEncodeAsync(ZodRealError);\nexport const safeDecodeAsync = /* @__PURE__ */ core._safeDecodeAsync(ZodRealError);\n", "import * as core from \"../core/index.js\";\nimport { util } from \"../core/index.js\";\nimport * as processors from \"../core/json-schema-processors.js\";\nimport * as regexes from \"../core/regexes.js\";\nimport { createStandardJSONSchemaMethod, createToJSONSchemaMethod } from \"../core/to-json-schema.js\";\nimport en from \"../locales/en.js\";\nimport * as checks from \"./checks.js\";\nimport * as parse from \"./parse.js\";\n// Register English as the default locale on first ZodType construction. Hooked into the `ZodType` `$constructor` (rather than a top-level `config(en())` in `external.ts`) so bundlers honoring `sideEffects: false` can't tree-shake it out — see #5953, #5725. An explicit `z.config(z.locales.xx())` call wins regardless of order, since this only sets the default when none is present.\nfunction _ensureDefaultLocale() {\n if (!core.globalConfig.localeError)\n core.config(en());\n}\n// the default memoizer is read by the core container init, which runs before `ZodType.init`, so each container calls this first\nfunction _ensureDefaultMemoizer() {\n if (!core.globalConfig.memoizer)\n core.config({ memoizer: core.memoizer() });\n}\nexport const ZodType = /*@__PURE__*/ core.$constructor(\"ZodType\", (inst, def) => {\n _ensureDefaultLocale();\n core.$ZodType.init(inst, def);\n inst.def = def;\n inst.type = def.type;\n return inst;\n}, {\n check(...chks) {\n const def = this.def;\n return this.clone(util.mergeDefs(def, {\n checks: [\n ...(def.checks ?? []),\n ...chks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }), { parent: true });\n },\n with(...chks) {\n return this.check(...chks);\n },\n clone(def, params) {\n return core.clone(this, def, params);\n },\n brand() {\n return this;\n },\n register(reg, meta) {\n reg.add(this, meta);\n return this;\n },\n refine(check, params) {\n return this.check(refine(check, params));\n },\n superRefine(refinement, params) {\n return this.check(superRefine(refinement, params));\n },\n overwrite(fn) {\n return this.check(checks.overwrite(fn));\n },\n optional() {\n return optional(this);\n },\n exactOptional() {\n return exactOptional(this);\n },\n nullable() {\n return nullable(this);\n },\n nullish() {\n return optional(nullable(this));\n },\n nonoptional(params) {\n return nonoptional(this, params);\n },\n array() {\n return array(this);\n },\n or(arg) {\n return union([this, arg]);\n },\n and(arg) {\n return intersection(this, arg);\n },\n transform(tx) {\n return pipe(this, transform(tx));\n },\n default(d) {\n return _default(this, d);\n },\n prefault(d) {\n return prefault(this, d);\n },\n catch(params) {\n return _catch(this, params);\n },\n pipe(target) {\n return pipe(this, target);\n },\n readonly() {\n return readonly(this);\n },\n describe(description) {\n const cl = this.clone();\n core.globalRegistry.add(cl, { description });\n return cl;\n },\n meta(...args) {\n // overloaded: meta() returns the registered metadata, meta(data) returns a clone with `data` registered. The mapped type picks up the second overload, so we accept variadic any-args and return `any` to satisfy both at runtime.\n if (args.length === 0)\n return core.globalRegistry.get(this);\n const cl = this.clone();\n core.globalRegistry.add(cl, args[0]);\n return cl;\n },\n isOptional() {\n return this.safeParse(undefined).success;\n },\n isNullable() {\n return this.safeParse(null).success;\n },\n apply(fn, ...args) {\n return args.length === 0 ? fn(this) : fn(this, ...args);\n },\n // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode.\n get \"~standard\"() {\n return util.hide(this, \"~standard\", {\n ...core.standardProps(this),\n jsonSchema: {\n input: createStandardJSONSchemaMethod(this, \"input\"),\n output: createStandardJSONSchemaMethod(this, \"output\"),\n },\n });\n },\n set \"~standard\"(value) {\n util.own(this, \"~standard\", value);\n },\n parse: function _parse(data, params) {\n return parse.parse(this, data, params, { callee: _parse });\n },\n parseAsync: async function _parseAsync(data, params) {\n return await parse.parseAsync(this, data, params, { callee: _parseAsync });\n },\n safeParse(data, params) {\n return parse.safeParse(this, data, params);\n },\n async safeParseAsync(data, params) {\n return parse.safeParseAsync(this, data, params);\n },\n // `spa` is an alias: same function object as `safeParseAsync`, as before.\n get spa() {\n return this?.safeParseAsync;\n },\n set spa(value) {\n util.own(this, \"spa\", value);\n },\n validate(data, params) {\n return parse.validate(this, data, params);\n },\n validateAsync(data, params) {\n return parse.validateAsync(this, data, params);\n },\n encode: function _encode(data, params) {\n return parse.encode(this, data, params, { callee: _encode });\n },\n decode: function _decode(data, params) {\n return parse.decode(this, data, params, { callee: _decode });\n },\n encodeAsync: async function _encodeAsync(data, params) {\n return await parse.encodeAsync(this, data, params, { callee: _encodeAsync });\n },\n decodeAsync: async function _decodeAsync(data, params) {\n return await parse.decodeAsync(this, data, params, { callee: _decodeAsync });\n },\n safeEncode(data, params) {\n return parse.safeEncode(this, data, params);\n },\n safeDecode(data, params) {\n return parse.safeDecode(this, data, params);\n },\n async safeEncodeAsync(data, params) {\n return parse.safeEncodeAsync(this, data, params);\n },\n async safeDecodeAsync(data, params) {\n return parse.safeDecodeAsync(this, data, params);\n },\n toJSONSchema(params) {\n return createToJSONSchemaMethod(this, {})(params);\n },\n // Reads through to the registry on every access, so it must not cache.\n get description() {\n return core.globalRegistry.get(this)?.description;\n },\n // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property.\n get _def() {\n return this._zod.def;\n },\n});\n/** @internal */\nexport const _ZodString = /*@__PURE__*/ core.$constructor(\"_ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.stringProcessor(inst, ctx, json, params);\n}, \n/*@__PURE__*/ util.derived({\n format: (inst) => processors.aggregateChecks(inst).format ?? null,\n minLength: (inst) => processors.aggregateChecks(inst).minimum ?? null,\n maxLength: (inst) => processors.aggregateChecks(inst).maximum ?? null,\n}, {\n regex(...args) {\n return this.check(checks.regex(...args));\n },\n includes(...args) {\n return this.check(checks.includes(...args));\n },\n startsWith(...args) {\n return this.check(checks.startsWith(...args));\n },\n endsWith(...args) {\n return this.check(checks.endsWith(...args));\n },\n min(...args) {\n return this.check(checks.minLength(...args));\n },\n max(...args) {\n return this.check(checks.maxLength(...args));\n },\n length(...args) {\n return this.check(checks.length(...args));\n },\n nonempty(...args) {\n return this.check(checks.minLength(1, ...args));\n },\n lowercase(params) {\n return this.check(checks.lowercase(params));\n },\n uppercase(params) {\n return this.check(checks.uppercase(params));\n },\n trim() {\n return this.check(checks.trim());\n },\n normalize(...args) {\n return this.check(checks.normalize(...args));\n },\n toLowerCase() {\n return this.check(checks.toLowerCase());\n },\n toUpperCase() {\n return this.check(checks.toUpperCase());\n },\n slugify() {\n return this.check(checks.slugify());\n },\n}));\nexport const ZodString = /*@__PURE__*/ core.$constructor(\"ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n _ZodString.init(inst, def);\n}, {\n email(params) {\n return this.check(core._email(ZodEmail, params));\n },\n url(params) {\n return this.check(core._url(ZodURL, params));\n },\n jwt(params) {\n return this.check(core._jwt(ZodJWT, params));\n },\n emoji(params) {\n return this.check(core._emoji(ZodEmoji, params));\n },\n guid(params) {\n return this.check(core._guid(ZodGUID, params));\n },\n uuid(params) {\n return this.check(core._uuid(ZodUUID, params));\n },\n uuidv4(params) {\n return this.check(core._uuidv4(ZodUUID, params));\n },\n uuidv6(params) {\n return this.check(core._uuidv6(ZodUUID, params));\n },\n uuidv7(params) {\n return this.check(core._uuidv7(ZodUUID, params));\n },\n nanoid(params) {\n return this.check(core._nanoid(ZodNanoID, params));\n },\n cuid(params) {\n return this.check(core._cuid(ZodCUID, params));\n },\n cuid2(params) {\n return this.check(core._cuid2(ZodCUID2, params));\n },\n ulid(params) {\n return this.check(core._ulid(ZodULID, params));\n },\n base64(params) {\n return this.check(core._base64(ZodBase64, params));\n },\n base64url(params) {\n return this.check(core._base64url(ZodBase64URL, params));\n },\n xid(params) {\n return this.check(core._xid(ZodXID, params));\n },\n ksuid(params) {\n return this.check(core._ksuid(ZodKSUID, params));\n },\n ipv4(params) {\n return this.check(core._ipv4(ZodIPv4, params));\n },\n ipv6(params) {\n return this.check(core._ipv6(ZodIPv6, params));\n },\n cidrv4(params) {\n return this.check(core._cidrv4(ZodCIDRv4, params));\n },\n cidrv6(params) {\n return this.check(core._cidrv6(ZodCIDRv6, params));\n },\n e164(params) {\n return this.check(core._e164(ZodE164, params));\n },\n datetime(params) {\n return this.check(core._isoDateTime(ZodISODateTime, params));\n },\n date(params) {\n return this.check(core._isoDate(ZodISODate, params));\n },\n time(params) {\n return this.check(core._isoTime(ZodISOTime, params));\n },\n duration(params) {\n return this.check(core._isoDuration(ZodISODuration, params));\n },\n});\nexport function string(params) {\n return core._string(ZodString, params);\n}\nexport const ZodStringFormat = /*@__PURE__*/ core.$constructor(\"ZodStringFormat\", (inst, def) => {\n core.$ZodStringFormat.init(inst, def);\n _ZodString.init(inst, def);\n});\nexport const ZodISODateTime = /*@__PURE__*/ core.$constructor(\"ZodISODateTime\", (inst, def) => {\n core.$ZodISODateTime.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodISODate = /*@__PURE__*/ core.$constructor(\"ZodISODate\", (inst, def) => {\n core.$ZodISODate.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodISOTime = /*@__PURE__*/ core.$constructor(\"ZodISOTime\", (inst, def) => {\n core.$ZodISOTime.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodISODuration = /*@__PURE__*/ core.$constructor(\"ZodISODuration\", (inst, def) => {\n core.$ZodISODuration.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodEmail = /*@__PURE__*/ core.$constructor(\"ZodEmail\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmail.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function email(params) {\n return core._email(ZodEmail, params);\n}\nexport const ZodGUID = /*@__PURE__*/ core.$constructor(\"ZodGUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodGUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function guid(params) {\n return core._guid(ZodGUID, params);\n}\nexport const ZodUUID = /*@__PURE__*/ core.$constructor(\"ZodUUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodUUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function uuid(params) {\n return core._uuid(ZodUUID, params);\n}\nexport function uuidv4(params) {\n return core._uuidv4(ZodUUID, params);\n}\n// ZodUUIDv6\nexport function uuidv6(params) {\n return core._uuidv6(ZodUUID, params);\n}\n// ZodUUIDv7\nexport function uuidv7(params) {\n return core._uuidv7(ZodUUID, params);\n}\nexport const ZodURL = /*@__PURE__*/ core.$constructor(\"ZodURL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodURL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function url(params) {\n return core._url(ZodURL, params);\n}\nexport function httpUrl(params) {\n return core._url(ZodURL, {\n protocol: regexes.httpProtocol,\n hostname: regexes.domain,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEmoji = /*@__PURE__*/ core.$constructor(\"ZodEmoji\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmoji.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function emoji(params) {\n return core._emoji(ZodEmoji, params);\n}\nexport const ZodNanoID = /*@__PURE__*/ core.$constructor(\"ZodNanoID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodNanoID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function nanoid(params) {\n return core._nanoid(ZodNanoID, params);\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const ZodCUID = /*@__PURE__*/ core.$constructor(\"ZodCUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\n/**\n * Validates a CUID v1 string.\n *\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport function cuid(params) {\n return core._cuid(ZodCUID, params);\n}\nexport const ZodCUID2 = /*@__PURE__*/ core.$constructor(\"ZodCUID2\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID2.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cuid2(params) {\n return core._cuid2(ZodCUID2, params);\n}\nexport const ZodULID = /*@__PURE__*/ core.$constructor(\"ZodULID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodULID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ulid(params) {\n return core._ulid(ZodULID, params);\n}\nexport const ZodXID = /*@__PURE__*/ core.$constructor(\"ZodXID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodXID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function xid(params) {\n return core._xid(ZodXID, params);\n}\nexport const ZodKSUID = /*@__PURE__*/ core.$constructor(\"ZodKSUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodKSUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ksuid(params) {\n return core._ksuid(ZodKSUID, params);\n}\nexport const ZodIPv4 = /*@__PURE__*/ core.$constructor(\"ZodIPv4\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv4(params) {\n return core._ipv4(ZodIPv4, params);\n}\nexport const ZodMAC = /*@__PURE__*/ core.$constructor(\"ZodMAC\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodMAC.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function mac(params) {\n return core._mac(ZodMAC, params);\n}\nexport const ZodIPv6 = /*@__PURE__*/ core.$constructor(\"ZodIPv6\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv6(params) {\n return core._ipv6(ZodIPv6, params);\n}\nexport const ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv4\", (inst, def) => {\n core.$ZodCIDRv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv4(params) {\n return core._cidrv4(ZodCIDRv4, params);\n}\nexport const ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv6\", (inst, def) => {\n core.$ZodCIDRv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv6(params) {\n return core._cidrv6(ZodCIDRv6, params);\n}\nexport const ZodBase64 = /*@__PURE__*/ core.$constructor(\"ZodBase64\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64(params) {\n return core._base64(ZodBase64, params);\n}\nexport const ZodBase64URL = /*@__PURE__*/ core.$constructor(\"ZodBase64URL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64URL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64url(params) {\n return core._base64url(ZodBase64URL, params);\n}\nexport const ZodE164 = /*@__PURE__*/ core.$constructor(\"ZodE164\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodE164.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function e164(params) {\n return core._e164(ZodE164, params);\n}\nexport const ZodCreditCard = /*@__PURE__*/ core.$constructor(\"ZodCreditCard\", (inst, def) => {\n core.$ZodCreditCard.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function creditCard(params) {\n return core._creditCard(ZodCreditCard, params);\n}\nexport const ZodIBAN = /*@__PURE__*/ core.$constructor(\"ZodIBAN\", (inst, def) => {\n core.$ZodIBAN.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function iban(params) {\n return core._iban(ZodIBAN, params);\n}\nexport const ZodJWT = /*@__PURE__*/ core.$constructor(\"ZodJWT\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodJWT.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function jwt(params) {\n return core._jwt(ZodJWT, params);\n}\nexport const ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodCustomStringFormat\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCustomStringFormat.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params);\n}\nexport function hostname(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hostname\", regexes.hostname, _params);\n}\nexport function hex(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hex\", regexes.hex, _params);\n}\nexport function currencyCode(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"currency_code\", regexes.currencyCode, _params);\n}\nexport function hash(alg, params) {\n const enc = params?.enc ?? \"hex\";\n const format = `${alg}_${enc}`;\n const regex = core.regexes[format];\n if (!regex)\n throw new Error(`Unrecognized hash format: ${format}`);\n return core._stringFormat(ZodCustomStringFormat, format, regex, params);\n}\nexport const ZodNumber = /*@__PURE__*/ core.$constructor(\"ZodNumber\", (inst, def) => {\n core.$ZodNumber.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.numberProcessor(inst, ctx, json, params);\n inst.isFinite = true;\n}, \n/*@__PURE__*/ util.derived({\n minValue: (inst) => {\n const { minimum, exclusiveMinimum } = processors.aggregateChecks(inst);\n return Math.max(minimum ?? Number.NEGATIVE_INFINITY, exclusiveMinimum ?? Number.NEGATIVE_INFINITY);\n },\n maxValue: (inst) => {\n const { maximum, exclusiveMaximum } = processors.aggregateChecks(inst);\n return Math.min(maximum ?? Number.POSITIVE_INFINITY, exclusiveMaximum ?? Number.POSITIVE_INFINITY);\n },\n isInt: (inst) => {\n const { isInt, multipleOf } = processors.aggregateChecks(inst);\n return !!isInt || !!multipleOf?.some(Number.isSafeInteger);\n },\n format: (inst) => processors.aggregateChecks(inst).format ?? null,\n}, {\n gt(value, params) {\n return this.check(checks.gt(value, params));\n },\n gte(value, params) {\n return this.check(checks.gte(value, params));\n },\n min(value, params) {\n return this.check(checks.gte(value, params));\n },\n lt(value, params) {\n return this.check(checks.lt(value, params));\n },\n lte(value, params) {\n return this.check(checks.lte(value, params));\n },\n max(value, params) {\n return this.check(checks.lte(value, params));\n },\n int(params) {\n return this.check(int(params));\n },\n safe(params) {\n return this.check(int(params));\n },\n positive(params) {\n return this.check(checks.gt(0, params));\n },\n nonnegative(params) {\n return this.check(checks.gte(0, params));\n },\n negative(params) {\n return this.check(checks.lt(0, params));\n },\n nonpositive(params) {\n return this.check(checks.lte(0, params));\n },\n multipleOf(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n step(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n finite() {\n return this;\n },\n}));\nexport function number(params) {\n return core._number(ZodNumber, params);\n}\nexport const ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodNumberFormat\", (inst, def) => {\n core.$ZodNumberFormat.init(inst, def);\n ZodNumber.init(inst, def);\n});\nexport function int(params) {\n return core._int(ZodNumberFormat, params);\n}\nexport function float32(params) {\n return core._float32(ZodNumberFormat, params);\n}\nexport function float64(params) {\n return core._float64(ZodNumberFormat, params);\n}\nexport function int32(params) {\n return core._int32(ZodNumberFormat, params);\n}\nexport function uint32(params) {\n return core._uint32(ZodNumberFormat, params);\n}\nexport const ZodBoolean = /*@__PURE__*/ core.$constructor(\"ZodBoolean\", (inst, def) => {\n core.$ZodBoolean.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.booleanProcessor(inst, ctx, json, params);\n});\nexport function boolean(params) {\n return core._boolean(ZodBoolean, params);\n}\nexport const ZodBigInt = /*@__PURE__*/ core.$constructor(\"ZodBigInt\", (inst, def) => {\n core.$ZodBigInt.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params);\n}, \n/*@__PURE__*/ util.derived({\n minValue: (inst) => processors.aggregateChecks(inst).minimum ?? null,\n maxValue: (inst) => processors.aggregateChecks(inst).maximum ?? null,\n format: (inst) => processors.aggregateChecks(inst).format ?? null,\n}, {\n gte(value, params) {\n return this.check(checks.gte(value, params));\n },\n min(value, params) {\n return this.check(checks.gte(value, params));\n },\n gt(value, params) {\n return this.check(checks.gt(value, params));\n },\n lt(value, params) {\n return this.check(checks.lt(value, params));\n },\n lte(value, params) {\n return this.check(checks.lte(value, params));\n },\n max(value, params) {\n return this.check(checks.lte(value, params));\n },\n positive(params) {\n return this.check(checks.gt(BigInt(0), params));\n },\n negative(params) {\n return this.check(checks.lt(BigInt(0), params));\n },\n nonpositive(params) {\n return this.check(checks.lte(BigInt(0), params));\n },\n nonnegative(params) {\n return this.check(checks.gte(BigInt(0), params));\n },\n multipleOf(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n}));\nexport function bigint(params) {\n return core._bigint(ZodBigInt, params);\n}\nexport const ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodBigIntFormat\", (inst, def) => {\n core.$ZodBigIntFormat.init(inst, def);\n ZodBigInt.init(inst, def);\n});\nexport function int64(params) {\n return core._int64(ZodBigIntFormat, params);\n}\nexport function uint64(params) {\n return core._uint64(ZodBigIntFormat, params);\n}\nexport const ZodSymbol = /*@__PURE__*/ core.$constructor(\"ZodSymbol\", (inst, def) => {\n core.$ZodSymbol.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params);\n});\nexport function symbol(params) {\n return core._symbol(ZodSymbol, params);\n}\nexport const ZodUndefined = /*@__PURE__*/ core.$constructor(\"ZodUndefined\", (inst, def) => {\n core.$ZodUndefined.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params);\n});\nfunction _undefined(params) {\n return core._undefined(ZodUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodNull = /*@__PURE__*/ core.$constructor(\"ZodNull\", (inst, def) => {\n core.$ZodNull.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullProcessor(inst, ctx, json, params);\n});\nfunction _null(params) {\n return core._null(ZodNull, params);\n}\nexport { _null as null };\nexport const ZodAny = /*@__PURE__*/ core.$constructor(\"ZodAny\", (inst, def) => {\n core.$ZodAny.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.anyProcessor(inst, ctx, json, params);\n});\nexport function any() {\n return core._any(ZodAny);\n}\nexport const ZodUnknown = /*@__PURE__*/ core.$constructor(\"ZodUnknown\", (inst, def) => {\n core.$ZodUnknown.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unknownProcessor(inst, ctx, json, params);\n});\nexport function unknown() {\n return core._unknown(ZodUnknown);\n}\nexport const ZodNever = /*@__PURE__*/ core.$constructor(\"ZodNever\", (inst, def) => {\n core.$ZodNever.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.neverProcessor(inst, ctx, json, params);\n});\nexport function never(params) {\n return core._never(ZodNever, params);\n}\nexport const ZodVoid = /*@__PURE__*/ core.$constructor(\"ZodVoid\", (inst, def) => {\n core.$ZodVoid.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params);\n});\nfunction _void(params) {\n return core._void(ZodVoid, params);\n}\nexport { _void as void };\nexport const ZodDate = /*@__PURE__*/ core.$constructor(\"ZodDate\", (inst, def) => {\n core.$ZodDate.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params);\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n}, \n/*@__PURE__*/ util.derived({\n minDate: (inst) => {\n const { minimum } = processors.aggregateChecks(inst);\n return minimum ? new Date(minimum) : null;\n },\n maxDate: (inst) => {\n const { maximum } = processors.aggregateChecks(inst);\n return maximum ? new Date(maximum) : null;\n },\n}, {}));\nexport function date(params) {\n return core._date(ZodDate, params);\n}\nexport const ZodArray = /*@__PURE__*/ core.$constructor(\"ZodArray\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodArray.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.arrayProcessor(inst, ctx, json, params);\n inst.element = def.element;\n}, {\n min(n, params) {\n return this.check(checks.minLength(n, params));\n },\n nonempty(params) {\n return this.check(checks.minLength(1, params));\n },\n max(n, params) {\n return this.check(checks.maxLength(n, params));\n },\n length(n, params) {\n return this.check(checks.length(n, params));\n },\n unwrap() {\n return this.element;\n },\n});\nexport function array(element, params) {\n return core._array(ZodArray, element, params);\n}\n// .keyof\nexport function keyof(schema) {\n const shape = schema._zod.def.shape;\n return _enum(Object.keys(shape));\n}\nexport const ZodObject = /*@__PURE__*/ core.$constructor(\"ZodObject\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodObjectJIT.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.objectProcessor(inst, ctx, json, params);\n util.installLazyProp(inst, \"shape\", (self) => self._zod.def.shape, false);\n}, {\n keyof() {\n return _enum(Object.keys(this._zod.def.shape));\n },\n catchall(catchall) {\n // `mergeDefs` rather than a spread: spreading reads `shape`, and resolving it can mint a whole fresh subtree\n return this.clone(util.mergeDefs(this._zod.def, { catchall: catchall }));\n },\n passthrough() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: unknown() }));\n },\n loose() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: unknown() }));\n },\n strict() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: never() }));\n },\n strip() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: undefined }));\n },\n extend(incoming) {\n return util.extend(this, incoming);\n },\n safeExtend(incoming) {\n return util.safeExtend(this, incoming);\n },\n merge(other) {\n return util.merge(this, other);\n },\n pick(mask) {\n return util.pick(this, mask);\n },\n omit(mask) {\n return util.omit(this, mask);\n },\n partial(...args) {\n return util.partial(ZodOptional, this, args[0]);\n },\n exactPartial(...args) {\n return util.partial(ZodExactOptional, this, args[0], \"exactPartial\");\n },\n required(...args) {\n return util.required(ZodNonOptional, this, args[0]);\n },\n});\nexport function object(shape, params) {\n const def = {\n type: \"object\",\n shape: shape ?? {},\n ...util.normalizeParams(params),\n };\n return new ZodObject(def);\n}\n// strictObject\nexport function strictObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: never(),\n ...util.normalizeParams(params),\n });\n}\n// looseObject\nexport function looseObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: unknown(),\n ...util.normalizeParams(params),\n });\n}\nexport const ZodUnion = /*@__PURE__*/ core.$constructor(\"ZodUnion\", (inst, def) => {\n core.$ZodUnion.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\nexport function union(options, params) {\n return new ZodUnion({\n type: \"union\",\n options: options,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodXor = /*@__PURE__*/ core.$constructor(\"ZodXor\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodXor.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\n/** Creates an exclusive union (XOR) where exactly one option must match.\n * Unlike regular unions that succeed when any option matches, xor fails if\n * zero or more than one option matches the input. */\nexport function xor(options, params) {\n return new ZodXor({\n type: \"union\",\n options: options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodDiscriminatedUnion\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodDiscriminatedUnion.init(inst, def);\n});\nexport function discriminatedUnion(discriminator, options, params) {\n // const [options, params] = args;\n return new ZodDiscriminatedUnion({\n type: \"union\",\n options: options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodIntersection = /*@__PURE__*/ core.$constructor(\"ZodIntersection\", (inst, def) => {\n core.$ZodIntersection.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.intersectionProcessor(inst, ctx, json, params);\n});\nexport function intersection(left, right) {\n return new ZodIntersection({\n type: \"intersection\",\n left: left,\n right: right,\n });\n}\nexport const ZodTuple = /*@__PURE__*/ core.$constructor(\"ZodTuple\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodTuple.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params);\n}, {\n rest(rest) {\n return this.clone({\n ...this._zod.def,\n rest: rest,\n });\n },\n partial() {\n const def = this._zod.def;\n // a refinement was authored against the full arity; partialing would run it on a shorter array\n if (def.checks?.length)\n throw new Error(\".partial() cannot be used on tuple schemas containing refinements\");\n return this.clone({\n ...def,\n items: def.items.map((item) => new ZodOptional({ type: \"optional\", innerType: item })),\n });\n },\n});\nexport function tuple(items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof core.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new ZodTuple({\n type: \"tuple\",\n items: items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodRecord = /*@__PURE__*/ core.$constructor(\"ZodRecord\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodRecord.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.recordProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n});\nexport function record(keyType, valueType, params) {\n // v3-compat: z.record(valueType, params?) — defaults keyType to z.string()\n if (!valueType || !valueType._zod) {\n return new ZodRecord({\n type: \"record\",\n keyType: string(),\n valueType: keyType,\n ...util.normalizeParams(valueType),\n });\n }\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\n// type alksjf = core.output<core.$ZodRecordKey>;\nexport function partialRecord(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n partial: true,\n });\n}\nexport function looseRecord(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n mode: \"loose\",\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMap = /*@__PURE__*/ core.$constructor(\"ZodMap\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodMap.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function map(keyType, valueType, params) {\n return new ZodMap({\n type: \"map\",\n keyType: keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSet = /*@__PURE__*/ core.$constructor(\"ZodSet\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodSet.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params);\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function set(valueType, params) {\n return new ZodSet({\n type: \"set\",\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEnum = /*@__PURE__*/ core.$constructor(\"ZodEnum\", (inst, def) => {\n core.$ZodEnum.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.enumProcessor(inst, ctx, json, params);\n inst.enum = def.entries;\n // reuse the parsed value set so a numeric TS enum's reverse-mapping keys stay out\n inst.options = [...inst._zod.values];\n const keys = new Set(Object.keys(def.entries));\n inst.extract = (values, params) => {\n const newEntries = {};\n for (const value of values) {\n if (keys.has(value)) {\n newEntries[value] = def.entries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n inst.exclude = (values, params) => {\n const newEntries = { ...def.entries };\n for (const value of values) {\n if (keys.has(value)) {\n delete newEntries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n});\nfunction _enum(values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport { _enum as enum };\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function nativeEnum(entries, params) {\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLiteral = /*@__PURE__*/ core.$constructor(\"ZodLiteral\", (inst, def) => {\n core.$ZodLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.literalProcessor(inst, ctx, json, params);\n inst.values = new Set(def.values);\n Object.defineProperty(inst, \"value\", {\n get() {\n if (def.values.length > 1) {\n throw new Error(\"This schema contains multiple valid literal values. Use `.values` instead.\");\n }\n return def.values[0];\n },\n });\n});\nexport function literal(value, params) {\n return new ZodLiteral({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport const ZodFile = /*@__PURE__*/ core.$constructor(\"ZodFile\", (inst, def) => {\n core.$ZodFile.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params);\n inst.min = (size, params) => inst.check(core._minSize(size, params));\n inst.max = (size, params) => inst.check(core._maxSize(size, params));\n inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params));\n});\nexport function file(params) {\n return core._file(ZodFile, params);\n}\nexport const ZodTransform = /*@__PURE__*/ core.$constructor(\"ZodTransform\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodTransform.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.transformProcessor(inst, ctx, json, params);\n inst._zod.parse = (payload, _ctx) => {\n if (_ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n if (!(\"input\" in _issue))\n _issue.input = payload.value;\n _issue.inst ?? (_issue.inst = inst);\n // _issue.continue ??= true;\n payload.issues.push(util.issue(_issue));\n }\n };\n const output = def.transform(payload.value, payload);\n if (output instanceof Promise) {\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n payload.value = output;\n return payload;\n };\n});\nexport function transform(fn) {\n return new ZodTransform({\n type: \"transform\",\n transform: fn,\n });\n}\nexport const ZodOptional = /*@__PURE__*/ core.$constructor(\"ZodOptional\", (inst, def) => {\n core.$ZodOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function optional(innerType) {\n return new ZodOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodExactOptional = /*@__PURE__*/ core.$constructor(\"ZodExactOptional\", (inst, def) => {\n core.$ZodExactOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function exactOptional(innerType) {\n return new ZodExactOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodNullable = /*@__PURE__*/ core.$constructor(\"ZodNullable\", (inst, def) => {\n core.$ZodNullable.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullableProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nullable(innerType) {\n return new ZodNullable({\n type: \"nullable\",\n innerType: innerType,\n });\n}\n// nullish\nexport function nullish(innerType) {\n return optional(nullable(innerType));\n}\nexport const ZodDefault = /*@__PURE__*/ core.$constructor(\"ZodDefault\", (inst, def) => {\n core.$ZodDefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.defaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeDefault = inst.unwrap;\n});\nexport function _default(innerType, defaultValue) {\n return new ZodDefault({\n type: \"default\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodPrefault = /*@__PURE__*/ core.$constructor(\"ZodPrefault\", (inst, def) => {\n core.$ZodPrefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.prefaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function prefault(innerType, defaultValue) {\n return new ZodPrefault({\n type: \"prefault\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodNonOptional = /*@__PURE__*/ core.$constructor(\"ZodNonOptional\", (inst, def) => {\n core.$ZodNonOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nonoptionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nonoptional(innerType, params) {\n return new ZodNonOptional({\n type: \"nonoptional\",\n innerType: innerType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSuccess = /*@__PURE__*/ core.$constructor(\"ZodSuccess\", (inst, def) => {\n core.$ZodSuccess.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function success(innerType) {\n return new ZodSuccess({\n type: \"success\",\n innerType: innerType,\n });\n}\nexport const ZodCatch = /*@__PURE__*/ core.$constructor(\"ZodCatch\", (inst, def) => {\n core.$ZodCatch.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.catchProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeCatch = inst.unwrap;\n});\nfunction _catch(innerType, catchValue) {\n return new ZodCatch({\n type: \"catch\",\n innerType: innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : core.util.constantCatch(catchValue)),\n });\n}\nexport { _catch as catch };\nexport const ZodNaN = /*@__PURE__*/ core.$constructor(\"ZodNaN\", (inst, def) => {\n core.$ZodNaN.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params);\n});\nexport function nan(params) {\n return core._nan(ZodNaN, params);\n}\nexport const ZodPipe = /*@__PURE__*/ core.$constructor(\"ZodPipe\", (inst, def) => {\n core.$ZodPipe.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.pipeProcessor(inst, ctx, json, params);\n inst.in = def.in;\n inst.out = def.out;\n});\nexport function pipe(in_, out) {\n return new ZodPipe({\n type: \"pipe\",\n in: in_,\n out: out,\n // ...util.normalizeParams(params),\n });\n}\nexport const ZodCodec = /*@__PURE__*/ core.$constructor(\"ZodCodec\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodCodec.init(inst, def);\n});\nexport function codec(in_, out, params) {\n return new ZodCodec({\n type: \"pipe\",\n in: in_,\n out: out,\n transform: params.decode,\n reverseTransform: params.encode,\n });\n}\nexport function invertCodec(codec) {\n const def = codec._zod.def;\n return new ZodCodec({\n type: \"pipe\",\n in: def.out,\n out: def.in,\n transform: def.reverseTransform,\n reverseTransform: def.transform,\n });\n}\nexport const ZodPreprocess = /*@__PURE__*/ core.$constructor(\"ZodPreprocess\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodPreprocess.init(inst, def);\n});\nexport const ZodReadonly = /*@__PURE__*/ core.$constructor(\"ZodReadonly\", (inst, def) => {\n core.$ZodReadonly.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.readonlyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function readonly(innerType) {\n return new ZodReadonly({\n type: \"readonly\",\n innerType: innerType,\n });\n}\nexport const ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodTemplateLiteral\", (inst, def) => {\n core.$ZodTemplateLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params);\n});\nexport function templateLiteral(parts, params) {\n return new ZodTemplateLiteral({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLazy = /*@__PURE__*/ core.$constructor(\"ZodLazy\", (inst, def) => {\n core.$ZodLazy.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.lazyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.getter();\n});\nexport function lazy(getter) {\n return new ZodLazy({\n type: \"lazy\",\n getter: getter,\n });\n}\nexport const ZodPromise = /*@__PURE__*/ core.$constructor(\"ZodPromise\", (inst, def) => {\n core.$ZodPromise.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function promise(innerType) {\n return new ZodPromise({\n type: \"promise\",\n innerType: innerType,\n });\n}\nexport const ZodFunction = /*@__PURE__*/ core.$constructor(\"ZodFunction\", (inst, def) => {\n core.$ZodFunction.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params);\n});\nexport function _function(params) {\n return new ZodFunction({\n type: \"function\",\n input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())),\n output: params?.output ?? unknown(),\n });\n}\nexport { _function as function };\nexport const ZodCustom = /*@__PURE__*/ core.$constructor(\"ZodCustom\", (inst, def) => {\n core.$ZodCustom.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.customProcessor(inst, ctx, json, params);\n});\n// custom checks\nexport function check(fn) {\n const ch = new core.$ZodCheck({\n check: \"custom\",\n // ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\nexport function custom(fn, _params) {\n return core._custom(ZodCustom, fn ?? (() => true), _params);\n}\nexport function refine(fn, _params = {}) {\n return core._refine(ZodCustom, fn, _params);\n}\n// superRefine\nexport function superRefine(fn, params) {\n return core._superRefine(fn, params);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\nexport const ZodInstanceOf = /*@__PURE__*/ core.$constructor(\"ZodInstanceOf\", (inst, def) => {\n ZodCustom.init(inst, def);\n}, {\n properties(shape, params) {\n // asserts in place, so the narrowed output type is truthful without a wrapper\n return this.check(core._properties(shape, params));\n },\n});\nfunction _instanceof(cls, params = {}) {\n const inst = new ZodInstanceOf({\n type: \"custom\",\n check: \"custom\",\n fn: (data) => data instanceof cls,\n abort: true,\n ...util.normalizeParams(params),\n });\n inst._zod.bag.Class = cls;\n // Override check to emit invalid_type instead of custom\n inst._zod.check = (payload) => {\n if (!(payload.value instanceof cls)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: cls.name,\n input: payload.value,\n inst,\n path: [...(inst._zod.def.path ?? [])],\n });\n }\n };\n return inst;\n}\nexport { _instanceof as instanceof };\n// stringbool\nexport const stringbool = (...args) => core._stringbool({\n Codec: ZodCodec,\n Boolean: ZodBoolean,\n String: ZodString,\n}, ...args);\nexport function json(params) {\n const jsonSchema = lazy(() => {\n return union([string(params), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n });\n return jsonSchema;\n}\n// preprocess\nexport function preprocess(fn, schema) {\n return new ZodPreprocess({\n type: \"pipe\",\n in: transform(fn),\n out: schema,\n });\n}\n", "import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport function string(params) {\n return core._coercedString(schemas.ZodString, params);\n}\nexport function number(params) {\n return core._coercedNumber(schemas.ZodNumber, params);\n}\nexport function boolean(params) {\n return core._coercedBoolean(schemas.ZodBoolean, params);\n}\nexport function bigint(params) {\n return core._coercedBigint(schemas.ZodBigInt, params);\n}\nexport function date(params) {\n return core._coercedDate(schemas.ZodDate, params);\n}\n", "import { z } from \"zod\";\nimport { cliProducts } from \"./constants\";\n\nconst dateTimeString = z\n\t.string()\n\t.refine((value) => Number.isFinite(Date.parse(value)), \"Invalid datetime\");\nconst base64Url = z\n\t.string()\n\t.min(43)\n\t.max(128)\n\t.regex(/^[A-Za-z0-9_-]+$/);\n\nexport const beginDeviceAuthorizationRequestSchema = z\n\t.object({\n\t\tclientName: z.string().trim().min(1).max(120),\n\t\tclientVersion: z.string().trim().min(1).max(64),\n\t\tcodeChallenge: base64Url,\n\t\tcodeChallengeMethod: z.literal(\"S256\"),\n\t\tplatform: z.string().trim().min(1).max(64),\n\t})\n\t.strict();\n\nexport const beginDeviceAuthorizationResponseSchema = z\n\t.object({\n\t\tdeviceCode: z.string().min(40).max(128),\n\t\texpiresIn: z.number().int().min(60).max(1800),\n\t\tinterval: z.number().int().min(1).max(30),\n\t\tuserCode: z.string().regex(/^[A-HJ-NP-Z2-9]{4}-[A-HJ-NP-Z2-9]{4}$/),\n\t\tverificationUri: z.string().url(),\n\t\tverificationUriComplete: z.string().url(),\n\t})\n\t.strict();\n\nexport const tokenRequestSchema = z\n\t.object({\n\t\tcodeVerifier: base64Url,\n\t\tdeviceCode: z.string().min(40).max(128),\n\t})\n\t.strict();\n\nexport const cliSessionIdentitySchema = z\n\t.object({\n\t\temail: z.string().email(),\n\t\tid: z.string().min(1),\n\t\tname: z.string().min(1).max(120),\n\t\tuserId: z.string().min(1),\n\t})\n\t.strict();\n\nexport const tokenResponseSchema = z\n\t.object({\n\t\taccessToken: z.string().min(40),\n\t\texpiresIn: z.number().int().positive(),\n\t\trefreshExpiresIn: z.number().int().positive(),\n\t\trefreshToken: z.string().min(40),\n\t\tsession: cliSessionIdentitySchema,\n\t\ttokenType: z.literal(\"Bearer\"),\n\t})\n\t.strict();\n\nexport const deviceTokenErrorSchema = z\n\t.object({\n\t\terror: z.enum([\n\t\t\t\"authorization_pending\",\n\t\t\t\"slow_down\",\n\t\t\t\"access_denied\",\n\t\t\t\"expired_token\",\n\t\t\t\"invalid_grant\",\n\t\t]),\n\t})\n\t.strict();\n\nexport const refreshRequestSchema = z\n\t.object({ refreshToken: z.string().min(40) })\n\t.strict();\nexport const revokeRequestSchema = refreshRequestSchema;\n\nexport const storedCliCredentialsSchema = z\n\t.object({\n\t\taccessToken: z.string().min(1),\n\t\taccessTokenExpiresAt: dateTimeString,\n\t\t// Credentials written before issuer binding was introduced are accepted only\n\t\t// so the client can direct the user to sign in again. They are never sent.\n\t\tissuer: z.string().url().optional(),\n\t\trefreshToken: z.string().min(1),\n\t\trefreshTokenExpiresAt: dateTimeString,\n\t\tsession: cliSessionIdentitySchema,\n\t})\n\t.strict();\nexport type StoredCliCredentials = z.infer<typeof storedCliCredentialsSchema>;\n\nexport const cliProductSchema = z.enum(cliProducts);\n", "import { execFile } from \"node:child_process\";\nimport type { CliProduct } from \"@go-labs/cli-auth/protocol\";\nimport { z } from \"zod\";\nimport type { SecretsApi } from \"./credential-store\";\nimport { assertBunRuntime } from \"./runtime\";\nimport {\n\tCliCredentialStoreUnavailableError,\n\ttype CredentialStoreFailure,\n\tclassifyCredentialStoreFailure,\n} from \"./storage-error\";\n\nconst timeoutMs = 10_000;\nconst maxBuffer = 64 * 1024;\n\n// No shell, secret argv, inherited stdin, raw backend errors, or unbounded output.\nconst runBackend = (\n\tproduct: CliProduct,\n\texecutable: string,\n\targs: string[],\n\tinput: string,\n\tfailure: CredentialStoreFailure,\n): Promise<string> =>\n\tnew Promise((resolve, reject) => {\n\t\tconst child = execFile(\n\t\t\texecutable,\n\t\t\targs,\n\t\t\t{\n\t\t\t\ttimeout: timeoutMs,\n\t\t\t\tkillSignal: \"SIGKILL\",\n\t\t\t\tmaxBuffer,\n\t\t\t\twindowsHide: true,\n\t\t\t},\n\t\t\t(error, stdout, stderr) => {\n\t\t\t\tif (error) {\n\t\t\t\t\tconst reason =\n\t\t\t\t\t\terror.code === \"ERR_CHILD_PROCESS_STDIO_MAXBUFFER\"\n\t\t\t\t\t\t\t? \"invalid-response\"\n\t\t\t\t\t\t\t: error.killed\n\t\t\t\t\t\t\t\t? \"timeout\"\n\t\t\t\t\t\t\t\t: classifyCredentialStoreFailure(\n\t\t\t\t\t\t\t\t\t\t`${stdout}\\n${stderr}`,\n\t\t\t\t\t\t\t\t\t\tfailure,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\treject(new CliCredentialStoreUnavailableError(product, reason));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tresolve(stdout);\n\t\t\t},\n\t\t);\n\t\tchild.stdin?.on(\"error\", () => {\n\t\t\t/* Completion callback owns diagnostics. */\n\t\t});\n\t\tchild.stdin?.end(input);\n\t});\n\n// Run Bun.secrets in a cancellable child. A Promise.race cannot stop native calls\n// or a desktop unlock prompt from keeping the CLI alive after its timeout.\nconst nativeWorker = `\ntry {\n const { operation, input } = JSON.parse(await Bun.stdin.text());\n const value = await Bun.secrets[operation](input);\n process.stdout.write(JSON.stringify({ value: value ?? null }));\n} catch (error) {\n const message = error instanceof Error ? error.message : \"Credential backend failed\";\n // libsecret's bus transport errors can omit the D-Bus context.\n const context = process.platform === \"linux\" && /^Could not connect:/i.test(message) ? \"D-Bus: \" : \"\";\n process.stderr.write(context + message);\n process.exitCode = 1;\n}\n`;\nconst nativeResponse = z\n\t.object({ value: z.union([z.string(), z.boolean(), z.null()]) })\n\t.strict();\n\nexport const createIsolatedBunSecrets = (product: CliProduct): SecretsApi => {\n\tconst run = async (\n\t\toperation: \"get\" | \"set\" | \"delete\",\n\t\tinput: { name: string; service: string; value?: string },\n\t) => {\n\t\tassertBunRuntime();\n\t\tconst output = await runBackend(\n\t\t\tproduct,\n\t\t\tprocess.execPath,\n\t\t\t[\"--no-env-file\", \"--eval\", nativeWorker],\n\t\t\tJSON.stringify({ operation, input }),\n\t\t\toperation === \"set\"\n\t\t\t\t? \"write-failed\"\n\t\t\t\t: operation === \"delete\"\n\t\t\t\t\t? \"delete-failed\"\n\t\t\t\t\t: \"read-failed\",\n\t\t);\n\t\ttry {\n\t\t\treturn nativeResponse.parse(JSON.parse(output)).value;\n\t\t} catch {\n\t\t\tthrow new CliCredentialStoreUnavailableError(product, \"invalid-response\");\n\t\t}\n\t};\n\treturn {\n\t\tget: async (input) => {\n\t\t\tconst value = await run(\"get\", input);\n\t\t\tif (value === null || typeof value === \"string\") return value;\n\t\t\tthrow new CliCredentialStoreUnavailableError(product, \"invalid-response\");\n\t\t},\n\t\tset: async (input) => {\n\t\t\tawait run(\"set\", input);\n\t\t},\n\t\tdelete: async (input) => (await run(\"delete\", input)) === true,\n\t};\n};\n", "export const MINIMUM_BUN_VERSION = [1, 4, 0] as const;\n\nexport const parseBunVersion = (version: string): [number, number, number] => {\n\tconst match = /^(\\d+)\\.(\\d+)\\.(\\d+)/.exec(version);\n\tif (!match) throw new Error(`Unable to parse Bun version: ${version}`);\n\treturn [Number(match[1]), Number(match[2]), Number(match[3])];\n};\n\nconst compareVersions = (left: readonly number[], right: readonly number[]) => {\n\tfor (let index = 0; index < 3; index += 1) {\n\t\tconst difference = (left[index] ?? 0) - (right[index] ?? 0);\n\t\tif (difference !== 0) return difference;\n\t}\n\treturn 0;\n};\n\nexport const assertBunRuntime = (\n\truntime: { version: string } | undefined = globalThis.Bun,\n): void => {\n\tif (!runtime) {\n\t\tthrow new Error(\n\t\t\t\"This CLI requires Bun 1.4.0 or newer. Install it with `npm install --global bun`, then retry the command.\",\n\t\t);\n\t}\n\tif (\n\t\tcompareVersions(parseBunVersion(runtime.version), MINIMUM_BUN_VERSION) < 0\n\t) {\n\t\tthrow new Error(\n\t\t\t`This CLI requires Bun 1.4.0 or newer (found ${runtime.version}). Run \\`bun upgrade\\`, then retry the command.`,\n\t\t);\n\t}\n};\n", "import type { CliProduct } from \"@go-labs/cli-auth/protocol\";\n\nexport type CredentialStoreFailure =\n\t| \"missing-library\"\n\t| \"bus-unavailable\"\n\t| \"bus-denied\"\n\t| \"service-unavailable\"\n\t| \"locked\"\n\t| \"timeout\"\n\t| \"invalid-response\"\n\t| \"read-failed\"\n\t| \"write-failed\"\n\t| \"delete-failed\";\n\nconst guidance: Record<CredentialStoreFailure, string> = {\n\t\"missing-library\":\n\t\t\"Install the runtime's native credential-store library and ensure your own native keyring/session is accessible and unlocked; Linux desktop storage requires libsecret AND an accessible, unlocked Secret Service.\",\n\t\"bus-unavailable\":\n\t\t\"The Linux user D-Bus session is absent or unreachable. --no-browser does not provide storage. Start or repair your own user session and native keyring before retrying.\",\n\t\"bus-denied\":\n\t\t\"Access to the Linux user bus was denied. Fix your own native keyring/session permissions or host policy; do not change bus/socket permissions or borrow another user's bus.\",\n\t\"service-unavailable\":\n\t\t\"The user bus is reachable but your own Secret Service is unavailable. Start or repair your own native keyring session; do not expose another user's store.\",\n\tlocked:\n\t\t\"Unlock your own native credential collection/session before retrying. The CLI will not wait indefinitely for an unlock prompt.\",\n\ttimeout:\n\t\t\"The native credential backend did not finish within 10 seconds and its process was terminated. Fix or unlock your own native keyring/session outside the CLI; the CLI will not bypass host permissions.\",\n\t\"invalid-response\":\n\t\t\"The native credential backend returned an invalid response. Check your own keyring/session and configuration; no credential output was disclosed.\",\n\t\"read-failed\":\n\t\t\"The native credential backend could not read credentials. Check your own keyring/session availability and permissions; this is not evidence that you are logged out.\",\n\t\"write-failed\":\n\t\t\"The native credential backend could not persist credentials. Check your own keyring/session write permissions and availability; no plaintext fallback is used.\",\n\t\"delete-failed\":\n\t\t\"The native credential backend could not delete its entry. Check your own keyring/session permissions and remove any non-secret preflight probe through that backend if necessary.\",\n};\n\nexport class CliCredentialStoreUnavailableError extends Error {\n\treadonly code = \"CLI_CREDENTIAL_STORE_UNAVAILABLE\";\n\treadonly reason: CredentialStoreFailure;\n\n\tconstructor(\n\t\tproduct: CliProduct,\n\t\treason: CredentialStoreFailure = \"read-failed\",\n\t) {\n\t\tsuper(\n\t\t\t`Secure credential storage is unavailable for the ${product} CLI [CLI_CREDENTIAL_STORE_UNAVAILABLE:${reason}]. ${guidance[reason]}`,\n\t\t);\n\t\tthis.name = \"CliCredentialStoreUnavailableError\";\n\t\tthis.reason = reason;\n\t}\n}\n\n// Classify only; never attach backend output/causes, which may contain secrets.\nexport const classifyCredentialStoreFailure = (\n\tmessage: string,\n\tfallback: CredentialStoreFailure,\n): CredentialStoreFailure => {\n\tif (\n\t\t/libsecret.*(not found|not available|cannot open|load)|dlopen|shared (object|library).*not found/i.test(\n\t\t\tmessage,\n\t\t)\n\t)\n\t\treturn \"missing-library\";\n\tif (\n\t\t/(d-?bus|user bus|session bus).*(denied|not permitted)|(?:denied|not permitted).*(d-?bus|user bus|session bus)/i.test(\n\t\t\tmessage,\n\t\t)\n\t)\n\t\treturn \"bus-denied\";\n\tif (/locked|interaction.*not allowed|user.*cancel/i.test(message))\n\t\treturn \"locked\";\n\tif (\n\t\t/ServiceUnknown|org\\.freedesktop\\.secrets.*(not provided|no owner|not available)|secret.?service.*(unavailable|not running)/i.test(\n\t\t\tmessage,\n\t\t)\n\t)\n\t\treturn \"service-unavailable\";\n\tif (/d-?bus|user bus|session bus|autolaunch/i.test(message))\n\t\treturn \"bus-unavailable\";\n\treturn fallback;\n};\n\nexport class CliCredentialPersistenceError extends Error {\n\treadonly code = \"CLI_CREDENTIAL_PERSISTENCE_FAILED\";\n\tconstructor(\n\t\treadonly remoteRevoked: boolean,\n\t\treadonly localRestored: boolean,\n\t\treadonly phase: \"login\" | \"refresh\",\n\t) {\n\t\tsuper(\n\t\t\t`CLI credentials could not be saved after ${phase} [CLI_CREDENTIAL_PERSISTENCE_FAILED]. ${remoteRevoked ? \"The newly issued session was revoked.\" : \"Remote revocation could not be confirmed; revoke the session in the product's session management before retrying.\"} ${localRestored ? (phase === \"login\" ? \"The previous local credentials were preserved.\" : \"The unusable rotated local credentials were removed; sign in again.\") : \"Local cleanup could not be confirmed. Inspect your own native credential backend before retrying.\"}`,\n\t\t);\n\t\tthis.name = \"CliCredentialPersistenceError\";\n\t}\n}\n\nexport interface CliStorageErrorPayload {\n\tcode:\n\t\t| \"CLI_CREDENTIAL_STORE_UNAVAILABLE\"\n\t\t| \"CLI_CREDENTIAL_PERSISTENCE_FAILED\";\n\tmessage: string;\n\tdetails: Record<string, string | boolean>;\n}\n\nexport const getCliStorageError = (\n\terror: unknown,\n): CliStorageErrorPayload | undefined => {\n\tif (error instanceof CliCredentialStoreUnavailableError)\n\t\treturn {\n\t\t\tcode: error.code,\n\t\t\tmessage: error.message,\n\t\t\tdetails: { reason: error.reason },\n\t\t};\n\tif (error instanceof CliCredentialPersistenceError)\n\t\treturn {\n\t\t\tcode: error.code,\n\t\t\tmessage: error.message,\n\t\t\tdetails: {\n\t\t\t\tremoteRevoked: error.remoteRevoked,\n\t\t\t\tlocalRestored: error.localRestored,\n\t\t\t\tphase: error.phase,\n\t\t\t},\n\t\t};\n\treturn undefined;\n};\n", "import { hostname } from \"node:os\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport {\n\tbeginDeviceAuthorizationResponseSchema,\n\tcreatePkcePair,\n\tdeviceTokenErrorSchema,\n\ttype StoredCliCredentials,\n\ttokenResponseSchema,\n} from \"@go-labs/cli-auth/protocol\";\nimport type { CliCredentialStore } from \"./credential-store\";\nimport { assertBunRuntime } from \"./runtime\";\nimport { CliCredentialPersistenceError } from \"./storage-error\";\n\nexport type FetchLike = (\n\tinput: string | URL | Request,\n\tinit?: RequestInit,\n) => Promise<Response>;\n\nexport const normalizeCliAuthIssuer = (value: string): string => {\n\tconst url = new URL(value);\n\turl.hash = \"\";\n\turl.search = \"\";\n\turl.pathname = url.pathname.replace(/\\/+$/, \"\");\n\treturn url.toString().replace(/\\/+$/, \"\");\n};\n\nexport const isCliCredentialForIssuer = (\n\tcredentials: StoredCliCredentials,\n\tapiBaseUrl: string,\n): boolean => credentials.issuer === normalizeCliAuthIssuer(apiBaseUrl);\n\nconst credentialIssuerError = (issuer: string | undefined): Error =>\n\tissuer\n\t\t? new Error(\n\t\t\t\t\"These CLI credentials belong to a different API URL. Run auth login for this API URL before retrying.\",\n\t\t\t)\n\t\t: new Error(\n\t\t\t\t\"These CLI credentials were created by an older CLI and are not bound to an API URL. Run auth login again.\",\n\t\t\t);\n\nconst assertCredentialIssuer = (\n\tcredentials: StoredCliCredentials,\n\tapiBaseUrl: string,\n): void => {\n\tconst expectedIssuer = normalizeCliAuthIssuer(apiBaseUrl);\n\tif (!credentials.issuer || credentials.issuer !== expectedIssuer) {\n\t\tthrow credentialIssuerError(credentials.issuer);\n\t}\n};\n\nconst postJson = async (\n\tfetchImplementation: FetchLike,\n\turl: string,\n\tbody: unknown,\n\toptions: Pick<RequestInit, \"signal\"> = {},\n): Promise<Response> =>\n\tfetchImplementation(url, {\n\t\tbody: JSON.stringify(body),\n\t\theaders: { \"content-type\": \"application/json\" },\n\t\tmethod: \"POST\",\n\t\t...options,\n\t});\n\nconst readJson = async (response: Response): Promise<unknown> => {\n\ttry {\n\t\treturn await response.json();\n\t} catch {\n\t\tthrow new Error(\n\t\t\t`CLI authentication returned HTTP ${response.status} without valid JSON.`,\n\t\t);\n\t}\n};\n\nconst localCredentialLocks = new WeakMap<CliCredentialStore, Promise<void>>();\n\nconst withCredentialLock = <Result>(\n\tstore: CliCredentialStore,\n\toperation: () => Promise<Result>,\n): Promise<Result> => {\n\tif (store.withCredentialLock) {\n\t\treturn store.withCredentialLock(operation);\n\t}\n\n\tconst previous = localCredentialLocks.get(store) ?? Promise.resolve();\n\tconst pending = previous.then(operation, operation);\n\tconst tail = pending.then(\n\t\t() => undefined,\n\t\t() => undefined,\n\t);\n\tlocalCredentialLocks.set(store, tail);\n\treturn pending.finally(() => {\n\t\tif (localCredentialLocks.get(store) === tail) {\n\t\t\tlocalCredentialLocks.delete(store);\n\t\t}\n\t});\n};\n\nconst toStoredCredentials = (\n\tresponse: ReturnType<typeof tokenResponseSchema.parse>,\n\tissuer: string,\n\tnow: Date,\n): StoredCliCredentials => ({\n\taccessToken: response.accessToken,\n\taccessTokenExpiresAt: new Date(\n\t\tnow.getTime() + response.expiresIn * 1000,\n\t).toISOString(),\n\tissuer,\n\trefreshToken: response.refreshToken,\n\trefreshTokenExpiresAt: new Date(\n\t\tnow.getTime() + response.refreshExpiresIn * 1000,\n\t).toISOString(),\n\tsession: response.session,\n});\n\nexport const openSystemBrowser = async (url: string): Promise<boolean> => {\n\tassertBunRuntime();\n\tconst command =\n\t\tprocess.platform === \"darwin\"\n\t\t\t? [\"open\", url]\n\t\t\t: process.platform === \"win32\"\n\t\t\t\t? [\n\t\t\t\t\t\t\"powershell.exe\",\n\t\t\t\t\t\t\"-NoProfile\",\n\t\t\t\t\t\t\"-NonInteractive\",\n\t\t\t\t\t\t\"-Command\",\n\t\t\t\t\t\t\"Start-Process -FilePath $env:GO_LABS_CLI_VERIFICATION_URI -ErrorAction Stop\",\n\t\t\t\t\t]\n\t\t\t\t: [\"xdg-open\", url];\n\ttry {\n\t\t// PowerShell -Command treats trailing arguments as script text, not $args.\n\t\t// Pass the verification URL as data without interpreting it as code.\n\t\tconst browserProcess = Bun.spawn(command, {\n\t\t\tenv:\n\t\t\t\tprocess.platform === \"win32\"\n\t\t\t\t\t? { ...process.env, GO_LABS_CLI_VERIFICATION_URI: url }\n\t\t\t\t\t: process.env,\n\t\t\tstderr: \"ignore\",\n\t\t\tstdout: \"ignore\",\n\t\t});\n\t\treturn (await browserProcess.exited) === 0;\n\t} catch {\n\t\treturn false;\n\t}\n};\n\nexport interface VerificationDetails {\n\tbrowserOpened: boolean;\n\tuserCode: string;\n\tverificationUriComplete: string;\n}\n\nconst persistLoginCredentials = async ({\n\tstore,\n\tcredentials,\n\tbaseUrl,\n\tfetchImplementation,\n}: {\n\tstore: CliCredentialStore;\n\tcredentials: StoredCliCredentials;\n\tbaseUrl: string;\n\tfetchImplementation: FetchLike;\n}): Promise<void> => {\n\ttry {\n\t\tawait withCredentialLock(store, () =>\n\t\t\tpersistIssuedCredentials({\n\t\t\t\tstore,\n\t\t\t\tcredentials,\n\t\t\t\tapiBaseUrl: baseUrl,\n\t\t\t\tfetch: fetchImplementation,\n\t\t\t\tphase: \"login\",\n\t\t\t}),\n\t\t);\n\t} catch (error) {\n\t\tif (error instanceof CliCredentialPersistenceError) throw error;\n\t\t// Lock acquisition/release may fail after issuance too. Do not\n\t\t// abandon the new session or mutate local state without the lock.\n\t\tthrow new CliCredentialPersistenceError(\n\t\t\tawait revokeIssuedCredentials(fetchImplementation, baseUrl, credentials),\n\t\t\tfalse,\n\t\t\t\"login\",\n\t\t);\n\t}\n};\n\n/** Next polling interval for a device-token error, or throws when terminal. */\nconst nextPollIntervalMs = (errorCode: string, intervalMs: number): number => {\n\tif (errorCode === \"authorization_pending\") return intervalMs;\n\tif (errorCode === \"slow_down\") return intervalMs + 5000;\n\tif (errorCode === \"access_denied\") {\n\t\tthrow new Error(\"CLI authentication was denied in the browser.\");\n\t}\n\tthrow new Error(\"CLI authentication expired. Run auth login again.\");\n};\n\nexport const loginWithBrowser = async ({\n\tapiBaseUrl,\n\tclientName = hostname(),\n\tclientVersion,\n\tfetch: fetchImplementation = globalThis.fetch,\n\tnow = () => new Date(),\n\tonVerification,\n\topenBrowser = openSystemBrowser,\n\tplatform = `${process.platform}-${process.arch}`,\n\tsleep = (milliseconds: number) => Bun.sleep(milliseconds),\n\tstore,\n}: {\n\tapiBaseUrl: string;\n\tclientName?: string;\n\tclientVersion: string;\n\tfetch?: FetchLike;\n\tnow?: () => Date;\n\tonVerification: (details: VerificationDetails) => void;\n\topenBrowser?: (url: string) => Promise<boolean>;\n\tplatform?: string;\n\tsleep?: (milliseconds: number) => Promise<void>;\n\tstore: CliCredentialStore;\n}): Promise<StoredCliCredentials> => {\n\tconst baseUrl = normalizeCliAuthIssuer(apiBaseUrl);\n\t// A read alone cannot establish persistence/rotation/delete capability.\n\tif (store.preflight)\n\t\tawait withCredentialLock(\n\t\t\tstore,\n\t\t\t() => store.preflight?.() ?? Promise.resolve(),\n\t\t);\n\tconst pkce = createPkcePair();\n\tconst beginResponse = await postJson(\n\t\tfetchImplementation,\n\t\t`${baseUrl}/api/cli-auth/device`,\n\t\t{\n\t\t\tclientName,\n\t\t\tclientVersion,\n\t\t\tcodeChallenge: pkce.challenge,\n\t\t\tcodeChallengeMethod: pkce.method,\n\t\t\tplatform,\n\t\t},\n\t);\n\tif (!beginResponse.ok) {\n\t\tthrow new Error(\n\t\t\t`Unable to start CLI browser authentication (HTTP ${beginResponse.status}).`,\n\t\t);\n\t}\n\tconst authorization = beginDeviceAuthorizationResponseSchema.parse(\n\t\tawait readJson(beginResponse),\n\t);\n\tconst browserOpened = await openBrowser(\n\t\tauthorization.verificationUriComplete,\n\t);\n\tonVerification({\n\t\tbrowserOpened,\n\t\tuserCode: authorization.userCode,\n\t\tverificationUriComplete: authorization.verificationUriComplete,\n\t});\n\n\tconst deadline = now().getTime() + authorization.expiresIn * 1000;\n\tlet intervalMs = authorization.interval * 1000;\n\twhile (now().getTime() < deadline) {\n\t\tawait sleep(intervalMs);\n\t\tconst response = await postJson(\n\t\t\tfetchImplementation,\n\t\t\t`${baseUrl}/api/cli-auth/token`,\n\t\t\t{ codeVerifier: pkce.verifier, deviceCode: authorization.deviceCode },\n\t\t);\n\t\tconst payload = await readJson(response);\n\t\tif (response.ok) {\n\t\t\tconst issued = tokenResponseSchema.parse(payload);\n\t\t\tconst credentials = toStoredCredentials(issued, baseUrl, now());\n\t\t\tawait persistLoginCredentials({\n\t\t\t\tstore,\n\t\t\t\tcredentials,\n\t\t\t\tbaseUrl,\n\t\t\t\tfetchImplementation,\n\t\t\t});\n\t\t\treturn credentials;\n\t\t}\n\t\tconst error = deviceTokenErrorSchema.safeParse(payload);\n\t\tif (!error.success) {\n\t\t\tthrow new Error(\n\t\t\t\t`CLI authentication failed with HTTP ${response.status}.`,\n\t\t\t);\n\t\t}\n\t\tintervalMs = nextPollIntervalMs(error.data.error, intervalMs);\n\t}\n\tthrow new Error(\"CLI authentication expired. Run auth login again.\");\n};\n\nconst revokeIssuedCredentials = async (\n\tfetchImplementation: FetchLike,\n\tapiBaseUrl: string,\n\tcredentials: StoredCliCredentials,\n): Promise<boolean> => {\n\ttry {\n\t\tconst response = await postJson(\n\t\t\tfetchImplementation,\n\t\t\t`${normalizeCliAuthIssuer(apiBaseUrl)}/api/cli-auth/revoke`,\n\t\t\t{ refreshToken: credentials.refreshToken },\n\t\t\t{ signal: AbortSignal.timeout(refreshRequestTimeoutMs) },\n\t\t);\n\t\treturn response.ok;\n\t} catch {\n\t\treturn false;\n\t}\n};\n\nconst restoreLoginSnapshot = async (\n\tstore: CliCredentialStore,\n\tcredentials: StoredCliCredentials,\n\tcurrent: StoredCliCredentials | null,\n\tprior: StoredCliCredentials | null,\n): Promise<boolean> => {\n\tif (isDeepStrictEqual(current, prior)) return true;\n\tif (current !== null && current.refreshToken !== credentials.refreshToken) {\n\t\treturn false;\n\t}\n\tif (prior) await store.set(prior);\n\telse await store.delete();\n\treturn isDeepStrictEqual(await store.get(), prior);\n};\n\nconst removeRefreshedCredentials = async (\n\tstore: CliCredentialStore,\n\tcurrent: StoredCliCredentials | null,\n): Promise<boolean> => {\n\tif (current) await store.delete();\n\treturn (await store.get()) === null;\n};\n\nconst restoreLocalCredentials = async ({\n\tstore,\n\tcredentials,\n\tphase,\n\tprior,\n}: {\n\tstore: CliCredentialStore;\n\tcredentials: StoredCliCredentials;\n\tphase: \"login\" | \"refresh\";\n\tprior?: StoredCliCredentials | null;\n}): Promise<boolean> => {\n\ttry {\n\t\tconst current = await store.get();\n\t\tif (phase === \"login\" && prior !== undefined) {\n\t\t\treturn await restoreLoginSnapshot(store, credentials, current, prior);\n\t\t}\n\t\tif (\n\t\t\tphase === \"refresh\" &&\n\t\t\t(!current ||\n\t\t\t\tcurrent.refreshToken === credentials.refreshToken ||\n\t\t\t\tcurrent.refreshToken === prior?.refreshToken)\n\t\t) {\n\t\t\treturn await removeRefreshedCredentials(store, current);\n\t\t}\n\t} catch {\n\t\t/* The backend may still be unavailable. */\n\t}\n\treturn false;\n};\n\n// This operation runs under the credential lock. On login, restore only the\n// snapshot read under that lock. A rotated refresh token can NEVER be restored:\n// its predecessor has been consumed, so remove it to prevent a replay.\nconst persistIssuedCredentials = async ({\n\tstore,\n\tcredentials,\n\tprevious,\n\tapiBaseUrl,\n\tfetch: fetchImplementation,\n\tphase,\n}: {\n\tstore: CliCredentialStore;\n\tcredentials: StoredCliCredentials;\n\tprevious?: StoredCliCredentials | null;\n\tapiBaseUrl: string;\n\tfetch: FetchLike;\n\tphase: \"login\" | \"refresh\";\n}): Promise<void> => {\n\tlet prior = previous;\n\ttry {\n\t\tif (phase === \"login\") prior = await store.get();\n\t\tawait store.set(credentials);\n\t\tconst saved = await store.get();\n\t\tif (!isDeepStrictEqual(saved, credentials))\n\t\t\tthrow new Error(\"Credential write could not be verified\");\n\t\treturn;\n\t} catch {\n\t\tconst remoteRevoked = await revokeIssuedCredentials(\n\t\t\tfetchImplementation,\n\t\t\tapiBaseUrl,\n\t\t\tcredentials,\n\t\t);\n\t\tconst localRestored = await restoreLocalCredentials({\n\t\t\tstore,\n\t\t\tcredentials,\n\t\t\tphase,\n\t\t\tprior,\n\t\t});\n\t\tthrow new CliCredentialPersistenceError(\n\t\t\tremoteRevoked,\n\t\t\tlocalRestored,\n\t\t\tphase,\n\t\t);\n\t}\n};\n\nconst refreshes = new WeakMap<CliCredentialStore, Promise<string>>();\nconst refreshRequestTimeoutMs = 30_000;\n\nconst isInvalidGrantResponse = (payload: unknown): boolean => {\n\tconst parsed = deviceTokenErrorSchema.safeParse(payload);\n\treturn parsed.success && parsed.data.error === \"invalid_grant\";\n};\n\nconst readJsonOrNull = async (response: Response): Promise<unknown | null> => {\n\ttry {\n\t\treturn await response.json();\n\t} catch {\n\t\treturn null;\n\t}\n};\n\nconst deleteInvalidCredentials = async (\n\tstore: CliCredentialStore,\n\tcredentials: StoredCliCredentials,\n): Promise<void> => {\n\tconst current = await store.get();\n\tif (!current) return;\n\tif (\n\t\tcurrent.issuer === credentials.issuer &&\n\t\tcurrent.refreshToken === credentials.refreshToken\n\t) {\n\t\tawait store.delete();\n\t}\n};\n\nconst refreshAccessToken = async ({\n\tapiBaseUrl,\n\tcredentials,\n\tfetch: fetchImplementation,\n\tnow,\n\tstore,\n}: {\n\tapiBaseUrl: string;\n\tcredentials: StoredCliCredentials;\n\tfetch: FetchLike;\n\tnow: () => Date;\n\tstore: CliCredentialStore;\n}): Promise<string> => {\n\tassertCredentialIssuer(credentials, apiBaseUrl);\n\tlet response: Response;\n\ttry {\n\t\tresponse = await postJson(\n\t\t\tfetchImplementation,\n\t\t\t`${normalizeCliAuthIssuer(apiBaseUrl)}/api/cli-auth/refresh`,\n\t\t\t{ refreshToken: credentials.refreshToken },\n\t\t\t{ signal: AbortSignal.timeout(refreshRequestTimeoutMs) },\n\t\t);\n\t} catch {\n\t\tthrow new Error(\n\t\t\t\"Unable to refresh the CLI session because the API could not be reached. Credentials were kept; retry the command.\",\n\t\t);\n\t}\n\tif (!response.ok) {\n\t\tconst payload = await readJsonOrNull(response);\n\t\tif (isInvalidGrantResponse(payload)) {\n\t\t\tawait deleteInvalidCredentials(store, credentials);\n\t\t\tthrow new Error(\n\t\t\t\t\"The CLI session expired or was revoked. Run auth login again.\",\n\t\t\t);\n\t\t}\n\t\tthrow new Error(\n\t\t\t`Unable to refresh the CLI session (HTTP ${response.status}). Credentials were kept; retry the command.`,\n\t\t);\n\t}\n\tconst payload = await readJsonOrNull(response);\n\tif (payload === null) {\n\t\tthrow new Error(\n\t\t\t\"Unable to refresh the CLI session because the API returned malformed JSON. Credentials were kept; retry the command.\",\n\t\t);\n\t}\n\tlet issued: ReturnType<typeof tokenResponseSchema.parse>;\n\ttry {\n\t\tissued = tokenResponseSchema.parse(payload);\n\t} catch {\n\t\tthrow new Error(\n\t\t\t\"Unable to refresh the CLI session because the API returned invalid credentials. Credentials were kept; retry the command.\",\n\t\t);\n\t}\n\tconst stored = toStoredCredentials(\n\t\tissued,\n\t\tnormalizeCliAuthIssuer(apiBaseUrl),\n\t\tnow(),\n\t);\n\tawait persistIssuedCredentials({\n\t\tstore,\n\t\tcredentials: stored,\n\t\tprevious: credentials,\n\t\tapiBaseUrl,\n\t\tfetch: fetchImplementation,\n\t\tphase: \"refresh\",\n\t});\n\treturn stored.accessToken;\n};\n\nconst refreshWithCurrentCredentials = async ({\n\tapiBaseUrl,\n\tfetch: fetchImplementation,\n\tnow,\n\tstore,\n}: {\n\tapiBaseUrl: string;\n\tfetch: FetchLike;\n\tnow: () => Date;\n\tstore: CliCredentialStore;\n}): Promise<string> => {\n\tconst credentials = await store.get();\n\tif (!credentials) throw new Error(\"Not authenticated. Run auth login first.\");\n\tassertCredentialIssuer(credentials, apiBaseUrl);\n\tif (Date.parse(credentials.accessTokenExpiresAt) - now().getTime() > 60_000) {\n\t\treturn credentials.accessToken;\n\t}\n\treturn refreshAccessToken({\n\t\tapiBaseUrl,\n\t\tcredentials,\n\t\tfetch: fetchImplementation,\n\t\tnow,\n\t\tstore,\n\t});\n};\n\nexport const getAuthenticatedAccessToken = async ({\n\tapiBaseUrl,\n\tfetch: fetchImplementation = globalThis.fetch,\n\tnow = () => new Date(),\n\tstore,\n}: {\n\tapiBaseUrl: string;\n\tfetch?: FetchLike;\n\tnow?: () => Date;\n\tstore: CliCredentialStore;\n}): Promise<string> => {\n\tconst credentials = await store.get();\n\tif (!credentials) throw new Error(\"Not authenticated. Run auth login first.\");\n\tassertCredentialIssuer(credentials, apiBaseUrl);\n\tif (Date.parse(credentials.accessTokenExpiresAt) - now().getTime() > 60_000) {\n\t\treturn credentials.accessToken;\n\t}\n\tconst existing = refreshes.get(store);\n\tif (existing) return existing;\n\tconst refreshOperation = () =>\n\t\twithCredentialLock(store, () =>\n\t\t\trefreshWithCurrentCredentials({\n\t\t\t\tapiBaseUrl,\n\t\t\t\tfetch: fetchImplementation,\n\t\t\t\tnow,\n\t\t\t\tstore,\n\t\t\t}),\n\t\t);\n\tconst refresh = refreshOperation().finally(() => refreshes.delete(store));\n\trefreshes.set(store, refresh);\n\treturn refresh;\n};\n\nexport const logoutCliSession = async ({\n\tapiBaseUrl,\n\tfetch: fetchImplementation = globalThis.fetch,\n\tstore,\n}: {\n\tapiBaseUrl: string;\n\tfetch?: FetchLike;\n\tstore: CliCredentialStore;\n}): Promise<{ remoteRevoked: boolean }> => {\n\tconst issuer = normalizeCliAuthIssuer(apiBaseUrl);\n\treturn withCredentialLock(store, async () => {\n\t\tconst credentials = await store.get();\n\t\tlet remoteRevoked = credentials === null;\n\t\tif (credentials) {\n\t\t\ttry {\n\t\t\t\tassertCredentialIssuer(credentials, apiBaseUrl);\n\t\t\t\tconst response = await postJson(\n\t\t\t\t\tfetchImplementation,\n\t\t\t\t\t`${issuer}/api/cli-auth/revoke`,\n\t\t\t\t\t{ refreshToken: credentials.refreshToken },\n\t\t\t\t\t{ signal: AbortSignal.timeout(refreshRequestTimeoutMs) },\n\t\t\t\t);\n\t\t\t\tremoteRevoked = response.ok;\n\t\t\t} catch {\n\t\t\t\tremoteRevoked = false;\n\t\t\t}\n\t\t}\n\t\tawait store.delete();\n\t\treturn { remoteRevoked };\n\t});\n};\n", "import { readFileSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { basename, resolve } from \"node:path\";\nimport {\n\ttype CliCredentialStore,\n\tcreateBunCredentialStore,\n\tgetAuthenticatedAccessToken,\n\tisCliCredentialForIssuer,\n\tloginWithBrowser,\n\tlogoutCliSession,\n} from \"@go-labs/cli-auth/client\";\nimport { activeEventTypeSchema } from \"@go-labs/event-tech-validators/event-type.schema\";\nimport {\n\tapi,\n\tconfigureEventTechAccessToken,\n\tconfigureEventTechApiBaseUrl,\n\tconfigureEventTechApiFromEnvironment,\n\tgetEventTechApiBaseUrl,\n\ttype RouterInputs,\n} from \"./api-client.js\";\nimport {\n\tassertOnlyFlags,\n\tassertPositionalCount,\n\tassertStateChangeTarget,\n\tgetOptionalFlag,\n\tgetRequiredFlag,\n\ttype ParsedArguments,\n\tparseArguments,\n\tparseBoundedInteger,\n\tparseNonnegativeInteger,\n\tparsePositiveInteger,\n\treadInlineOrFile,\n} from \"./arguments.js\";\nimport { usage } from \"./commands/index.js\";\nimport { runLuckyDrawSetupCommand } from \"./commands/lucky-draw-setup.js\";\nimport { runPassportCommand } from \"./commands/passport.js\";\nimport { runStaffRedemptionCommand } from \"./commands/staff-redemption.js\";\nimport {\n\tlistRegistryCommands,\n\trunRegistryCommand,\n} from \"./registry/run-registry-command.js\";\nimport {\n\ttype CliRuntime,\n\tCliUsageError,\n\tprocessRuntime,\n\twriteError,\n\twriteSuccess,\n} from \"./runtime/index.js\";\n\ntype EventListInput = RouterInputs[\"event\"][\"getEventsByOrgId\"];\ntype EventCreateInput = RouterInputs[\"event\"][\"createEvent\"];\ntype OrganizationCreateInput =\n\tRouterInputs[\"admin\"][\"organization\"][\"createOrganization\"];\ntype PreDrawPrizesInput = RouterInputs[\"event\"][\"luckyDraw\"][\"preDrawPrizes\"];\ntype LuckyDrawParticipantReplacementInput =\n\tRouterInputs[\"event\"][\"luckyDraw\"][\"createLuckyDrawParticipant\"];\ntype LuckyDrawParticipantListInput =\n\tRouterInputs[\"event\"][\"luckyDraw\"][\"getLuckyDrawParticipantsByEventId\"];\ntype EventAppearanceUpdateInput =\n\tRouterInputs[\"event\"][\"updateEventAppearance\"];\ntype PhotoWallDisplayInput =\n\tRouterInputs[\"event\"][\"photoWall\"][\"getPhotoWallDisplayItems\"];\n\nconst getInstalledCliVersion = (): string => {\n\ttry {\n\t\tconst packageJson = JSON.parse(\n\t\t\treadFileSync(resolve(import.meta.dir, \"../package.json\"), \"utf8\"),\n\t\t) as { version?: unknown };\n\t\treturn typeof packageJson.version === \"string\"\n\t\t\t? packageJson.version\n\t\t\t: \"unknown\";\n\t} catch {\n\t\treturn \"unknown\";\n\t}\n};\n\ntype JsonObject = Record<string, unknown>;\n\nconst parseJsonObject = (value: string, name: string): JsonObject => {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(value) as unknown;\n\t} catch {\n\t\tthrow new CliUsageError(`--${name} must be valid JSON.`);\n\t}\n\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n\t\tthrow new CliUsageError(`--${name} must be a JSON object.`);\n\t}\n\treturn parsed as JsonObject;\n};\n\nconst parseAppearance = (\n\tvalue: string,\n): NonNullable<EventAppearanceUpdateInput[\"appearance\"]> =>\n\tparseJsonObject(value, \"appearance\") as NonNullable<\n\t\tEventAppearanceUpdateInput[\"appearance\"]\n\t>;\n\nconst parseCursor = (\n\tvalue: string,\n): NonNullable<PhotoWallDisplayInput[\"cursor\"]> => {\n\tconst parsed = parseJsonObject(value, \"cursor\");\n\tif (typeof parsed.id !== \"string\" || parsed.id.length === 0) {\n\t\tthrow new CliUsageError(\"--cursor.id must be a non-empty string.\");\n\t}\n\tif (typeof parsed.createdAt !== \"string\") {\n\t\tthrow new CliUsageError(\"--cursor.createdAt must be an ISO date string.\");\n\t}\n\tconst createdAt = new Date(parsed.createdAt);\n\tif (Number.isNaN(createdAt.getTime())) {\n\t\tthrow new CliUsageError(\"--cursor.createdAt must be a valid date.\");\n\t}\n\treturn { createdAt, id: parsed.id };\n};\n\nconst parseRetainedIds = (value: string): string[] => {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(value) as unknown;\n\t} catch {\n\t\tthrow new CliUsageError(\"--retained-ids must be valid JSON.\");\n\t}\n\tif (!Array.isArray(parsed)) {\n\t\tthrow new CliUsageError(\"--retained-ids must be a JSON array.\");\n\t}\n\tif (\n\t\tparsed.length > 100 ||\n\t\tparsed.some((id) => typeof id !== \"string\" || id.length === 0)\n\t) {\n\t\tthrow new CliUsageError(\n\t\t\t\"--retained-ids must contain at most 100 non-empty strings.\",\n\t\t);\n\t}\n\treturn parsed;\n};\n\nconst luckyDrawParticipantFields = new Set([\"email\", \"luckyDrawId\", \"name\"]);\n\ntype LuckyDrawParticipantInput =\n\tLuckyDrawParticipantReplacementInput[\"participants\"][number];\n\nconst asParticipantRecord = (\n\tparticipant: unknown,\n\tindex: number,\n): Record<string, unknown> => {\n\tif (\n\t\ttypeof participant !== \"object\" ||\n\t\tparticipant === null ||\n\t\tArray.isArray(participant)\n\t) {\n\t\tthrow new CliUsageError(`--participants[${index}] must be an object.`);\n\t}\n\tif (\n\t\tObject.keys(participant).some((key) => !luckyDrawParticipantFields.has(key))\n\t) {\n\t\tthrow new CliUsageError(\n\t\t\t`--participants[${index}] contains an unsupported field.`,\n\t\t);\n\t}\n\treturn participant as Record<string, unknown>;\n};\n\nconst readParticipantField = (\n\tparticipant: Record<string, unknown>,\n\tkey: string,\n): unknown => (key in participant ? participant[key] : undefined);\n\nconst parseLuckyDrawParticipant = (\n\tparticipant: unknown,\n\tindex: number,\n): LuckyDrawParticipantInput => {\n\tconst record = asParticipantRecord(participant, index);\n\tconst luckyDrawId = readParticipantField(record, \"luckyDrawId\");\n\tconst name = readParticipantField(record, \"name\");\n\tconst email = readParticipantField(record, \"email\");\n\tif (typeof luckyDrawId !== \"string\") {\n\t\tthrow new CliUsageError(\n\t\t\t`--participants[${index}].luckyDrawId must be a string.`,\n\t\t);\n\t}\n\tif (name !== undefined && typeof name !== \"string\") {\n\t\tthrow new CliUsageError(`--participants[${index}].name must be a string.`);\n\t}\n\tif (email !== undefined && email !== null && typeof email !== \"string\") {\n\t\tthrow new CliUsageError(\n\t\t\t`--participants[${index}].email must be a string or null.`,\n\t\t);\n\t}\n\treturn {\n\t\tluckyDrawId,\n\t\t...(name === undefined ? {} : { name }),\n\t\t...(email === undefined ? {} : { email }),\n\t};\n};\n\nconst parseLuckyDrawParticipants = (\n\tvalue: string,\n): LuckyDrawParticipantReplacementInput[\"participants\"] => {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(value);\n\t} catch {\n\t\tthrow new CliUsageError(\"--participants must be valid JSON.\");\n\t}\n\tif (!Array.isArray(parsed)) {\n\t\tthrow new CliUsageError(\"--participants must be a JSON array.\");\n\t}\n\n\treturn parsed.map(parseLuckyDrawParticipant);\n};\n\nconst parseAppearanceMediaType = (value: string): \"image\" | \"video\" => {\n\tif (value === \"image\" || value === \"video\") return value;\n\tthrow new CliUsageError(\"--media-type must be one of: image, video.\");\n};\n\nconst eventStatuses = [\"DRAFT\", \"ONGOING\", \"COMPLETED\", \"ALL\"] as const;\nconst archiveStatuses = [\"active\", \"archived\", \"all\"] as const;\n\nconst parseEventListStatus = (value: string): EventListInput[\"status\"] => {\n\tif (!eventStatuses.some((status) => status === value)) {\n\t\tthrow new CliUsageError(\n\t\t\t`--status must be one of: ${eventStatuses.join(\", \")}.`,\n\t\t);\n\t}\n\treturn value as EventListInput[\"status\"];\n};\n\nconst parseArchiveStatus = (value: string): EventListInput[\"archiveStatus\"] => {\n\tif (!archiveStatuses.some((status) => status === value)) {\n\t\tthrow new CliUsageError(\n\t\t\t`--archive-status must be one of: ${archiveStatuses.join(\", \")}.`,\n\t\t);\n\t}\n\treturn value as EventListInput[\"archiveStatus\"];\n};\n\nconst parseCreatableEventType = (value: string): EventCreateInput[\"type\"] => {\n\tconst result = activeEventTypeSchema.safeParse(value);\n\tif (!result.success) {\n\t\tthrow new CliUsageError(\n\t\t\t`--type must be one of: ${activeEventTypeSchema.options.join(\", \")}.`,\n\t\t);\n\t}\n\treturn result.data;\n};\n\nconst parseEventTypeList = (\n\tvalue: string,\n): NonNullable<OrganizationCreateInput[\"allowedEventTypes\"]> => {\n\tconst types = value.split(\",\").map((type) => type.trim());\n\treturn [...new Set(types)].map((type) => {\n\t\tconst result = activeEventTypeSchema.safeParse(type);\n\t\tif (!result.success) {\n\t\t\tthrow new CliUsageError(\n\t\t\t\t`--allowed-event-types entries must be one of: ${activeEventTypeSchema.options.join(\", \")}.`,\n\t\t\t);\n\t\t}\n\t\treturn result.data;\n\t});\n};\n\nconst parseIsoDateTime = (value: string, name: string): Date => {\n\tif (!/^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d/.test(value)) {\n\t\tthrow new CliUsageError(\n\t\t\t`--${name} must be an ISO 8601 date-time such as 2026-11-20T18:00:00+08:00.`,\n\t\t);\n\t}\n\tconst parsed = new Date(value);\n\tif (Number.isNaN(parsed.getTime())) {\n\t\tthrow new CliUsageError(`--${name} must be a valid date-time.`);\n\t}\n\treturn parsed;\n};\n\ninterface CommandContext {\n\tparsed: ParsedArguments;\n\truntime: CliRuntime;\n\tcredentialStore: CliCredentialStore;\n\tapiBaseUrl: string;\n\tcliVersion: string;\n\tensureAuthentication: () => Promise<void>;\n}\n\ntype CommandHandler = (context: CommandContext) => Promise<void>;\n\nconst commandKey = (action?: string, subAction?: string): string =>\n\tJSON.stringify([action ?? null, subAction ?? null]);\n\nconst runAuthLogin: CommandHandler = async ({\n\tparsed,\n\truntime,\n\tcredentialStore,\n\tapiBaseUrl,\n\tcliVersion,\n}) => {\n\tassertPositionalCount(parsed, 2);\n\tassertOnlyFlags(parsed, [\"no-browser\"]);\n\tconst credentials = await loginWithBrowser({\n\t\tapiBaseUrl,\n\t\tclientVersion: cliVersion,\n\t\tonVerification: ({ browserOpened, userCode, verificationUriComplete }) => {\n\t\t\truntime.stderr.write(\n\t\t\t\t`${browserOpened ? \"Opened\" : \"Open\"} ${verificationUriComplete}\\nCode: ${userCode}\\nWaiting for approval…\\n`,\n\t\t\t);\n\t\t},\n\t\t...(parsed.flags.get(\"no-browser\") === true\n\t\t\t? { openBrowser: async () => false }\n\t\t\t: {}),\n\t\tstore: credentialStore,\n\t});\n\twriteSuccess(runtime, {\n\t\tauthenticated: true,\n\t\tsession: credentials.session,\n\t\tstorage: \"Bun.secrets\",\n\t});\n};\n\nconst runAuthStatus: CommandHandler = async ({\n\tparsed,\n\truntime,\n\tcredentialStore,\n\tapiBaseUrl,\n}) => {\n\tassertPositionalCount(parsed, 2);\n\tassertOnlyFlags(parsed, []);\n\tconst credentials = await credentialStore.get();\n\twriteSuccess(\n\t\truntime,\n\t\tcredentials && isCliCredentialForIssuer(credentials, apiBaseUrl)\n\t\t\t? {\n\t\t\t\t\tauthenticated: true,\n\t\t\t\t\taccessTokenExpiresAt: credentials.accessTokenExpiresAt,\n\t\t\t\t\trefreshTokenExpiresAt: credentials.refreshTokenExpiresAt,\n\t\t\t\t\tsession: credentials.session,\n\t\t\t\t\tstorage: \"Bun.secrets\",\n\t\t\t\t}\n\t\t\t: { authenticated: false, storage: \"Bun.secrets\" },\n\t);\n};\n\nconst runAuthLogout: CommandHandler = async ({\n\tparsed,\n\truntime,\n\tcredentialStore,\n\tapiBaseUrl,\n}) => {\n\tassertPositionalCount(parsed, 2);\n\tassertOnlyFlags(parsed, []);\n\twriteSuccess(runtime, {\n\t\tloggedOut: true,\n\t\t...(await logoutCliSession({ apiBaseUrl, store: credentialStore })),\n\t});\n};\n\nconst runAuthWhoami: CommandHandler = async ({\n\tparsed,\n\truntime,\n\tensureAuthentication,\n}) => {\n\tassertPositionalCount(parsed, 2);\n\tassertOnlyFlags(parsed, []);\n\tawait ensureAuthentication();\n\twriteSuccess(runtime, await api.auth.whoami.query(undefined));\n};\n\nconst runOrganizationList: CommandHandler = async ({\n\tparsed,\n\truntime,\n\tensureAuthentication,\n}) => {\n\tassertPositionalCount(parsed, 2);\n\tassertOnlyFlags(parsed, []);\n\tawait ensureAuthentication();\n\twriteSuccess(\n\t\truntime,\n\t\tawait api.organization.getOrganizationsForUser.query(undefined),\n\t);\n};\n\nconst runOrganizationGet: CommandHandler = async ({\n\tparsed,\n\truntime,\n\tensureAuthentication,\n}) => {\n\tassertPositionalCount(parsed, 2);\n\tassertOnlyFlags(parsed, [\"organization-id\"]);\n\tawait ensureAuthentication();\n\twriteSuccess(\n\t\truntime,\n\t\tawait api.organization.getOrganizationById.query({\n\t\t\torganizationId: getRequiredFlag(parsed, \"organization-id\"),\n\t\t}),\n\t);\n};\n\nconst runOrganizationCreate: CommandHandler = async ({\n\tparsed,\n\truntime,\n\tensureAuthentication,\n}) => {\n\tassertPositionalCount(parsed, 2);\n\tassertOnlyFlags(parsed, [\"name\", \"owner-email\", \"allowed-event-types\"]);\n\tconst allowedEventTypes = getOptionalFlag(parsed, \"allowed-event-types\");\n\tconst input: OrganizationCreateInput = {\n\t\tname: getRequiredFlag(parsed, \"name\"),\n\t\townerEmail: getRequiredFlag(parsed, \"owner-email\"),\n\t\t...(allowedEventTypes === undefined\n\t\t\t? {}\n\t\t\t: { allowedEventTypes: parseEventTypeList(allowedEventTypes) }),\n\t};\n\tawait ensureAuthentication();\n\twriteSuccess(\n\t\truntime,\n\t\tawait api.admin.organization.createOrganization.mutate(input),\n\t);\n};\n\nconst runEventCreate: CommandHandler = async ({\n\tparsed,\n\truntime,\n\tensureAuthentication,\n}) => {\n\tassertPositionalCount(parsed, 2);\n\tassertOnlyFlags(parsed, [\n\t\t\"organization-id\",\n\t\t\"name\",\n\t\t\"type\",\n\t\t\"start\",\n\t\t\"end\",\n\t\t\"location\",\n\t]);\n\tconst end = getOptionalFlag(parsed, \"end\");\n\tconst input: EventCreateInput = {\n\t\torganizationId: getRequiredFlag(parsed, \"organization-id\"),\n\t\tname: getRequiredFlag(parsed, \"name\"),\n\t\ttype: parseCreatableEventType(getRequiredFlag(parsed, \"type\")),\n\t\tlocation: getRequiredFlag(parsed, \"location\"),\n\t\teventDateRange: {\n\t\t\tfrom: parseIsoDateTime(getRequiredFlag(parsed, \"start\"), \"start\"),\n\t\t\t...(end === undefined ? {} : { to: parseIsoDateTime(end, \"end\") }),\n\t\t},\n\t};\n\tawait ensureAuthentication();\n\twriteSuccess(runtime, await api.event.createEvent.mutate(input));\n};\n\nconst runEventList: CommandHandler = async ({\n\tparsed,\n\truntime,\n\tensureAuthentication,\n}) => {\n\tassertPositionalCount(parsed, 2);\n\tassertOnlyFlags(parsed, [\n\t\t\"organization-id\",\n\t\t\"page\",\n\t\t\"per-page\",\n\t\t\"name\",\n\t\t\"status\",\n\t\t\"archive-status\",\n\t]);\n\tconst input: EventListInput = {\n\t\torganizationId: getRequiredFlag(parsed, \"organization-id\"),\n\t\tpage: parsePositiveInteger(getOptionalFlag(parsed, \"page\") ?? \"1\", \"page\"),\n\t\tperPage: parsePositiveInteger(\n\t\t\tgetOptionalFlag(parsed, \"per-page\") ?? \"20\",\n\t\t\t\"per-page\",\n\t\t),\n\t\tname: getOptionalFlag(parsed, \"name\") ?? \"\",\n\t\tstatus: parseEventListStatus(getOptionalFlag(parsed, \"status\") ?? \"ALL\"),\n\t\tarchiveStatus: parseArchiveStatus(\n\t\t\tgetOptionalFlag(parsed, \"archive-status\") ?? \"active\",\n\t\t),\n\t};\n\tawait ensureAuthentication();\n\twriteSuccess(runtime, await api.event.getEventsByOrgId.query(input));\n};\n\nconst runEventGet: CommandHandler = async ({\n\tparsed,\n\truntime,\n\tensureAuthentication,\n}) => {\n\tassertPositionalCount(parsed, 2);\n\tassertOnlyFlags(parsed, [\"event-id\"]);\n\tawait ensureAuthentication();\n\twriteSuccess(\n\t\truntime,\n\t\tawait api.event.getEventForNav.query({\n\t\t\teventId: getRequiredFlag(parsed, \"event-id\"),\n\t\t}),\n\t);\n};\n\nconst runEventAppearanceGet: CommandHandler = async ({\n\tparsed,\n\truntime,\n\tensureAuthentication,\n}) => {\n\tassertPositionalCount(parsed, 3);\n\tassertOnlyFlags(parsed, [\"event-id\", \"public\"]);\n\tconst eventId = getRequiredFlag(parsed, \"event-id\");\n\tif (parsed.flags.get(\"public\") === true) {\n\t\twriteSuccess(\n\t\t\truntime,\n\t\t\tawait api.public.getEventAppearance.query({ eventId }),\n\t\t);\n\t\treturn;\n\t}\n\tawait ensureAuthentication();\n\twriteSuccess(\n\t\truntime,\n\t\tawait api.event.getEventAppearance.query({\n\t\t\teventId,\n\t\t}),\n\t);\n};\n\nconst runEventAppearanceUpdate: CommandHandler = async ({\n\tparsed,\n\truntime,\n\tensureAuthentication,\n}) => {\n\tassertPositionalCount(parsed, 3);\n\tassertOnlyFlags(parsed, [\n\t\t\"event-id\",\n\t\t\"appearance-version\",\n\t\t\"appearance\",\n\t\t\"reset\",\n\t]);\n\tconst reset =\n\t\tparsed.positionals[2] === \"reset\" || parsed.flags.get(\"reset\") === true;\n\tconst appearanceValue = getOptionalFlag(parsed, \"appearance\");\n\tif (reset && appearanceValue !== undefined) {\n\t\tthrow new CliUsageError(\"Use either --appearance or --reset, not both.\");\n\t}\n\tif (!reset && appearanceValue === undefined) {\n\t\tthrow new CliUsageError(\n\t\t\t\"--appearance is required unless --reset is provided.\",\n\t\t);\n\t}\n\tconst input: EventAppearanceUpdateInput = {\n\t\teventId: getRequiredFlag(parsed, \"event-id\"),\n\t\tappearanceVersion: parseNonnegativeInteger(\n\t\t\tgetRequiredFlag(parsed, \"appearance-version\"),\n\t\t\t\"appearance-version\",\n\t\t),\n\t\tappearance: reset ? null : parseAppearance(appearanceValue as string),\n\t};\n\tawait ensureAuthentication();\n\twriteSuccess(runtime, await api.event.updateEventAppearance.mutate(input));\n};\n\nconst runEventAppearanceUpload: CommandHandler = async ({\n\tparsed,\n\truntime,\n\tensureAuthentication,\n}) => {\n\tassertPositionalCount(parsed, 3);\n\tassertOnlyFlags(parsed, [\"event-id\", \"file\", \"content-type\", \"media-type\"]);\n\tconst eventId = getRequiredFlag(parsed, \"event-id\");\n\tconst filePath = getRequiredFlag(parsed, \"file\");\n\tconst contentType = getRequiredFlag(parsed, \"content-type\");\n\tconst mediaType = parseAppearanceMediaType(\n\t\tgetRequiredFlag(parsed, \"media-type\"),\n\t);\n\tconst file = await readFile(filePath);\n\tawait ensureAuthentication();\n\tconst signed = await api.attachment.getPresignedUrlToUpload.mutate({\n\t\tfolder: `event-appearance/${mediaType === \"image\" ? \"images\" : \"videos\"}`,\n\t\tfileName: basename(filePath),\n\t\tcontentType,\n\t\tsize: file.byteLength,\n\t\teventId,\n\t});\n\tconst uploadResponse = await fetch(signed.uploadUrl, {\n\t\tmethod: \"PUT\",\n\t\theaders: { \"content-type\": contentType },\n\t\tbody: file,\n\t});\n\tif (!uploadResponse.ok) {\n\t\tthrow new Error(\n\t\t\t`Appearance media upload failed with HTTP ${uploadResponse.status}.`,\n\t\t);\n\t}\n\twriteSuccess(runtime, signed);\n};\n\nconst runPhotoWallDisplayItems: CommandHandler = async ({\n\tparsed,\n\truntime,\n\tensureAuthentication,\n}) => {\n\tassertPositionalCount(parsed, 3);\n\tassertOnlyFlags(parsed, [\"event-id\", \"limit\", \"cursor\", \"retained-ids\"]);\n\tconst cursorValue = getOptionalFlag(parsed, \"cursor\");\n\tconst retainedIdsValue = getOptionalFlag(parsed, \"retained-ids\");\n\tconst input: PhotoWallDisplayInput = {\n\t\teventId: getRequiredFlag(parsed, \"event-id\"),\n\t\tlimit: parseBoundedInteger(\n\t\t\tgetOptionalFlag(parsed, \"limit\") ?? \"30\",\n\t\t\t\"limit\",\n\t\t\t1,\n\t\t\t60,\n\t\t),\n\t\t...(cursorValue === undefined ? {} : { cursor: parseCursor(cursorValue) }),\n\t\tretainedIds:\n\t\t\tretainedIdsValue === undefined ? [] : parseRetainedIds(retainedIdsValue),\n\t};\n\tawait ensureAuthentication();\n\twriteSuccess(\n\t\truntime,\n\t\tawait api.event.photoWall.getPhotoWallDisplayItems.query(input),\n\t);\n};\n\nconst runLuckyDrawPreDraw: CommandHandler = async ({\n\tparsed,\n\truntime,\n\tensureAuthentication,\n}) => {\n\tassertPositionalCount(parsed, 2);\n\tassertOnlyFlags(parsed, [\"event-id\", \"prize-count\"]);\n\tconst input: PreDrawPrizesInput = {\n\t\teventId: getRequiredFlag(parsed, \"event-id\"),\n\t\tprizeCount: parsePositiveInteger(\n\t\t\tgetRequiredFlag(parsed, \"prize-count\"),\n\t\t\t\"prize-count\",\n\t\t),\n\t};\n\tawait ensureAuthentication();\n\twriteSuccess(runtime, await api.event.luckyDraw.preDrawPrizes.mutate(input));\n};\n\nconst runLuckyDrawParticipantsReplace: CommandHandler = async ({\n\tparsed,\n\truntime,\n\tensureAuthentication,\n}) => {\n\tassertPositionalCount(parsed, 3);\n\tassertOnlyFlags(parsed, [\n\t\t\"event-id\",\n\t\t\"participants\",\n\t\t\"participants-file\",\n\t\t\"allow-state-change\",\n\t\t\"target\",\n\t]);\n\tconst eventId = getRequiredFlag(parsed, \"event-id\");\n\tassertStateChangeTarget(parsed, eventId);\n\tconst input: LuckyDrawParticipantReplacementInput = {\n\t\teventId,\n\t\tparticipants: parseLuckyDrawParticipants(\n\t\t\tawait readInlineOrFile(parsed, \"participants\", \"participants-file\"),\n\t\t),\n\t};\n\tawait ensureAuthentication();\n\twriteSuccess(\n\t\truntime,\n\t\tawait api.event.luckyDraw.createLuckyDrawParticipant.mutate(input),\n\t);\n};\n\nconst runLuckyDrawParticipantsList: CommandHandler = async ({\n\tparsed,\n\truntime,\n\tensureAuthentication,\n}) => {\n\tassertPositionalCount(parsed, 3);\n\tassertOnlyFlags(parsed, [\"event-id\", \"page\", \"per-page\"]);\n\tconst input: LuckyDrawParticipantListInput = {\n\t\teventId: getRequiredFlag(parsed, \"event-id\"),\n\t\tpage: parsePositiveInteger(getOptionalFlag(parsed, \"page\") ?? \"1\", \"page\"),\n\t\tperPage: parseBoundedInteger(\n\t\t\tgetOptionalFlag(parsed, \"per-page\") ?? \"100\",\n\t\t\t\"per-page\",\n\t\t\t1,\n\t\t\t100,\n\t\t),\n\t};\n\tawait ensureAuthentication();\n\twriteSuccess(\n\t\truntime,\n\t\tawait api.event.luckyDraw.getLuckyDrawParticipantsByEventId.query(input),\n\t);\n};\n\nconst organizationCommands = new Map<string, CommandHandler>([\n\t[commandKey(\"list\"), runOrganizationList],\n\t[commandKey(\"get\"), runOrganizationGet],\n\t[commandKey(\"create\"), runOrganizationCreate],\n]);\n\n// Lookup of group -> (action, subAction) -> handler. Keys must match the\n// original guards exactly: absent sub-actions are part of the key.\nconst commandTable = new Map<string, Map<string, CommandHandler>>([\n\t[\n\t\t\"auth\",\n\t\tnew Map<string, CommandHandler>([\n\t\t\t[commandKey(\"login\"), runAuthLogin],\n\t\t\t[commandKey(\"status\"), runAuthStatus],\n\t\t\t[commandKey(\"logout\"), runAuthLogout],\n\t\t\t[commandKey(\"whoami\"), runAuthWhoami],\n\t\t]),\n\t],\n\t[\"organization\", organizationCommands],\n\t[\"org\", organizationCommands],\n\t[\n\t\t\"event\",\n\t\tnew Map<string, CommandHandler>([\n\t\t\t[commandKey(\"create\"), runEventCreate],\n\t\t\t[commandKey(\"list\"), runEventList],\n\t\t\t[commandKey(\"get\"), runEventGet],\n\t\t\t[commandKey(\"appearance\", \"get\"), runEventAppearanceGet],\n\t\t\t[commandKey(\"appearance\", \"update\"), runEventAppearanceUpdate],\n\t\t\t[commandKey(\"appearance\", \"reset\"), runEventAppearanceUpdate],\n\t\t\t[commandKey(\"appearance\", \"upload\"), runEventAppearanceUpload],\n\t\t\t[commandKey(\"photo-wall\", \"display-items\"), runPhotoWallDisplayItems],\n\t\t\t[commandKey(\"photo-wall\", \"display\"), runPhotoWallDisplayItems],\n\t\t]),\n\t],\n\t[\n\t\t\"lucky-draw\",\n\t\tnew Map<string, CommandHandler>([\n\t\t\t[commandKey(\"pre-draw\"), runLuckyDrawPreDraw],\n\t\t\t[commandKey(\"participants\", \"replace\"), runLuckyDrawParticipantsReplace],\n\t\t\t[commandKey(\"participants\", \"list\"), runLuckyDrawParticipantsList],\n\t\t]),\n\t],\n]);\n\nconst runCommand = async (\n\tparsed: ParsedArguments,\n\truntime: CliRuntime,\n\tcredentialStore: CliCredentialStore,\n\tapiBaseUrl: string,\n\tconfigureAccessToken: typeof configureEventTechAccessToken,\n): Promise<void> => {\n\tconst [group, action, subAction] = parsed.positionals;\n\tconst cliVersion = getInstalledCliVersion();\n\tlet accessToken: string | undefined;\n\tconst ensureAuthentication = async () => {\n\t\taccessToken ??= await getAuthenticatedAccessToken({\n\t\t\tapiBaseUrl,\n\t\t\tstore: credentialStore,\n\t\t});\n\t\tconfigureAccessToken(accessToken);\n\t};\n\tif (\n\t\tawait runRegistryCommand({\n\t\t\tparsed,\n\t\t\truntime,\n\t\t\tauthenticate: ensureAuthentication,\n\t\t})\n\t) {\n\t\treturn;\n\t}\n\tif (group === \"commands\" && action === undefined) {\n\t\tassertOnlyFlags(parsed, []);\n\t\twriteSuccess(runtime, { commands: listRegistryCommands() });\n\t\treturn;\n\t}\n\tif (parsed.flags.has(\"help\") || group === \"help\") {\n\t\tassertOnlyFlags(parsed, [\"help\"]);\n\t\twriteSuccess(runtime, { usage });\n\t\treturn;\n\t}\n\tif (parsed.flags.has(\"version\") || group === \"version\") {\n\t\tassertOnlyFlags(parsed, [\"version\"]);\n\t\twriteSuccess(runtime, { version: cliVersion });\n\t\treturn;\n\t}\n\n\tif (group === \"passport\") {\n\t\tawait runPassportCommand({\n\t\t\tpositionals: parsed.positionals,\n\t\t\tflags: parsed.flags,\n\t\t\truntime,\n\t\t\tauthenticate: ensureAuthentication,\n\t\t});\n\t\treturn;\n\t}\n\n\tif (group === \"staff-redemption\") {\n\t\tawait runStaffRedemptionCommand({\n\t\t\tparsed,\n\t\t\truntime,\n\t\t\tauthenticate: ensureAuthentication,\n\t\t});\n\t\treturn;\n\t}\n\n\tif (\n\t\tgroup === \"lucky-draw\" &&\n\t\t(await runLuckyDrawSetupCommand({\n\t\t\tparsed,\n\t\t\truntime,\n\t\t\tauthenticate: ensureAuthentication,\n\t\t}))\n\t) {\n\t\treturn;\n\t}\n\n\tconst handler =\n\t\tgroup === undefined\n\t\t\t? undefined\n\t\t\t: commandTable.get(group)?.get(commandKey(action, subAction));\n\tif (handler === undefined) {\n\t\tthrow new CliUsageError(\n\t\t\t\"Unknown command. Run `et --help` for available commands.\",\n\t\t);\n\t}\n\tawait handler({\n\t\tparsed,\n\t\truntime,\n\t\tcredentialStore,\n\t\tapiBaseUrl,\n\t\tcliVersion,\n\t\tensureAuthentication,\n\t});\n};\n\nexport const runCli = async (\n\targs: readonly string[],\n\truntime: CliRuntime = processRuntime,\n\tcredentialStore: CliCredentialStore = createBunCredentialStore({\n\t\tproduct: \"event-tech\",\n\t}),\n\tconfigureAccessToken: typeof configureEventTechAccessToken = configureEventTechAccessToken,\n): Promise<number> => {\n\ttry {\n\t\tconst parsed = parseArguments(args);\n\t\tconst apiUrl = getOptionalFlag(parsed, \"api-url\");\n\t\tif (apiUrl) configureEventTechApiBaseUrl(apiUrl);\n\t\telse configureEventTechApiFromEnvironment();\n\t\tawait runCommand(\n\t\t\tparsed,\n\t\t\truntime,\n\t\t\tcredentialStore,\n\t\t\tgetEventTechApiBaseUrl(),\n\t\t\tconfigureAccessToken,\n\t\t);\n\t\treturn 0;\n\t} catch (error) {\n\t\twriteError(runtime, error);\n\t\treturn error instanceof CliUsageError ? 2 : 1;\n\t}\n};\n\nexport const getConfiguredApiBaseUrl = (): string => getEventTechApiBaseUrl();\nexport type { EventTechClient } from \"./api-client.js\";\nexport {\n\tcreateEventTechClient,\n\tcreateEventTechPublicClient,\n\tsetEventTechClientForTesting,\n} from \"./api-client.js\";\nexport type { CliRuntime } from \"./runtime/index.js\";\nexport { CliUsageError } from \"./runtime/index.js\";\nexport { parseArguments };\n", "\n/* !!! This is code generated by Prisma. Do not edit directly. !!! */\n/* eslint-disable */\n// biome-ignore-all lint: generated file\n// @ts-nocheck \n/*\n* This file exports all enum related types from the schema.\n*\n* 🟢 You can import this file directly.\n*/\n\nexport const ActivityActorType = {\n USER: 'USER',\n PARTICIPANT: 'PARTICIPANT',\n ANONYMOUS: 'ANONYMOUS',\n SYSTEM: 'SYSTEM'\n} as const\n\nexport type ActivityActorType = (typeof ActivityActorType)[keyof typeof ActivityActorType]\n\n\nexport const ActivityEventCategory = {\n ORGANIZATION: 'ORGANIZATION',\n MEMBER: 'MEMBER',\n EVENT: 'EVENT',\n CONFIG: 'CONFIG',\n SUBMISSION: 'SUBMISSION',\n PARTICIPANT: 'PARTICIPANT',\n EXPORT: 'EXPORT',\n SYSTEM: 'SYSTEM'\n} as const\n\nexport type ActivityEventCategory = (typeof ActivityEventCategory)[keyof typeof ActivityEventCategory]\n\n\nexport const EventPassportQueueStatus = {\n UNDER_10_MIN: 'UNDER_10_MIN',\n UNDER_30_MIN: 'UNDER_30_MIN',\n OVER_30_MIN: 'OVER_30_MIN'\n} as const\n\nexport type EventPassportQueueStatus = (typeof EventPassportQueueStatus)[keyof typeof EventPassportQueueStatus]\n\n\nexport const EventPassportStampSource = {\n QR: 'QR',\n MANUAL: 'MANUAL',\n STAFF_QR: 'STAFF_QR',\n PRIZE_DESK: 'PRIZE_DESK'\n} as const\n\nexport type EventPassportStampSource = (typeof EventPassportStampSource)[keyof typeof EventPassportStampSource]\n\n\nexport const HumanBingoItemType = {\n SINGLE_SELECT: 'SINGLE_SELECT',\n TEXT_INPUT: 'TEXT_INPUT',\n PHOTO_UPLOAD: 'PHOTO_UPLOAD',\n VIDEO_UPLOAD: 'VIDEO_UPLOAD'\n} as const\n\nexport type HumanBingoItemType = (typeof HumanBingoItemType)[keyof typeof HumanBingoItemType]\n\n\nexport const LuckyDrawType = {\n WHEEL: 'WHEEL',\n SLOT_COUNTER: 'SLOT_COUNTER'\n} as const\n\nexport type LuckyDrawType = (typeof LuckyDrawType)[keyof typeof LuckyDrawType]\n\n\nexport const WheelSegmentText = {\n NAME: 'NAME',\n LUCKY_DRAW_ID: 'LUCKY_DRAW_ID'\n} as const\n\nexport type WheelSegmentText = (typeof WheelSegmentText)[keyof typeof WheelSegmentText]\n\n\nexport const PassportAccountLinkMethod = {\n EMAIL_OTP: 'EMAIL_OTP',\n GOOGLE: 'GOOGLE'\n} as const\n\nexport type PassportAccountLinkMethod = (typeof PassportAccountLinkMethod)[keyof typeof PassportAccountLinkMethod]\n\n\nexport const StationParticipantStatus = {\n NOT_STARTED: 'NOT_STARTED',\n IN_PROGRESS: 'IN_PROGRESS',\n COMPLETED: 'COMPLETED'\n} as const\n\nexport type StationParticipantStatus = (typeof StationParticipantStatus)[keyof typeof StationParticipantStatus]\n\n\nexport const MissionType = {\n SINGLE_CHOICE: 'SINGLE_CHOICE',\n MULTIPLE_CHOICE: 'MULTIPLE_CHOICE',\n FILL_IN_THE_BLANK: 'FILL_IN_THE_BLANK',\n PHOTO_UPLOAD: 'PHOTO_UPLOAD',\n VIDEO_UPLOAD: 'VIDEO_UPLOAD',\n MATCHING_GAME: 'MATCHING_GAME',\n SPOT_THE_DIFFERENCE_GAME: 'SPOT_THE_DIFFERENCE_GAME'\n} as const\n\nexport type MissionType = (typeof MissionType)[keyof typeof MissionType]\n\n\nexport const MissionStatus = {\n NOT_STARTED: 'NOT_STARTED',\n IN_PROGRESS: 'IN_PROGRESS',\n COMPLETED: 'COMPLETED'\n} as const\n\nexport type MissionStatus = (typeof MissionStatus)[keyof typeof MissionStatus]\n\n\nexport const StaffRedemptionDrawOutcome = {\n PRIZE: 'PRIZE',\n NO_PRIZE: 'NO_PRIZE'\n} as const\n\nexport type StaffRedemptionDrawOutcome = (typeof StaffRedemptionDrawOutcome)[keyof typeof StaffRedemptionDrawOutcome]\n\n\nexport const crdb_internal_region = {\n aws_ap_southeast_1: 'aws_ap_southeast_1'\n} as const\n\nexport type crdb_internal_region = (typeof crdb_internal_region)[keyof typeof crdb_internal_region]\n\n\nexport const OrganizationStatus = {\n INACTIVE: 'INACTIVE',\n ACTIVE: 'ACTIVE',\n SUSPENDED: 'SUSPENDED'\n} as const\n\nexport type OrganizationStatus = (typeof OrganizationStatus)[keyof typeof OrganizationStatus]\n\n\nexport const EventTechInvitationKind = {\n ORGANIZATION: 'ORGANIZATION',\n PROVISIONING: 'PROVISIONING',\n EVENT: 'EVENT'\n} as const\n\nexport type EventTechInvitationKind = (typeof EventTechInvitationKind)[keyof typeof EventTechInvitationKind]\n\n\nexport const EventAccessRole = {\n MANAGER: 'MANAGER',\n OPERATOR: 'OPERATOR',\n VIEWER: 'VIEWER',\n HELPDESK: 'HELPDESK'\n} as const\n\nexport type EventAccessRole = (typeof EventAccessRole)[keyof typeof EventAccessRole]\n\n\nexport const EventTechEmailDeliveryStatus = {\n SENDING: 'SENDING',\n SENT: 'SENT',\n FAILED: 'FAILED'\n} as const\n\nexport type EventTechEmailDeliveryStatus = (typeof EventTechEmailDeliveryStatus)[keyof typeof EventTechEmailDeliveryStatus]\n\n\nexport const MemberStatus = {\n PENDING: 'PENDING',\n ACTIVE: 'ACTIVE',\n LEFT: 'LEFT',\n REMOVED: 'REMOVED',\n REJECTED: 'REJECTED'\n} as const\n\nexport type MemberStatus = (typeof MemberStatus)[keyof typeof MemberStatus]\n\n\nexport const OrganizationRole = {\n OWNER: 'OWNER',\n ADMIN: 'ADMIN',\n MEMBER: 'MEMBER'\n} as const\n\nexport type OrganizationRole = (typeof OrganizationRole)[keyof typeof OrganizationRole]\n\n\nexport const EventStatus = {\n DRAFT: 'DRAFT',\n ONGOING: 'ONGOING',\n COMPLETED: 'COMPLETED'\n} as const\n\nexport type EventStatus = (typeof EventStatus)[keyof typeof EventStatus]\n\n\nexport const EventType = {\n POST_IT_NOTE: 'POST_IT_NOTE',\n PHOTO_WALL: 'PHOTO_WALL',\n STORY_COLLECTION: 'STORY_COLLECTION',\n LUCKY_DRAW: 'LUCKY_DRAW',\n SCAVENGER_HUNT: 'SCAVENGER_HUNT',\n HUMAN_BINGO: 'HUMAN_BINGO',\n SIGNATURE_WALL: 'SIGNATURE_WALL',\n GARDENS_BY_THE_BAY: 'GARDENS_BY_THE_BAY',\n RATING_SYSTEM: 'RATING_SYSTEM',\n EVENT_PASSPORT: 'EVENT_PASSPORT',\n STAFF_REDEMPTION: 'STAFF_REDEMPTION'\n} as const\n\nexport type EventType = (typeof EventType)[keyof typeof EventType]\n\n\nexport const SubmissionStatus = {\n PENDING: 'PENDING',\n APPROVED: 'APPROVED',\n REJECTED: 'REJECTED'\n} as const\n\nexport type SubmissionStatus = (typeof SubmissionStatus)[keyof typeof SubmissionStatus]\n\n\nexport const UserRole = {\n ADMIN: 'ADMIN',\n USER: 'USER',\n GUEST: 'GUEST'\n} as const\n\nexport type UserRole = (typeof UserRole)[keyof typeof UserRole]\n\n\nexport const CliDeviceAuthorizationStatus = {\n PENDING: 'PENDING',\n APPROVED: 'APPROVED',\n DENIED: 'DENIED',\n CONSUMED: 'CONSUMED',\n EXPIRED: 'EXPIRED'\n} as const\n\nexport type CliDeviceAuthorizationStatus = (typeof CliDeviceAuthorizationStatus)[keyof typeof CliDeviceAuthorizationStatus]\n", "import { EventType } from \"@go-labs/event-tech-db/enums\";\nimport { z } from \"zod\";\n\n/** Retired in #2401: values are retained only so historical events keep decoding. Never creatable. */\nexport const DEPRECATED_EVENT_TYPES = [\n\tEventType.SCAVENGER_HUNT,\n\tEventType.GARDENS_BY_THE_BAY,\n] as const;\n\nexport const isDeprecatedEventType = (type: EventType) =>\n\tDEPRECATED_EVENT_TYPES.some((deprecatedType) => deprecatedType === type);\n\n/** Use for new events and type choices, not for decoding existing event records. */\nexport const activeEventTypeSchema = z\n\t.enum(EventType)\n\t.exclude(DEPRECATED_EVENT_TYPES);\nexport const ACTIVE_EVENT_TYPES = activeEventTypeSchema.options;\n", "// src/observable/observable.ts\n/**\n* Whether a value is an observable: an object with `subscribe`.\n* @public\n*/\nfunction isObservable(x) {\n\treturn typeof x === \"object\" && x !== null && \"subscribe\" in x;\n}\n/**\n* Creates an observable. `subscribe` runs for each subscriber, and can\n* return a function that cleans up when it unsubscribes.\n* @example\n* ```ts\n* const ticks = observable<number>((observer) => {\n* const timer = setInterval(() => observer.next(Date.now()), 1000);\n* return () => clearInterval(timer);\n* });\n* ```\n* @see https://trpc.io/docs/client/links#creating-a-custom-link\n* @public\n*/\nfunction observable(subscribe) {\n\tconst self = {\n\t\tsubscribe(observer) {\n\t\t\tlet teardownRef = null;\n\t\t\tlet isDone = false;\n\t\t\tlet unsubscribed = false;\n\t\t\tlet teardownImmediately = false;\n\t\t\tlet subscribing = true;\n\t\t\tlet thrownWhileSubscribing = null;\n\t\t\tfunction end(notify) {\n\t\t\t\ttry {\n\t\t\t\t\tnotify();\n\t\t\t\t} catch (cause) {\n\t\t\t\t\tvar _thrownWhileSubscribi;\n\t\t\t\t\tif (!subscribing) throw cause;\n\t\t\t\t\t(_thrownWhileSubscribi = thrownWhileSubscribing) !== null && _thrownWhileSubscribi !== void 0 || (thrownWhileSubscribing = { cause });\n\t\t\t\t} finally {\n\t\t\t\t\tunsubscribe();\n\t\t\t\t}\n\t\t\t}\n\t\t\tfunction unsubscribe() {\n\t\t\t\tif (teardownRef === null) {\n\t\t\t\t\tteardownImmediately = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (unsubscribed) return;\n\t\t\t\tunsubscribed = true;\n\t\t\t\tif (typeof teardownRef === \"function\") teardownRef();\n\t\t\t\telse if (teardownRef) teardownRef.unsubscribe();\n\t\t\t}\n\t\t\tteardownRef = subscribe({\n\t\t\t\tnext(value) {\n\t\t\t\t\tvar _observer$next;\n\t\t\t\t\tif (isDone) return;\n\t\t\t\t\t(_observer$next = observer.next) === null || _observer$next === void 0 || _observer$next.call(observer, value);\n\t\t\t\t},\n\t\t\t\terror(err) {\n\t\t\t\t\tif (isDone) return;\n\t\t\t\t\tisDone = true;\n\t\t\t\t\tend(() => {\n\t\t\t\t\t\tvar _observer$error;\n\t\t\t\t\t\treturn (_observer$error = observer.error) === null || _observer$error === void 0 ? void 0 : _observer$error.call(observer, err);\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\tcomplete() {\n\t\t\t\t\tif (isDone) return;\n\t\t\t\t\tisDone = true;\n\t\t\t\t\tend(() => {\n\t\t\t\t\t\tvar _observer$complete;\n\t\t\t\t\t\treturn (_observer$complete = observer.complete) === null || _observer$complete === void 0 ? void 0 : _observer$complete.call(observer);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t\tsubscribing = false;\n\t\t\tif (teardownImmediately) unsubscribe();\n\t\t\tif (thrownWhileSubscribing) throw thrownWhileSubscribing.cause;\n\t\t\treturn { unsubscribe };\n\t\t},\n\t\tpipe(...operations) {\n\t\t\treturn operations.reduce(pipeReducer, self);\n\t\t}\n\t};\n\treturn self;\n}\nfunction pipeReducer(prev, fn) {\n\treturn fn(prev);\n}\n/**\n* Resolves with an observable's first value. Rejects if it errors or\n* completes first. It doesn't unsubscribe after the first value.\n* @internal\n*/\nfunction observableToPromise(observable) {\n\tconst ac = new AbortController();\n\treturn new Promise((resolve, reject) => {\n\t\tlet isDone = false;\n\t\tfunction onDone() {\n\t\t\tif (isDone) return;\n\t\t\tisDone = true;\n\t\t\tobs$.unsubscribe();\n\t\t}\n\t\tac.signal.addEventListener(\"abort\", () => {\n\t\t\treject(ac.signal.reason);\n\t\t});\n\t\tconst obs$ = observable.subscribe({\n\t\t\tnext(data) {\n\t\t\t\tisDone = true;\n\t\t\t\tresolve(data);\n\t\t\t\tonDone();\n\t\t\t},\n\t\t\terror(data) {\n\t\t\t\treject(data);\n\t\t\t},\n\t\t\tcomplete() {\n\t\t\t\tac.abort();\n\t\t\t\tonDone();\n\t\t\t}\n\t\t});\n\t});\n}\n/**\n* Turns an observable into an async iterable, like Node's `events.on()`.\n* Values wait in a queue until `next()` reads them. An error rejects the\n* `next()` after the queued values, once. Completion, `return()` and aborting\n* `signal` unsubscribe and end every pending `next()` with `{ done: true }`;\n* anything the observable sends after that is ignored.\n*\n* If unsubscribing throws, `return()` rejects with the error, and completion\n* or an error from the observable rethrows it. On abort, it rejects the\n* `next()` after the queued values instead, as an error would.\n* @internal\n*/\nfunction observableToAsyncIterable(observable, signal) {\n\tconst values = [];\n\tconst pending = [];\n\tlet error = null;\n\tlet finished = false;\n\tlet subscription = null;\n\t/** Unsubscribes once, and returns what the teardown threw. */\n\tfunction unsubscribe() {\n\t\tif (finished) return null;\n\t\tfinished = true;\n\t\tsignal.removeEventListener(\"abort\", abort);\n\t\ttry {\n\t\t\tsubscription === null || subscription === void 0 || subscription.unsubscribe();\n\t\t\treturn null;\n\t\t} catch (cause) {\n\t\t\treturn { cause };\n\t\t}\n\t}\n\t/** Settles every pending `next()`: the first with `error` if there is one. */\n\tfunction settle() {\n\t\tconst first = error ? pending.shift() : void 0;\n\t\tif (error && first) {\n\t\t\tconst { cause } = error;\n\t\t\terror = null;\n\t\t\tfirst.reject(cause);\n\t\t}\n\t\tfor (const promise of pending.splice(0)) promise.resolve({\n\t\t\tvalue: void 0,\n\t\t\tdone: true\n\t\t});\n\t}\n\tfunction finish() {\n\t\tconst failure = unsubscribe();\n\t\tsettle();\n\t\tif (failure) throw failure.cause;\n\t}\n\tfunction abort() {\n\t\tconst failure = unsubscribe();\n\t\tif (failure) error = failure;\n\t\tsettle();\n\t}\n\tsubscription = observable.subscribe({\n\t\tnext(value) {\n\t\t\tif (finished) return;\n\t\t\tconst promise = pending.shift();\n\t\t\tif (promise) promise.resolve({\n\t\t\t\tvalue,\n\t\t\t\tdone: false\n\t\t\t});\n\t\t\telse values.push(value);\n\t\t},\n\t\terror(cause) {\n\t\t\tif (finished) return;\n\t\t\terror = { cause };\n\t\t\tfinish();\n\t\t},\n\t\tcomplete: finish\n\t});\n\tif (finished) subscription.unsubscribe();\n\telse if (signal.aborted) abort();\n\telse signal.addEventListener(\"abort\", abort, { once: true });\n\tconst iterator = {\n\t\t[Symbol.asyncIterator]() {\n\t\t\treturn iterator;\n\t\t},\n\t\tasync next() {\n\t\t\tif (values.length > 0) return {\n\t\t\t\tvalue: values.shift(),\n\t\t\t\tdone: false\n\t\t\t};\n\t\t\tif (error) {\n\t\t\t\tconst { cause } = error;\n\t\t\t\terror = null;\n\t\t\t\tthrow cause;\n\t\t\t}\n\t\t\tif (finished) return {\n\t\t\t\tvalue: void 0,\n\t\t\t\tdone: true\n\t\t\t};\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tpending.push({\n\t\t\t\t\tresolve,\n\t\t\t\t\treject\n\t\t\t\t});\n\t\t\t});\n\t\t},\n\t\tasync return() {\n\t\t\tvalues.length = 0;\n\t\t\terror = null;\n\t\t\tfinish();\n\t\t\treturn {\n\t\t\t\tvalue: void 0,\n\t\t\t\tdone: true\n\t\t\t};\n\t\t}\n\t};\n\treturn iterator;\n}\nexport { observableToPromise as i, observable as n, observableToAsyncIterable as r, isObservable as t };\n\n\n//# sourceMappingURL=observable-CodTG6Sf.mjs.map", "import { n as observable } from \"./observable-CodTG6Sf.mjs\";\n// src/observable/operators.ts\n/** Maps each value with `project`. */\nfunction map(project) {\n\treturn (source) => {\n\t\treturn observable((destination) => {\n\t\t\tlet index = 0;\n\t\t\treturn source.subscribe({\n\t\t\t\tnext(value) {\n\t\t\t\t\tdestination.next(project(value, index++));\n\t\t\t\t},\n\t\t\t\terror(error) {\n\t\t\t\t\tdestination.error(error);\n\t\t\t\t},\n\t\t\t\tcomplete() {\n\t\t\t\t\tdestination.complete();\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t};\n}\n/**\n* Shares one subscription to the source between all subscribers. It\n* starts with the first subscriber and ends when the last unsubscribes.\n*/\nfunction share(_opts) {\n\treturn (source) => {\n\t\tlet refCount = 0;\n\t\tlet subscription = null;\n\t\tlet isConnecting = false;\n\t\tlet observers = /* @__PURE__ */ new Set();\n\t\tfunction startIfNeeded() {\n\t\t\tif (subscription || isConnecting) return;\n\t\t\tisConnecting = true;\n\t\t\tlet isDone = false;\n\t\t\tlet sourceSubscription;\n\t\t\ttry {\n\t\t\t\tsourceSubscription = source.subscribe({\n\t\t\t\t\tnext(value) {\n\t\t\t\t\t\tnotify(observers, (observer) => {\n\t\t\t\t\t\t\tvar _observer$next;\n\t\t\t\t\t\t\treturn (_observer$next = observer.next) === null || _observer$next === void 0 ? void 0 : _observer$next.call(observer, value);\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t\terror(error) {\n\t\t\t\t\t\tisDone = true;\n\t\t\t\t\t\tterminate((observer) => {\n\t\t\t\t\t\t\tvar _observer$error;\n\t\t\t\t\t\t\treturn (_observer$error = observer.error) === null || _observer$error === void 0 ? void 0 : _observer$error.call(observer, error);\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t\tcomplete() {\n\t\t\t\t\t\tisDone = true;\n\t\t\t\t\t\tterminate((observer) => {\n\t\t\t\t\t\t\tvar _observer$complete;\n\t\t\t\t\t\t\treturn (_observer$complete = observer.complete) === null || _observer$complete === void 0 ? void 0 : _observer$complete.call(observer);\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} finally {\n\t\t\t\tisConnecting = false;\n\t\t\t}\n\t\t\tif (isDone) sourceSubscription.unsubscribe();\n\t\t\telse subscription = sourceSubscription;\n\t\t}\n\t\tfunction notify(targets, callback) {\n\t\t\tfor (const observer of [...targets]) if (targets.has(observer)) callback(observer);\n\t\t}\n\t\tfunction terminate(callback) {\n\t\t\tconst _sub = subscription;\n\t\t\tconst terminatedObservers = observers;\n\t\t\tsubscription = null;\n\t\t\tobservers = /* @__PURE__ */ new Set();\n\t\t\tisConnecting = false;\n\t\t\ttry {\n\t\t\t\tnotify(terminatedObservers, callback);\n\t\t\t} finally {\n\t\t\t\t_sub === null || _sub === void 0 || _sub.unsubscribe();\n\t\t\t}\n\t\t}\n\t\tfunction resetSource() {\n\t\t\tconst _sub = subscription;\n\t\t\tsubscription = null;\n\t\t\t_sub === null || _sub === void 0 || _sub.unsubscribe();\n\t\t}\n\t\tfunction resetIfNeeded() {\n\t\t\tif (refCount === 0 && subscription) resetSource();\n\t\t}\n\t\treturn observable((subscriber) => {\n\t\t\trefCount++;\n\t\t\tconst subscriberObservers = observers;\n\t\t\tsubscriberObservers.add(subscriber);\n\t\t\tstartIfNeeded();\n\t\t\treturn { unsubscribe() {\n\t\t\t\trefCount--;\n\t\t\t\tresetIfNeeded();\n\t\t\t\tsubscriberObservers.delete(subscriber);\n\t\t\t} };\n\t\t});\n\t};\n}\n/** Calls `observer` with each value, error and completion, and passes them on unchanged. */\nfunction tap(observer) {\n\treturn (source) => {\n\t\treturn observable((destination) => {\n\t\t\treturn source.subscribe({\n\t\t\t\tnext(value) {\n\t\t\t\t\tvar _observer$next2;\n\t\t\t\t\t(_observer$next2 = observer.next) === null || _observer$next2 === void 0 || _observer$next2.call(observer, value);\n\t\t\t\t\tdestination.next(value);\n\t\t\t\t},\n\t\t\t\terror(error) {\n\t\t\t\t\tvar _observer$error2;\n\t\t\t\t\t(_observer$error2 = observer.error) === null || _observer$error2 === void 0 || _observer$error2.call(observer, error);\n\t\t\t\t\tdestination.error(error);\n\t\t\t\t},\n\t\t\t\tcomplete() {\n\t\t\t\t\tvar _observer$complete2;\n\t\t\t\t\t(_observer$complete2 = observer.complete) === null || _observer$complete2 === void 0 || _observer$complete2.call(observer);\n\t\t\t\t\tdestination.complete();\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t};\n}\nconst distinctUnsetMarker = Symbol();\n/** Skips values equal to the one before, by `compare` (`===` by default). */\nfunction distinctUntilChanged(compare = (a, b) => a === b) {\n\treturn (source) => {\n\t\treturn observable((destination) => {\n\t\t\tlet lastValue = distinctUnsetMarker;\n\t\t\treturn source.subscribe({\n\t\t\t\tnext(value) {\n\t\t\t\t\tif (lastValue !== distinctUnsetMarker && compare(lastValue, value)) return;\n\t\t\t\t\tlastValue = value;\n\t\t\t\t\tdestination.next(value);\n\t\t\t\t},\n\t\t\t\terror(error) {\n\t\t\t\t\tdestination.error(error);\n\t\t\t\t},\n\t\t\t\tcomplete() {\n\t\t\t\t\tdestination.complete();\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t};\n}\nconst isDeepEqual = (a, b) => {\n\tif (a === b) return true;\n\treturn !!(a && b && typeof a === \"object\" && typeof b === \"object\") && Object.keys(a).length === Object.keys(b).length && Object.entries(a).every(([k, v]) => isDeepEqual(v, b[k]));\n};\n/**\n* Skips values equal to the one before, comparing objects and arrays by\n* their own enumerable keys. Objects without such keys, like two `Date`s,\n* always count as equal.\n*/\nfunction distinctUntilDeepChanged() {\n\treturn distinctUntilChanged(isDeepEqual);\n}\n// src/observable/behaviorSubject.ts\n/**\n* Calls one of several observers. A throw would stop the caller from\n* notifying the rest, so it is rethrown asynchronously instead: it still\n* shows up as an uncaught exception.\n*/\nfunction callObserver(callback) {\n\ttry {\n\t\tcallback();\n\t} catch (error) {\n\t\tsetTimeout(() => {\n\t\t\tthrow error;\n\t\t});\n\t}\n}\n/**\n* Creates an observable that holds a current value. New subscribers get\n* it right away, unless it's `undefined`.\n* @internal\n*/\nfunction behaviorSubject(initialValue) {\n\tlet value = initialValue;\n\tconst observerList = /* @__PURE__ */ new Set();\n\tconst addObserver = (observer) => {\n\t\tif (value !== void 0) observer.next(value);\n\t\tobserverList.add(observer);\n\t};\n\tconst removeObserver = (observer) => {\n\t\tobserverList.delete(observer);\n\t};\n\tconst obs = observable((observer) => {\n\t\taddObserver(observer);\n\t\treturn () => {\n\t\t\tremoveObserver(observer);\n\t\t};\n\t});\n\tobs.next = (nextValue) => {\n\t\tif (value === nextValue) return;\n\t\tvalue = nextValue;\n\t\tfor (const observer of [...observerList]) if (observerList.has(observer)) callObserver(() => observer.next(nextValue));\n\t};\n\tobs.get = () => value;\n\treturn obs;\n}\nexport { share as a, map as i, distinctUntilChanged as n, tap as o, distinctUntilDeepChanged as r, behaviorSubject as t };\n\n\n//# sourceMappingURL=observable-BjUZYMQq.mjs.map", "import { observable } from \"@trpc/server/observable\";\n// src/links/internals/createChain.ts\n/** @internal */\nfunction createChain(opts) {\n\treturn observable((observer) => {\n\t\tfunction execute(index = 0, op = opts.op) {\n\t\t\tconst next = opts.links[index];\n\t\t\tif (!next) throw new Error(\"No more links to execute - did you forget to add an ending link?\");\n\t\t\treturn next({\n\t\t\t\top,\n\t\t\t\tnext(nextOp) {\n\t\t\t\t\treturn execute(index + 1, nextOp);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\treturn execute().subscribe(observer);\n\t});\n}\n// src/links/splitLink.ts\nfunction asArray(value) {\n\treturn Array.isArray(value) ? value : [value];\n}\n/**\n* Sends each operation down one of two link chains, based on `condition`.\n*\n* @see https://trpc.io/docs/client/links/splitLink\n*/\nfunction splitLink(opts) {\n\treturn (runtime) => {\n\t\tconst yes = asArray(opts.true).map((link) => link(runtime));\n\t\tconst no = asArray(opts.false).map((link) => link(runtime));\n\t\treturn (props) => {\n\t\t\treturn observable((observer) => {\n\t\t\t\tconst links = opts.condition(props.op) ? yes : no;\n\t\t\t\treturn createChain({\n\t\t\t\t\top: props.op,\n\t\t\t\t\tlinks\n\t\t\t\t}).subscribe(observer);\n\t\t\t});\n\t\t};\n\t};\n}\nexport { createChain as n, splitLink as t };\n\n//# sourceMappingURL=splitLink-PFsRy7Mf.mjs.map", "// \\0@oxc-project+runtime@0.157.0/helpers/esm/typeof.js\nfunction _typeof(o) {\n\t\"@babel/helpers - typeof\";\n\treturn _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function(o) {\n\t\treturn typeof o;\n\t} : function(o) {\n\t\treturn o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o;\n\t}, _typeof(o);\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/toPrimitive.js\nfunction toPrimitive(t, e) {\n\tif (\"object\" != _typeof(t) || !t) return t;\n\tvar r;\n\tif (\"undefined\" != typeof Symbol && void 0 !== (r = t[Symbol.toPrimitive])) {\n\t\tvar i = r.call(t, e || \"default\");\n\t\tif (\"object\" != _typeof(i)) return i;\n\t\tthrow new TypeError(\"@@toPrimitive must return a primitive value.\");\n\t}\n\treturn (\"string\" === e ? String : Number)(t);\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/toPropertyKey.js\nfunction toPropertyKey(t) {\n\tvar i = toPrimitive(t, \"string\");\n\treturn \"symbol\" == _typeof(i) ? i : i + \"\";\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/defineProperty.js\nfunction _defineProperty(e, r, t) {\n\treturn (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {\n\t\tvalue: t,\n\t\tenumerable: !0,\n\t\tconfigurable: !0,\n\t\twritable: !0\n\t}) : e[r] = t, e;\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/objectSpread2.js\nfunction ownKeys(e, r) {\n\tvar t = Object.keys(e);\n\tif (Object.getOwnPropertySymbols) {\n\t\tvar o = Object.getOwnPropertySymbols(e);\n\t\tr && (o = o.filter(function(r) {\n\t\t\treturn Object.getOwnPropertyDescriptor(e, r).enumerable;\n\t\t})), t.push.apply(t, o);\n\t}\n\treturn t;\n}\nfunction _objectSpread2(e) {\n\tfor (var r = 1; r < arguments.length; r++) {\n\t\tvar t = null != arguments[r] ? arguments[r] : {};\n\t\tr % 2 ? ownKeys(Object(t), !0).forEach(function(r) {\n\t\t\t_defineProperty(e, r, t[r]);\n\t\t}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r) {\n\t\t\tObject.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));\n\t\t});\n\t}\n\treturn e;\n}\nexport { _defineProperty as n, _objectSpread2 as t };\n", "// src/unstable-core-do-not-import/utils.ts\n/**\n* Ensures there are no duplicate keys when building a procedure.\n* @internal\n*/\nfunction mergeWithoutOverrides(obj1, ...objs) {\n\tconst newObj = Object.assign(emptyObject(), obj1);\n\tfor (const overrides of objs) for (const key in overrides) {\n\t\tif (key in newObj && newObj[key] !== overrides[key]) throw new Error(`Duplicate key ${key}`);\n\t\tnewObj[key] = overrides[key];\n\t}\n\treturn newObj;\n}\n/**\n* Check that value is object\n* @internal\n*/\nfunction isObject(value) {\n\treturn !!value && !Array.isArray(value) && typeof value === \"object\";\n}\nfunction isFunction(fn) {\n\treturn typeof fn === \"function\";\n}\n/**\n* Create an object without inheriting anything from `Object.prototype`\n* @internal\n*/\nfunction emptyObject() {\n\treturn Object.create(null);\n}\nconst asyncIteratorsSupported = typeof Symbol === \"function\" && !!Symbol.asyncIterator;\nfunction isAsyncIterable(value) {\n\treturn asyncIteratorsSupported && isObject(value) && Symbol.asyncIterator in value;\n}\n/**\n* Run an IIFE\n*/\nconst run = (fn) => fn();\nfunction noop() {}\nfunction identity(it) {\n\treturn it;\n}\n/**\n* Generic runtime assertion function. Throws, if the condition is not `true`.\n*\n* Can be used as a slightly less dangerous variant of type assertions. Code\n* mistakes would be revealed at runtime then (hopefully during testing).\n*/\nfunction assert(condition, msg = \"no additional info\") {\n\tif (!condition) throw new Error(`AssertionError: ${msg}`);\n}\nfunction assertNever(value) {\n\tthrow new Error(`AssertionError: unexpected value ${String(value)}`);\n}\nfunction sleep(ms = 0) {\n\treturn new Promise((res) => setTimeout(res, ms));\n}\n/**\n* Ponyfill for\n* [`AbortSignal.any`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/any_static).\n*/\nfunction abortSignalsAnyPonyfill(signals) {\n\tif (typeof AbortSignal.any === \"function\") return AbortSignal.any(signals);\n\tconst ac = new AbortController();\n\tfor (const signal of signals) {\n\t\tif (signal.aborted) {\n\t\t\ttrigger();\n\t\t\tbreak;\n\t\t}\n\t\tsignal.addEventListener(\"abort\", trigger, { once: true });\n\t}\n\treturn ac.signal;\n\tfunction trigger() {\n\t\tac.abort();\n\t\tfor (const signal of signals) signal.removeEventListener(\"abort\", trigger);\n\t}\n}\n// src/unstable-core-do-not-import/rpc/codes.ts\n/**\n* The JSON-RPC 2.0 error code of each tRPC error code. tRPC's own codes\n* use the range JSON-RPC leaves for servers, `-32000` to `-32099`, ending\n* in the digits of the matching HTTP status.\n* @see https://trpc.io/docs/rpc#error-codes---json-rpc-20-error-codes\n*/\nconst TRPC_ERROR_CODES_BY_KEY = {\n\t/**\n\t* Invalid JSON was received by the server.\n\t* An error occurred on the server while parsing the JSON text.\n\t*/\n\tPARSE_ERROR: -32700,\n\t/**\n\t* The JSON sent is not a valid Request object.\n\t*/\n\tBAD_REQUEST: -32600,\n\tINTERNAL_SERVER_ERROR: -32603,\n\tNOT_IMPLEMENTED: -32603,\n\tBAD_GATEWAY: -32603,\n\tSERVICE_UNAVAILABLE: -32603,\n\tGATEWAY_TIMEOUT: -32603,\n\tUNAUTHORIZED: -32001,\n\tPAYMENT_REQUIRED: -32002,\n\tFORBIDDEN: -32003,\n\tNOT_FOUND: -32004,\n\tMETHOD_NOT_SUPPORTED: -32005,\n\tTIMEOUT: -32008,\n\tCONFLICT: -32009,\n\tPRECONDITION_FAILED: -32012,\n\tPAYLOAD_TOO_LARGE: -32013,\n\tUNSUPPORTED_MEDIA_TYPE: -32015,\n\tUNPROCESSABLE_CONTENT: -32022,\n\tPRECONDITION_REQUIRED: -32028,\n\tTOO_MANY_REQUESTS: -32029,\n\tCLIENT_CLOSED_REQUEST: -32099\n};\n/**\n* The tRPC error code of each JSON-RPC 2.0 error code.\n* @see https://trpc.io/docs/rpc#error-codes---json-rpc-20-error-codes\n*/\nconst TRPC_ERROR_CODES_BY_NUMBER = {\n\t[-32700]: \"PARSE_ERROR\",\n\t[-32600]: \"BAD_REQUEST\",\n\t[-32603]: \"INTERNAL_SERVER_ERROR\",\n\t[-32001]: \"UNAUTHORIZED\",\n\t[-32002]: \"PAYMENT_REQUIRED\",\n\t[-32003]: \"FORBIDDEN\",\n\t[-32004]: \"NOT_FOUND\",\n\t[-32005]: \"METHOD_NOT_SUPPORTED\",\n\t[-32008]: \"TIMEOUT\",\n\t[-32009]: \"CONFLICT\",\n\t[-32012]: \"PRECONDITION_FAILED\",\n\t[-32013]: \"PAYLOAD_TOO_LARGE\",\n\t[-32015]: \"UNSUPPORTED_MEDIA_TYPE\",\n\t[-32022]: \"UNPROCESSABLE_CONTENT\",\n\t[-32028]: \"PRECONDITION_REQUIRED\",\n\t[-32029]: \"TOO_MANY_REQUESTS\",\n\t[-32099]: \"CLIENT_CLOSED_REQUEST\"\n};\n/**\n* tRPC error codes that are considered retryable\n* With out of the box SSE, the client will reconnect when these errors are encountered\n*/\nconst retryableRpcCodes = [\n\tTRPC_ERROR_CODES_BY_KEY.BAD_GATEWAY,\n\tTRPC_ERROR_CODES_BY_KEY.SERVICE_UNAVAILABLE,\n\tTRPC_ERROR_CODES_BY_KEY.GATEWAY_TIMEOUT,\n\tTRPC_ERROR_CODES_BY_KEY.INTERNAL_SERVER_ERROR\n];\nexport { assert as a, identity as c, isObject as d, mergeWithoutOverrides as f, sleep as h, abortSignalsAnyPonyfill as i, isAsyncIterable as l, run as m, TRPC_ERROR_CODES_BY_NUMBER as n, assertNever as o, noop as p, retryableRpcCodes as r, emptyObject as s, TRPC_ERROR_CODES_BY_KEY as t, isFunction as u };\n\n\n//# sourceMappingURL=codes-BCsCCyMj.mjs.map", "import { d as isObject, n as TRPC_ERROR_CODES_BY_NUMBER, s as emptyObject, t as TRPC_ERROR_CODES_BY_KEY } from \"./codes-BCsCCyMj.mjs\";\n// src/unstable-core-do-not-import/createProxy.ts\nconst noop = () => {};\nconst freezeIfAvailable = (obj) => {\n\tif (Object.freeze) Object.freeze(obj);\n};\nfunction createInnerProxy(callback, path, memo) {\n\tvar _memo$cacheKey;\n\tconst cacheKey = path.join(\".\");\n\t(_memo$cacheKey = memo[cacheKey]) !== null && _memo$cacheKey !== void 0 || (memo[cacheKey] = new Proxy(noop, {\n\t\tget(_obj, key) {\n\t\t\tif (typeof key !== \"string\" || key === \"then\") return;\n\t\t\treturn createInnerProxy(callback, [...path, key], memo);\n\t\t},\n\t\tapply(_1, _2, args) {\n\t\t\tconst lastOfPath = path[path.length - 1];\n\t\t\tif (lastOfPath === \"valueOf\" || lastOfPath === \"toString\" || lastOfPath === \"toJSON\") return `tRPC.proxy(${path.slice(0, -1).join(\".\")})`;\n\t\t\tlet opts = {\n\t\t\t\targs,\n\t\t\t\tpath\n\t\t\t};\n\t\t\tif (lastOfPath === \"call\") opts = {\n\t\t\t\targs: args.length >= 2 ? [args[1]] : [],\n\t\t\t\tpath: path.slice(0, -1)\n\t\t\t};\n\t\t\telse if (lastOfPath === \"apply\") opts = {\n\t\t\t\targs: args.length >= 2 ? args[1] : [],\n\t\t\t\tpath: path.slice(0, -1)\n\t\t\t};\n\t\t\tfreezeIfAvailable(opts.args);\n\t\t\tfreezeIfAvailable(opts.path);\n\t\t\treturn callback(opts);\n\t\t}\n\t}));\n\treturn memo[cacheKey];\n}\n/**\n* Creates a proxy that records the property path it's accessed with, and\n* calls `callback` with the path and arguments when it's called.\n* @internal\n*/\nconst createRecursiveProxy = (callback) => createInnerProxy(callback, [], emptyObject());\n/**\n* Creates a proxy that maps each property to `callback(name)`, one level\n* deep. It's not thenable.\n* @internal\n*/\nconst createFlatProxy = (callback) => {\n\treturn new Proxy(noop, { get(_obj, name) {\n\t\tif (name === \"then\") return;\n\t\treturn callback(name);\n\t} });\n};\n// src/unstable-core-do-not-import/http/getHTTPStatusCode.ts\nconst JSONRPC2_TO_HTTP_CODE = {\n\tPARSE_ERROR: 400,\n\tBAD_REQUEST: 400,\n\tUNAUTHORIZED: 401,\n\tPAYMENT_REQUIRED: 402,\n\tFORBIDDEN: 403,\n\tNOT_FOUND: 404,\n\tMETHOD_NOT_SUPPORTED: 405,\n\tTIMEOUT: 408,\n\tCONFLICT: 409,\n\tPRECONDITION_FAILED: 412,\n\tPAYLOAD_TOO_LARGE: 413,\n\tUNSUPPORTED_MEDIA_TYPE: 415,\n\tUNPROCESSABLE_CONTENT: 422,\n\tPRECONDITION_REQUIRED: 428,\n\tTOO_MANY_REQUESTS: 429,\n\tCLIENT_CLOSED_REQUEST: 499,\n\tINTERNAL_SERVER_ERROR: 500,\n\tNOT_IMPLEMENTED: 501,\n\tBAD_GATEWAY: 502,\n\tSERVICE_UNAVAILABLE: 503,\n\tGATEWAY_TIMEOUT: 504\n};\nconst HTTP_CODE_TO_JSONRPC2 = {\n\t400: \"BAD_REQUEST\",\n\t401: \"UNAUTHORIZED\",\n\t402: \"PAYMENT_REQUIRED\",\n\t403: \"FORBIDDEN\",\n\t404: \"NOT_FOUND\",\n\t405: \"METHOD_NOT_SUPPORTED\",\n\t408: \"TIMEOUT\",\n\t409: \"CONFLICT\",\n\t412: \"PRECONDITION_FAILED\",\n\t413: \"PAYLOAD_TOO_LARGE\",\n\t415: \"UNSUPPORTED_MEDIA_TYPE\",\n\t422: \"UNPROCESSABLE_CONTENT\",\n\t428: \"PRECONDITION_REQUIRED\",\n\t429: \"TOO_MANY_REQUESTS\",\n\t499: \"CLIENT_CLOSED_REQUEST\",\n\t500: \"INTERNAL_SERVER_ERROR\",\n\t501: \"NOT_IMPLEMENTED\",\n\t502: \"BAD_GATEWAY\",\n\t503: \"SERVICE_UNAVAILABLE\",\n\t504: \"GATEWAY_TIMEOUT\"\n};\nfunction getStatusCodeFromKey(code) {\n\tvar _JSONRPC2_TO_HTTP_COD;\n\treturn (_JSONRPC2_TO_HTTP_COD = JSONRPC2_TO_HTTP_CODE[code]) !== null && _JSONRPC2_TO_HTTP_COD !== void 0 ? _JSONRPC2_TO_HTTP_COD : 500;\n}\nfunction getStatusKeyFromCode(code) {\n\tvar _HTTP_CODE_TO_JSONRPC;\n\treturn (_HTTP_CODE_TO_JSONRPC = HTTP_CODE_TO_JSONRPC2[code]) !== null && _HTTP_CODE_TO_JSONRPC !== void 0 ? _HTTP_CODE_TO_JSONRPC : \"INTERNAL_SERVER_ERROR\";\n}\n/**\n* The HTTP status for a response, or for a batch of them: `207` when the\n* responses' statuses differ.\n* @see https://trpc.io/docs/rpc#error-codes---http-status\n*/\nfunction getHTTPStatusCode(json, errors) {\n\tconst httpStatuses = new Set((Array.isArray(json) ? json : [json]).map((res, index) => {\n\t\tif (\"error\" in res) {\n\t\t\tif (isObject(res.error.data) && typeof res.error.data[\"httpStatus\"] === \"number\") return res.error.data[\"httpStatus\"];\n\t\t\tconst original = errors === null || errors === void 0 ? void 0 : errors[index];\n\t\t\tif (original) return getStatusCodeFromKey(original.code);\n\t\t\tconst code = TRPC_ERROR_CODES_BY_NUMBER[res.error.code];\n\t\t\treturn getStatusCodeFromKey(code);\n\t\t}\n\t\treturn 200;\n\t}));\n\tif (httpStatuses.size !== 1) return 207;\n\treturn httpStatuses.values().next().value;\n}\n/**\n* The HTTP status of a `TRPCError`'s code.\n* @see https://trpc.io/docs/rpc#error-codes---http-status\n*/\nfunction getHTTPStatusCodeFromError(error) {\n\treturn getStatusCodeFromKey(error.code);\n}\n// src/unstable-core-do-not-import/error/formatter.ts\nconst defaultFormatter = ({ shape }) => {\n\treturn shape;\n};\n/**\n* @internal\n*/\nfunction getDefaultErrorShape(opts) {\n\tconst shape = {\n\t\tmessage: opts.error.message,\n\t\tcode: TRPC_ERROR_CODES_BY_KEY[opts.error.code],\n\t\tdata: {\n\t\t\tcode: opts.error.code,\n\t\t\thttpStatus: getHTTPStatusCodeFromError(opts.error)\n\t\t}\n\t};\n\tif (opts.isDev && typeof opts.error.stack === \"string\") shape.data.stack = opts.error.stack;\n\tif (typeof opts.path === \"string\") shape.data.path = opts.path;\n\treturn shape;\n}\nconst formattedShapeSymbol = Symbol(\"trpc_formattedErrorShape\");\n/**\n* @internal\n*/\nfunction setFormattedErrorShape(error, shape) {\n\tObject.defineProperty(error, formattedShapeSymbol, {\n\t\tvalue: shape,\n\t\tenumerable: false,\n\t\tconfigurable: true,\n\t\twritable: true\n\t});\n}\n/**\n* @internal\n*/\nfunction getFormattedErrorShape(error) {\n\tif (isFormattedErrorShape(error)) return error[formattedShapeSymbol];\n}\nfunction isFormattedErrorShape(error) {\n\treturn formattedShapeSymbol in error;\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/typeof.js\nfunction _typeof(o) {\n\t\"@babel/helpers - typeof\";\n\treturn _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function(o) {\n\t\treturn typeof o;\n\t} : function(o) {\n\t\treturn o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o;\n\t}, _typeof(o);\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/toPrimitive.js\nfunction toPrimitive(t, e) {\n\tif (\"object\" != _typeof(t) || !t) return t;\n\tvar r;\n\tif (\"undefined\" != typeof Symbol && void 0 !== (r = t[Symbol.toPrimitive])) {\n\t\tvar i = r.call(t, e || \"default\");\n\t\tif (\"object\" != _typeof(i)) return i;\n\t\tthrow new TypeError(\"@@toPrimitive must return a primitive value.\");\n\t}\n\treturn (\"string\" === e ? String : Number)(t);\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/toPropertyKey.js\nfunction toPropertyKey(t) {\n\tvar i = toPrimitive(t, \"string\");\n\treturn \"symbol\" == _typeof(i) ? i : i + \"\";\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/defineProperty.js\nfunction _defineProperty(e, r, t) {\n\treturn (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {\n\t\tvalue: t,\n\t\tenumerable: !0,\n\t\tconfigurable: !0,\n\t\twritable: !0\n\t}) : e[r] = t, e;\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/objectSpread2.js\nfunction ownKeys(e, r) {\n\tvar t = Object.keys(e);\n\tif (Object.getOwnPropertySymbols) {\n\t\tvar o = Object.getOwnPropertySymbols(e);\n\t\tr && (o = o.filter(function(r) {\n\t\t\treturn Object.getOwnPropertyDescriptor(e, r).enumerable;\n\t\t})), t.push.apply(t, o);\n\t}\n\treturn t;\n}\nfunction _objectSpread2(e) {\n\tfor (var r = 1; r < arguments.length; r++) {\n\t\tvar t = null != arguments[r] ? arguments[r] : {};\n\t\tr % 2 ? ownKeys(Object(t), !0).forEach(function(r) {\n\t\t\t_defineProperty(e, r, t[r]);\n\t\t}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r) {\n\t\t\tObject.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));\n\t\t});\n\t}\n\treturn e;\n}\n// src/unstable-core-do-not-import/error/getErrorShape.ts\n/**\n* The shape of an error as the client gets it: from a procedure's\n* `.errors()` formatter if one ran, or else from the root error formatter.\n* @internal\n*/\nfunction getErrorShape(opts) {\n\tconst { path, error, config } = opts;\n\tconst formatted = getFormattedErrorShape(error);\n\tif (formatted !== void 0) return formatted;\n\tconst shape = getDefaultErrorShape({\n\t\terror,\n\t\tpath,\n\t\tisDev: config.isDev\n\t});\n\treturn config.errorFormatter(_objectSpread2(_objectSpread2({}, opts), {}, { shape }));\n}\nexport { getDefaultErrorShape as a, setFormattedErrorShape as c, getHTTPStatusCode as d, getHTTPStatusCodeFromError as f, createRecursiveProxy as g, createFlatProxy as h, defaultFormatter as i, HTTP_CODE_TO_JSONRPC2 as l, getStatusKeyFromCode as m, _objectSpread2 as n, getFormattedErrorShape as o, getStatusCodeFromKey as p, _defineProperty as r, isFormattedErrorShape as s, getErrorShape as t, JSONRPC2_TO_HTTP_CODE as u };\n\n\n//# sourceMappingURL=getErrorShape-CVrl8_-w.mjs.map", "import { d as isObject, f as mergeWithoutOverrides, s as emptyObject, u as isFunction } from \"./codes-BCsCCyMj.mjs\";\nimport { g as createRecursiveProxy, i as defaultFormatter, n as _objectSpread2, r as _defineProperty } from \"./getErrorShape-CVrl8_-w.mjs\";\n// src/unstable-core-do-not-import/error/TRPCError.ts\nvar UnknownCauseError = class extends Error {\n\tconstructor(cause) {\n\t\tsuper(getMessage(cause));\n\t\tObject.assign(this, cause);\n\t\tif (isErrorLike(cause)) {\n\t\t\tif (typeof cause.name === \"string\") this.name = cause.name;\n\t\t\tif (typeof cause.stack === \"string\") this.stack = cause.stack;\n\t\t}\n\t}\n};\nfunction getMessage(cause) {\n\tif (\"message\" in cause) return String(cause.message);\n}\n/**\n* Errors from another realm (e.g. `node:vm`, iframes) fail `instanceof Error`\n* but still carry the `[object Error]` brand.\n*/\nfunction isErrorLike(value) {\n\treturn value instanceof Error || Object.prototype.toString.call(value) === \"[object Error]\";\n}\nfunction getCauseFromUnknown(cause) {\n\tif (cause instanceof Error) return cause;\n\tconst type = typeof cause;\n\tif (type === \"undefined\" || type === \"function\" || cause === null) return;\n\tif (type !== \"object\") return new Error(String(cause));\n\tif (isObject(cause)) return new UnknownCauseError(cause);\n}\n/**\n* Turns anything thrown into a `TRPCError`. A `TRPCError` is returned as\n* is; anything else becomes an `INTERNAL_SERVER_ERROR` with it as the\n* cause.\n*/\nfunction getTRPCErrorFromUnknown(cause) {\n\tif (cause instanceof TRPCError) return cause;\n\tif (cause instanceof Error && cause.name === \"TRPCError\") return cause;\n\tconst trpcError = new TRPCError({\n\t\tcode: \"INTERNAL_SERVER_ERROR\",\n\t\tcause\n\t});\n\tif (isErrorLike(cause) && cause.stack) trpcError.stack = cause.stack;\n\treturn trpcError;\n}\n/**\n* An error with a tRPC error code, which sets the HTTP status and the code\n* the client sees. Throw it from resolvers and middlewares.\n* @example\n* ```ts\n* throw new TRPCError({ code: 'NOT_FOUND', message: 'No such post' });\n* ```\n* @see https://trpc.io/docs/server/error-handling#throwing-errors\n*/\nvar TRPCError = class extends Error {\n\tconstructor(opts) {\n\t\tvar _ref, _opts$message, _this$cause;\n\t\tconst cause = getCauseFromUnknown(opts.cause);\n\t\tconst message = (_ref = (_opts$message = opts.message) !== null && _opts$message !== void 0 ? _opts$message : cause === null || cause === void 0 ? void 0 : cause.message) !== null && _ref !== void 0 ? _ref : opts.code;\n\t\tsuper(message, { cause });\n\t\t_defineProperty(this, \"cause\", void 0);\n\t\t_defineProperty(this, \"code\", void 0);\n\t\tthis.code = opts.code;\n\t\tthis.name = \"TRPCError\";\n\t\t(_this$cause = this.cause) !== null && _this$cause !== void 0 || (this.cause = cause);\n\t}\n};\n// src/unstable-core-do-not-import/transformer.ts\n/**\n* @internal\n*/\nfunction getDataTransformer(transformer) {\n\tif (\"input\" in transformer) return transformer;\n\treturn {\n\t\tinput: transformer,\n\t\toutput: transformer\n\t};\n}\n/**\n* @internal\n*/\nconst defaultTransformer = {\n\tinput: {\n\t\tserialize: (obj) => obj,\n\t\tdeserialize: (obj) => obj\n\t},\n\toutput: {\n\t\tserialize: (obj) => obj,\n\t\tdeserialize: (obj) => obj\n\t}\n};\nfunction transformTRPCResponseItem(config, item) {\n\tif (\"error\" in item) return _objectSpread2(_objectSpread2({}, item), {}, { error: config.transformer.output.serialize(item.error) });\n\tif (\"data\" in item.result) return _objectSpread2(_objectSpread2({}, item), {}, { result: _objectSpread2(_objectSpread2({}, item.result), {}, { data: config.transformer.output.serialize(item.result.data) }) });\n\treturn item;\n}\n/**\n* Serializes a response, or a list of them, with the router's output\n* transformer. Meant for custom adapters.\n**/\nfunction transformTRPCResponse(config, itemOrItems) {\n\treturn Array.isArray(itemOrItems) ? itemOrItems.map((item) => transformTRPCResponseItem(config, item)) : transformTRPCResponseItem(config, itemOrItems);\n}\n/** @internal */\nfunction transformResultInner(response, transformer) {\n\tif (\"error\" in response) {\n\t\tconst error = transformer.deserialize(response.error);\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: _objectSpread2(_objectSpread2({}, response), {}, { error })\n\t\t};\n\t}\n\treturn {\n\t\tok: true,\n\t\tresult: _objectSpread2(_objectSpread2({}, response.result), (!response.result.type || response.result.type === \"data\") && {\n\t\t\ttype: \"data\",\n\t\t\tdata: transformer.deserialize(response.result.data)\n\t\t})\n\t};\n}\nvar TransformResultError = class extends Error {\n\tconstructor() {\n\t\tsuper(\"Unable to transform response from server\");\n\t}\n};\n/**\n* Transforms and validates that the result is a valid TRPCResponse\n* @internal\n*/\nfunction transformResult(response, transformer) {\n\tlet result;\n\ttry {\n\t\tresult = transformResultInner(response, transformer);\n\t} catch (_unused) {\n\t\tthrow new TransformResultError();\n\t}\n\tif (!result.ok && (!isObject(result.error.error) || typeof result.error.error[\"code\"] !== \"number\")) throw new TransformResultError();\n\tif (result.ok && !isObject(result.result)) throw new TransformResultError();\n\treturn result;\n}\n// src/unstable-core-do-not-import/router.ts\n/**\n* @internal\n*/\nconst lazyMarker = \"lazyMarker\";\nfunction once(fn) {\n\tconst uncalled = Symbol();\n\tlet result = uncalled;\n\treturn () => {\n\t\tif (result === uncalled) result = fn();\n\t\treturn result;\n\t};\n}\n/**\n* Loads a router on its first call instead of at startup, which can make\n* cold starts faster. Pass a function that imports the router, or a module\n* whose only export is the router.\n* @example\n* ```ts\n* const appRouter = router({\n* slow: lazy(() => import('./slow.js').then((m) => m.slowRouter)),\n* });\n* ```\n* @see https://trpc.io/docs/server/merging-routers#lazy-load\n*/\nfunction lazy(importRouter) {\n\tasync function resolve() {\n\t\tconst mod = await importRouter();\n\t\tif (isRouter(mod)) return mod;\n\t\tconst routers = Object.values(mod);\n\t\tif (routers.length !== 1 || !isRouter(routers[0])) throw new Error(\"Invalid router module - either define exactly 1 export or return the router directly.\\nExample: `lazy(() => import('./slow.js').then((m) => m.slowRouter))`\");\n\t\treturn routers[0];\n\t}\n\tresolve[lazyMarker] = true;\n\treturn resolve;\n}\nfunction isLazy(input) {\n\treturn typeof input === \"function\" && lazyMarker in input;\n}\nfunction isRouter(value) {\n\treturn isObject(value) && isObject(value[\"_def\"]) && \"router\" in value[\"_def\"];\n}\nconst emptyRouter = {\n\t_ctx: null,\n\t_errorShape: null,\n\t_meta: null,\n\tqueries: {},\n\tmutations: {},\n\tsubscriptions: {},\n\terrorFormatter: defaultFormatter,\n\ttransformer: defaultTransformer\n};\n/**\n* Reserved words that can't be used as router or procedure names\n*/\nconst reservedWords = [\n\t\"then\",\n\t\"call\",\n\t\"apply\"\n];\nfunction getRouterInput(router) {\n\tconst input = Object.assign(emptyObject(), router._def.record);\n\tfor (const loader of Object.values(router._def.lazy)) {\n\t\tlet record = input;\n\t\tfor (const key of loader.path) record = record[key] = Object.assign(emptyObject(), record[key]);\n\t\trecord[loader.key] = loader.ref;\n\t}\n\treturn input;\n}\n/**\n* @internal\n*/\nfunction createRouterFactory(config) {\n\tfunction createRouterInner(input) {\n\t\tconst reservedWordsUsed = new Set(Object.keys(input).filter((v) => reservedWords.includes(v)));\n\t\tif (reservedWordsUsed.size > 0) throw new Error(\"Reserved words used in `router({})` call: \" + Array.from(reservedWordsUsed).join(\", \"));\n\t\tconst procedures = emptyObject();\n\t\tconst lazy = emptyObject();\n\t\tfunction createLazyLoader(opts) {\n\t\t\treturn {\n\t\t\t\tref: opts.ref,\n\t\t\t\tpath: opts.path,\n\t\t\t\tkey: opts.key,\n\t\t\t\tload: once(async () => {\n\t\t\t\t\tconst router = await opts.ref();\n\t\t\t\t\tconst lazyPath = [...opts.path, opts.key];\n\t\t\t\t\tconst lazyKey = lazyPath.join(\".\");\n\t\t\t\t\topts.aggregate[opts.key] = step(getRouterInput(router), lazyPath);\n\t\t\t\t\tdelete lazy[lazyKey];\n\t\t\t\t})\n\t\t\t};\n\t\t}\n\t\tconst separator = config.pathSeparator;\n\t\tfunction step(from, path = []) {\n\t\t\tconst aggregate = emptyObject();\n\t\t\tfor (const [key, item] of Object.entries(from !== null && from !== void 0 ? from : {})) {\n\t\t\t\tif (separator !== \".\" && key.includes(separator)) throw new Error(`Key \"${[...path, key].join(\".\")}\" contains the pathSeparator ${JSON.stringify(separator)}, so its URL would be ambiguous. Rename it or pick another pathSeparator.`);\n\t\t\t\tif (isLazy(item)) {\n\t\t\t\t\tlazy[[...path, key].join(\".\")] = createLazyLoader({\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\tref: item,\n\t\t\t\t\t\tkey,\n\t\t\t\t\t\taggregate\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (isRouter(item)) {\n\t\t\t\t\taggregate[key] = step(getRouterInput(item), [...path, key]);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!isProcedure(item)) {\n\t\t\t\t\taggregate[key] = step(item, [...path, key]);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst newPath = [...path, key].join(\".\");\n\t\t\t\tif (procedures[newPath]) throw new Error(`Duplicate key: ${newPath}`);\n\t\t\t\tprocedures[newPath] = item;\n\t\t\t\taggregate[key] = item;\n\t\t\t}\n\t\t\treturn aggregate;\n\t\t}\n\t\tconst record = step(input);\n\t\tconst _def = _objectSpread2(_objectSpread2({\n\t\t\t_config: config,\n\t\t\trouter: true,\n\t\t\tprocedures,\n\t\t\tlazy\n\t\t}, emptyRouter), {}, { record });\n\t\treturn _objectSpread2(_objectSpread2({}, record), {}, {\n\t\t\t_def,\n\t\t\tcreateCaller: createCallerFactory()({ _def })\n\t\t});\n\t}\n\treturn createRouterInner;\n}\nfunction isProcedure(procedureOrRouter) {\n\treturn typeof procedureOrRouter === \"function\";\n}\n/**\n* @internal\n*/\nasync function getProcedureAtPath(router, path) {\n\tconst { _def } = router;\n\tlet procedure = _def.procedures[path];\n\twhile (!procedure) {\n\t\tconst key = Object.keys(_def.lazy).find((key) => path === key || path.startsWith(key + \".\"));\n\t\tif (!key) return null;\n\t\tawait _def.lazy[key].load();\n\t\tprocedure = _def.procedures[path];\n\t}\n\treturn procedure;\n}\n/**\n* Calls the procedure at `path`, throwing `NOT_FOUND` if there's none of\n* that type.\n* @internal\n*/\nasync function callProcedure(opts) {\n\tconst { type, path } = opts;\n\tconst proc = await getProcedureAtPath(opts.router, path);\n\tif (!proc || !isProcedure(proc) || proc._def.type !== type && !opts.allowMethodOverride) throw new TRPCError({\n\t\tcode: \"NOT_FOUND\",\n\t\tmessage: `No \"${type}\"-procedure on path \"${path}\"`\n\t});\n\t/* istanbul ignore if -- @preserve */\n\tif (proc._def.type !== type && opts.allowMethodOverride && proc._def.type === \"subscription\") throw new TRPCError({\n\t\tcode: \"METHOD_NOT_SUPPORTED\",\n\t\tmessage: `Method override is not supported for subscriptions`\n\t});\n\treturn proc(opts);\n}\nfunction createCallerFactory() {\n\treturn function createCallerInner(router) {\n\t\tconst { _def } = router;\n\t\treturn function createCaller(ctxOrCallback, opts) {\n\t\t\treturn createRecursiveProxy(async (innerOpts) => {\n\t\t\t\tconst { path, args } = innerOpts;\n\t\t\t\tconst fullPath = path.join(\".\");\n\t\t\t\tif (path.length === 1 && path[0] === \"_def\") return _def;\n\t\t\t\tconst procedure = await getProcedureAtPath(router, fullPath);\n\t\t\t\tlet ctx = void 0;\n\t\t\t\ttry {\n\t\t\t\t\tif (!procedure) throw new TRPCError({\n\t\t\t\t\t\tcode: \"NOT_FOUND\",\n\t\t\t\t\t\tmessage: `No procedure found on path \"${path}\"`\n\t\t\t\t\t});\n\t\t\t\t\tctx = isFunction(ctxOrCallback) ? await Promise.resolve(ctxOrCallback()) : ctxOrCallback;\n\t\t\t\t\treturn await procedure({\n\t\t\t\t\t\tpath: fullPath,\n\t\t\t\t\t\tgetRawInput: async () => args[0],\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\ttype: procedure._def.type,\n\t\t\t\t\t\tsignal: opts === null || opts === void 0 ? void 0 : opts.signal,\n\t\t\t\t\t\tbatchIndex: 0\n\t\t\t\t\t});\n\t\t\t\t} catch (cause) {\n\t\t\t\t\tvar _opts$onError, _procedure$_def$type;\n\t\t\t\t\topts === null || opts === void 0 || (_opts$onError = opts.onError) === null || _opts$onError === void 0 || _opts$onError.call(opts, {\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\terror: getTRPCErrorFromUnknown(cause),\n\t\t\t\t\t\tinput: args[0],\n\t\t\t\t\t\tpath: fullPath,\n\t\t\t\t\t\ttype: (_procedure$_def$type = procedure === null || procedure === void 0 ? void 0 : procedure._def.type) !== null && _procedure$_def$type !== void 0 ? _procedure$_def$type : \"unknown\"\n\t\t\t\t\t});\n\t\t\t\t\tthrow cause;\n\t\t\t\t}\n\t\t\t});\n\t\t};\n\t};\n}\nfunction mergeRouters(...routerList) {\n\tvar _routerList$, _routerList$2;\n\tconst record = mergeWithoutOverrides({}, ...[...new Set(routerList)].map((r) => getRouterInput(r)));\n\treturn createRouterFactory({\n\t\terrorFormatter: routerList.reduce((currentErrorFormatter, nextRouter) => {\n\t\t\tif (nextRouter._def._config.errorFormatter && nextRouter._def._config.errorFormatter !== defaultFormatter) {\n\t\t\t\tif (currentErrorFormatter !== defaultFormatter && currentErrorFormatter !== nextRouter._def._config.errorFormatter) throw new Error(\"You seem to have several error formatters\");\n\t\t\t\treturn nextRouter._def._config.errorFormatter;\n\t\t\t}\n\t\t\treturn currentErrorFormatter;\n\t\t}, defaultFormatter),\n\t\ttransformer: routerList.reduce((prev, current) => {\n\t\t\tif (current._def._config.transformer && current._def._config.transformer !== defaultTransformer) {\n\t\t\t\tif (prev !== defaultTransformer && prev !== current._def._config.transformer) throw new Error(\"You seem to have several transformers\");\n\t\t\t\treturn current._def._config.transformer;\n\t\t\t}\n\t\t\treturn prev;\n\t\t}, defaultTransformer),\n\t\tpathSeparator: routerList.reduce((prev, current) => {\n\t\t\tconst next = current._def._config.pathSeparator;\n\t\t\tif (next === \".\") return prev;\n\t\t\tif (prev !== \".\" && prev !== next) throw new Error(\"You seem to have several pathSeparators\");\n\t\t\treturn next;\n\t\t}, \".\"),\n\t\tisDev: routerList.every((r) => r._def._config.isDev),\n\t\tallowOutsideOfServer: routerList.every((r) => r._def._config.allowOutsideOfServer),\n\t\tisServer: routerList.every((r) => r._def._config.isServer),\n\t\t$types: (_routerList$ = routerList[0]) === null || _routerList$ === void 0 ? void 0 : _routerList$._def._config.$types,\n\t\tsse: (_routerList$2 = routerList[0]) === null || _routerList$2 === void 0 ? void 0 : _routerList$2._def._config.sse\n\t})(record);\n}\n// src/unstable-core-do-not-import/http/pathSeparator.ts\n/**\n* Applies the `'.'` default to a user-given `pathSeparator` option. Call it\n* once, where the option is read.\n* @internal\n*/\nfunction resolvePathSeparator(value) {\n\treturn value !== null && value !== void 0 ? value : \".\";\n}\n/**\n* `post.byId` → `post~byId`, for building URLs.\n* @internal\n*/\nfunction procedurePathToURLPath(path, separator) {\n\tif (separator === \".\") return path;\n\treturn path.split(\".\").join(separator);\n}\n/**\n* `post~byId` → `post.byId`, for reading URLs. Dotted paths still resolve,\n* so clients can move to the separator after the server does.\n* @internal\n*/\nfunction urlPathToProcedurePath(path, separator) {\n\tif (separator === \".\") return path;\n\treturn path.split(separator).join(\".\");\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/OverloadYield.js\nfunction _OverloadYield(e, d) {\n\tthis.v = e, this.k = d;\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/wrapAsyncGenerator.js\nfunction _wrapAsyncGenerator(e) {\n\treturn function() {\n\t\treturn new AsyncGenerator(e.apply(this, arguments));\n\t};\n}\nfunction AsyncGenerator(e) {\n\tvar t, n;\n\tfunction resume(t, n) {\n\t\ttry {\n\t\t\tvar r = e[t](n), o = r.value, u = o instanceof _OverloadYield;\n\t\t\tPromise.resolve(u ? o.v : o).then(function(n) {\n\t\t\t\tif (u) {\n\t\t\t\t\tvar i = \"return\" === t && o.k ? t : \"next\";\n\t\t\t\t\tif (!o.k || n.done) return resume(i, n);\n\t\t\t\t\tn = e[i](n).value;\n\t\t\t\t}\n\t\t\t\tsettle(!!r.done, n);\n\t\t\t}, function(e) {\n\t\t\t\tresume(\"throw\", e);\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tsettle(2, e);\n\t\t}\n\t}\n\tfunction settle(e, r) {\n\t\t2 === e ? t.reject(r) : t.resolve({\n\t\t\tvalue: r,\n\t\t\tdone: e\n\t\t}), (t = t.next) ? resume(t.key, t.arg) : n = null;\n\t}\n\tthis._invoke = function(e, r) {\n\t\treturn new Promise(function(o, u) {\n\t\t\tvar i = {\n\t\t\t\tkey: e,\n\t\t\t\targ: r,\n\t\t\t\tresolve: o,\n\t\t\t\treject: u,\n\t\t\t\tnext: null\n\t\t\t};\n\t\t\tn ? n = n.next = i : (t = n = i, resume(e, r));\n\t\t});\n\t}, \"function\" != typeof e[\"return\"] && (this[\"return\"] = void 0);\n}\nAsyncGenerator.prototype[\"function\" == typeof Symbol && Symbol.asyncIterator || \"@@asyncIterator\"] = function() {\n\treturn this;\n}, AsyncGenerator.prototype.next = function(e) {\n\treturn this._invoke(\"next\", e);\n}, AsyncGenerator.prototype[\"throw\"] = function(e) {\n\treturn this._invoke(\"throw\", e);\n}, AsyncGenerator.prototype[\"return\"] = function(e) {\n\treturn this._invoke(\"return\", e);\n};\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/asyncIterator.js\nfunction _asyncIterator(r) {\n\tvar n, t, o, e = 2;\n\tfor (\"undefined\" != typeof Symbol && (t = Symbol.asyncIterator, o = Symbol.iterator); e--;) {\n\t\tif (t && null != (n = r[t])) return n.call(r);\n\t\tif (o && null != (n = r[o])) return new AsyncFromSyncIterator(n.call(r));\n\t\tt = \"@@asyncIterator\", o = \"@@iterator\";\n\t}\n\tthrow new TypeError(\"Object is not async iterable\");\n}\nfunction AsyncFromSyncIterator(r) {\n\tfunction AsyncFromSyncIteratorContinuation(r) {\n\t\tif (Object(r) !== r) return Promise.reject(/* @__PURE__ */ new TypeError(r + \" is not an object.\"));\n\t\tvar n = r.done;\n\t\treturn Promise.resolve(r.value).then(function(r) {\n\t\t\treturn {\n\t\t\t\tvalue: r,\n\t\t\t\tdone: n\n\t\t\t};\n\t\t});\n\t}\n\treturn AsyncFromSyncIterator = function AsyncFromSyncIterator(r) {\n\t\tthis.s = r, this.n = r.next;\n\t}, AsyncFromSyncIterator.prototype = {\n\t\ts: null,\n\t\tn: null,\n\t\tnext: function next() {\n\t\t\treturn AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));\n\t\t},\n\t\t\"return\": function _return(r) {\n\t\t\tvar n = this.s[\"return\"];\n\t\t\treturn void 0 === n ? Promise.resolve({\n\t\t\t\tvalue: r,\n\t\t\t\tdone: !0\n\t\t\t}) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));\n\t\t},\n\t\t\"throw\": function _throw(r) {\n\t\t\tvar n = this.s[\"throw\"];\n\t\t\treturn void 0 === n ? Promise.reject(r) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));\n\t\t}\n\t}, new AsyncFromSyncIterator(r);\n}\n// src/unstable-core-do-not-import/stream/tracked.ts\nconst trackedSymbol = Symbol();\n/**\n* Wraps an event with an id, so a client can resume from it.\n* @deprecated Use `tracked(id, data)` instead.\n*/\nfunction sse(event) {\n\treturn tracked(event.id, event.data);\n}\n/** Whether a value was made by `tracked()`. */\nfunction isTrackedEnvelope(value) {\n\treturn Array.isArray(value) && value[2] === trackedSymbol;\n}\n/**\n* Gives a subscription event an id. When the connection drops, the client\n* reconnects with the last id it got, as `input.lastEventId`, so the\n* subscription can resume from there. The id can't be empty.\n* @example\n* ```ts\n* yield tracked(post.id, post);\n* ```\n* @see https://trpc.io/docs/server/subscriptions#tracked\n*/\nfunction tracked(id, data) {\n\tif (id === \"\") throw new Error(\"`id` must not be an empty string as empty string is the same as not setting the id at all\");\n\tif (/[\\0\\n\\r]/.test(id)) throw new Error(\"`id` must not contain line breaks or null characters as they are not allowed in a Server-Sent Events id\");\n\treturn [\n\t\tid,\n\t\tdata,\n\t\ttrackedSymbol\n\t];\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/asyncGeneratorDelegate.js\nfunction _asyncGeneratorDelegate(t) {\n\tvar e = {}, n = !1;\n\tfunction pump(e, r) {\n\t\treturn n = !0, r = new Promise(function(n) {\n\t\t\tn(t[e](r));\n\t\t}), {\n\t\t\tdone: !1,\n\t\t\tvalue: new _OverloadYield(r, 1)\n\t\t};\n\t}\n\treturn e[\"undefined\" != typeof Symbol && Symbol.iterator || \"@@iterator\"] = function() {\n\t\treturn this;\n\t}, e.next = function(t) {\n\t\treturn n ? (n = !1, t) : pump(\"next\", t);\n\t}, \"function\" == typeof t[\"throw\"] && (e[\"throw\"] = function(t) {\n\t\tif (n) throw n = !1, t;\n\t\treturn pump(\"throw\", t);\n\t}), \"function\" == typeof t[\"return\"] && (e[\"return\"] = function(t) {\n\t\treturn n ? (n = !1, t) : pump(\"return\", t);\n\t}), e;\n}\nexport { getTRPCErrorFromUnknown as C, getCauseFromUnknown as S, defaultTransformer as _, _asyncIterator as a, transformTRPCResponse as b, procedurePathToURLPath as c, callProcedure as d, createCallerFactory as f, mergeRouters as g, lazy as h, tracked as i, resolvePathSeparator as l, getProcedureAtPath as m, isTrackedEnvelope as n, _wrapAsyncGenerator as o, createRouterFactory as p, sse as r, _OverloadYield as s, _asyncGeneratorDelegate as t, urlPathToProcedurePath as u, getDataTransformer as v, TRPCError as x, transformResult as y };\n\n\n//# sourceMappingURL=asyncGeneratorDelegate-BRQGtkYG.mjs.map", "import { n as _defineProperty, t as _objectSpread2 } from \"./objectSpread2-pyA4QVO4.mjs\";\nimport { isObject } from \"@trpc/server/unstable-core-do-not-import\";\n// src/TRPCClientError.ts\n/**\n* Whether a value is a `TRPCClientError`, typed for a router or procedure.\n* @see https://trpc.io/docs/client/vanilla/error-handling#catching-a-thrown-error\n*/\nfunction isTRPCClientError(cause) {\n\treturn cause instanceof TRPCClientError;\n}\nfunction isTRPCErrorResponse(obj) {\n\treturn isObject(obj) && isObject(obj[\"error\"]) && typeof obj[\"error\"][\"code\"] === \"number\" && typeof obj[\"error\"][\"message\"] === \"string\";\n}\nfunction getMessageFromUnknownError(err, fallback) {\n\tif (typeof err === \"string\") return err;\n\tif (isObject(err) && typeof err[\"message\"] === \"string\") return err[\"message\"];\n\treturn fallback;\n}\n/**\n* The error a client call throws, whether the server sent an error or the\n* request failed.\n* @see https://trpc.io/docs/client/vanilla/error-handling\n*/\nvar TRPCClientError = class TRPCClientError extends Error {\n\tconstructor(message, opts) {\n\t\tvar _opts$result, _opts$result2;\n\t\tconst cause = opts === null || opts === void 0 ? void 0 : opts.cause;\n\t\tsuper(message, { cause });\n\t\t_defineProperty(this, \"cause\", void 0);\n\t\t_defineProperty(this, \"shape\", void 0);\n\t\t_defineProperty(this, \"data\", void 0);\n\t\t_defineProperty(this, \"meta\", void 0);\n\t\tthis.meta = opts === null || opts === void 0 ? void 0 : opts.meta;\n\t\tthis.cause = cause;\n\t\tthis.shape = opts === null || opts === void 0 || (_opts$result = opts.result) === null || _opts$result === void 0 ? void 0 : _opts$result.error;\n\t\tthis.data = opts === null || opts === void 0 || (_opts$result2 = opts.result) === null || _opts$result2 === void 0 ? void 0 : _opts$result2.error.data;\n\t\tthis.name = \"TRPCClientError\";\n\t\tObject.setPrototypeOf(this, TRPCClientError.prototype);\n\t}\n\t/**\n\t* Turns an error response, an `Error` or another object into a\n\t* `TRPCClientError`. A `TRPCClientError` is returned as it is.\n\t*/\n\tstatic from(_cause, opts = {}) {\n\t\tconst cause = _cause;\n\t\tif (isTRPCClientError(cause)) {\n\t\t\tif (opts.meta) cause.meta = _objectSpread2(_objectSpread2({}, cause.meta), opts.meta);\n\t\t\treturn cause;\n\t\t}\n\t\tif (isTRPCErrorResponse(cause)) return new TRPCClientError(cause.error.message, _objectSpread2(_objectSpread2({}, opts), {}, {\n\t\t\tresult: cause,\n\t\t\tcause: opts.cause\n\t\t}));\n\t\treturn new TRPCClientError(getMessageFromUnknownError(cause, \"Unknown error\"), _objectSpread2(_objectSpread2({}, opts), {}, { cause }));\n\t}\n};\nexport { isTRPCClientError as n, TRPCClientError as t };\n\n//# sourceMappingURL=TRPCClientError-DE6-fd1n.mjs.map", "// src/internals/transformer.ts\n/**\n* @internal\n*/\n/**\n* @internal\n*/\nfunction getTransformer(transformer) {\n\tconst _transformer = transformer;\n\tif (!_transformer) return {\n\t\tinput: {\n\t\t\tserialize: (data) => data,\n\t\t\tdeserialize: (data) => data\n\t\t},\n\t\toutput: {\n\t\t\tserialize: (data) => data,\n\t\t\tdeserialize: (data) => data\n\t\t}\n\t};\n\tif (\"input\" in _transformer) return _transformer;\n\treturn {\n\t\tinput: _transformer,\n\t\toutput: _transformer\n\t};\n}\nexport { getTransformer };\n\n//# sourceMappingURL=unstable-internals.mjs.map", "import { getTransformer } from \"./unstable-internals.mjs\";\nimport { t as _objectSpread2 } from \"./objectSpread2-pyA4QVO4.mjs\";\nimport { procedurePathToURLPath, resolvePathSeparator } from \"@trpc/server/unstable-core-do-not-import\";\n// src/getFetch.ts\nconst isFunction = (fn) => typeof fn === \"function\";\n/**\n* The `fetch` to use: `customFetchImpl` if given, or else the global one.\n* Throws if there's none.\n*/\nfunction getFetch(customFetchImpl) {\n\tif (customFetchImpl) return customFetchImpl;\n\tif (typeof window !== \"undefined\" && isFunction(window.fetch)) return window.fetch.bind(window);\n\tif (typeof globalThis !== \"undefined\" && isFunction(globalThis.fetch)) return globalThis.fetch;\n\tthrow new Error(\"No fetch implementation found\");\n}\n// src/internals/signals.ts\n/**\n* Like `Promise.all()` but for abort signals\n* - When all signals have been aborted, the merged signal will be aborted\n* - If one signal is `null`, no signal will be aborted\n*/\nfunction allAbortSignals(...signals) {\n\tconst ac = new AbortController();\n\tconst count = signals.length;\n\tlet abortedCount = 0;\n\tconst onAbort = () => {\n\t\tif (++abortedCount === count) ac.abort();\n\t};\n\tfor (const signal of signals) if (signal === null || signal === void 0 ? void 0 : signal.aborted) onAbort();\n\telse signal === null || signal === void 0 || signal.addEventListener(\"abort\", onAbort, { once: true });\n\treturn ac.signal;\n}\n/**\n* Like `Promise.race` but for abort signals\n*\n* Basically, a ponyfill for\n* [`AbortSignal.any`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/any_static).\n*/\nfunction raceAbortSignals(...signals) {\n\treturn raceAbortSignalsWithCleanup(...signals).signal;\n}\nfunction raceAbortSignalsWithCleanup(...signals) {\n\tconst ac = new AbortController();\n\tconst cleanup = () => {\n\t\tfor (const signal of signals) signal === null || signal === void 0 || signal.removeEventListener(\"abort\", onAbort);\n\t};\n\tconst onAbort = () => {\n\t\tcleanup();\n\t\tac.abort();\n\t};\n\tfor (const signal of signals) {\n\t\tif (signal === null || signal === void 0 ? void 0 : signal.aborted) {\n\t\t\tonAbort();\n\t\t\tbreak;\n\t\t}\n\t\tsignal === null || signal === void 0 || signal.addEventListener(\"abort\", onAbort, { once: true });\n\t}\n\treturn {\n\t\tsignal: ac.signal,\n\t\tcleanup\n\t};\n}\nfunction abortSignalToPromise(signal) {\n\treturn new Promise((_, reject) => {\n\t\tif (signal.aborted) {\n\t\t\treject(signal.reason);\n\t\t\treturn;\n\t\t}\n\t\tsignal.addEventListener(\"abort\", () => {\n\t\t\treject(signal.reason);\n\t\t}, { once: true });\n\t});\n}\n/**\n* Polyfill for DOMException with AbortError name\n*/\nvar AbortError = class extends Error {\n\tconstructor() {\n\t\tconst name = \"AbortError\";\n\t\tsuper(name);\n\t\tthis.name = name;\n\t\tthis.message = name;\n\t}\n};\n/**\n* Polyfill for `signal.throwIfAborted()`\n*\n* @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/throwIfAborted\n*/\nconst throwIfAborted = (signal) => {\n\tvar _signal$throwIfAborte;\n\tif (!(signal === null || signal === void 0 ? void 0 : signal.aborted)) return;\n\t(_signal$throwIfAborte = signal.throwIfAborted) === null || _signal$throwIfAborte === void 0 || _signal$throwIfAborte.call(signal);\n\tif (typeof DOMException !== \"undefined\") throw new DOMException(\"AbortError\", \"AbortError\");\n\tthrow new AbortError();\n};\n// src/links/internals/httpUtils.ts\nfunction resolveHTTPLinkOptions(opts) {\n\treturn {\n\t\turl: opts.url.toString(),\n\t\tfetch: opts.fetch,\n\t\ttransformer: getTransformer(opts.transformer),\n\t\tmethodOverride: opts.methodOverride,\n\t\tpathSeparator: resolvePathSeparator(opts.pathSeparator)\n\t};\n}\nfunction arrayToDict(array) {\n\tconst dict = {};\n\tfor (let index = 0; index < array.length; index++) {\n\t\tconst element = array[index];\n\t\tdict[index] = element;\n\t}\n\treturn dict;\n}\nconst METHOD = {\n\tquery: \"GET\",\n\tmutation: \"POST\",\n\tsubscription: \"PATCH\"\n};\nfunction getInput(opts) {\n\treturn \"input\" in opts ? opts.transformer.input.serialize(opts.input) : arrayToDict(opts.inputs.map((_input) => opts.transformer.input.serialize(_input)));\n}\nconst getUrl = (opts) => {\n\tconst parts = opts.url.split(\"?\");\n\tlet url = parts[0].replace(/\\/$/, \"\") + \"/\" + procedurePathToURLPath(opts.path, opts.pathSeparator);\n\tconst queryParts = [];\n\tif (parts[1]) queryParts.push(parts[1]);\n\tif (\"inputs\" in opts) queryParts.push(\"batch=1\");\n\tif (opts.type === \"query\" || opts.type === \"subscription\") {\n\t\tconst input = getInput(opts);\n\t\tif (input !== void 0 && opts.methodOverride !== \"POST\") queryParts.push(`input=${encodeURIComponent(JSON.stringify(input))}`);\n\t}\n\tif (queryParts.length) url += \"?\" + queryParts.join(\"&\");\n\treturn url;\n};\nconst getBody = (opts) => {\n\tif (opts.type === \"query\" && opts.methodOverride !== \"POST\") return;\n\tconst input = getInput(opts);\n\treturn input !== void 0 ? JSON.stringify(input) : void 0;\n};\nconst jsonHttpRequester = (opts) => {\n\treturn httpRequest(_objectSpread2(_objectSpread2({}, opts), {}, {\n\t\tcontentTypeHeader: \"application/json\",\n\t\tgetUrl,\n\t\tgetBody\n\t}));\n};\nasync function fetchHTTPResponse(opts) {\n\tvar _opts$methodOverride, _opts$trpcAcceptHeade;\n\tthrowIfAborted(opts.signal);\n\tconst url = opts.getUrl(opts);\n\tconst body = opts.getBody(opts);\n\tconst method = (_opts$methodOverride = opts.methodOverride) !== null && _opts$methodOverride !== void 0 ? _opts$methodOverride : METHOD[opts.type];\n\tconst resolvedHeaders = await (async () => {\n\t\tconst heads = await opts.headers();\n\t\tif (Symbol.iterator in heads) return Object.fromEntries(heads);\n\t\treturn heads;\n\t})();\n\tconst hasContentType = Object.keys(resolvedHeaders).some((key) => key.toLowerCase() === \"content-type\");\n\tconst headers = _objectSpread2(_objectSpread2(_objectSpread2({}, opts.contentTypeHeader && method !== \"GET\" && !hasContentType ? { \"content-type\": opts.contentTypeHeader } : {}), opts.trpcAcceptHeader ? { [(_opts$trpcAcceptHeade = opts.trpcAcceptHeaderKey) !== null && _opts$trpcAcceptHeade !== void 0 ? _opts$trpcAcceptHeade : \"trpc-accept\"]: opts.trpcAcceptHeader } : void 0), resolvedHeaders);\n\treturn getFetch(opts.fetch)(url, {\n\t\tmethod,\n\t\tsignal: opts.signal,\n\t\tbody,\n\t\theaders\n\t});\n}\nasync function httpRequest(opts) {\n\tconst meta = {};\n\tconst res = await fetchHTTPResponse(opts);\n\tmeta.response = res;\n\tconst json = await res.json();\n\tmeta.responseJSON = json;\n\treturn {\n\t\tjson,\n\t\tmeta\n\t};\n}\nexport { jsonHttpRequester as a, allAbortSignals as c, throwIfAborted as d, getFetch as f, httpRequest as i, raceAbortSignals as l, getBody as n, resolveHTTPLinkOptions as o, getUrl as r, abortSignalToPromise as s, fetchHTTPResponse as t, raceAbortSignalsWithCleanup as u };\n\n//# sourceMappingURL=httpUtils-CtMuyl9j.mjs.map", "import { a as jsonHttpRequester, c as allAbortSignals, o as resolveHTTPLinkOptions, r as getUrl, u as raceAbortSignalsWithCleanup } from \"./httpUtils-CtMuyl9j.mjs\";\nimport { t as TRPCClientError } from \"./TRPCClientError-DE6-fd1n.mjs\";\nimport { t as _objectSpread2 } from \"./objectSpread2-pyA4QVO4.mjs\";\nimport { observable } from \"@trpc/server/observable\";\nimport { transformResult } from \"@trpc/server/unstable-core-do-not-import\";\n// src/internals/dataLoader.ts\n/**\n* A function that should never be called unless we messed something up.\n*/\nconst throwFatalError = () => {\n\tthrow new Error(\"Something went wrong. Please submit an issue at https://github.com/trpc/trpc/issues/new\");\n};\n/**\n* Dataloader that's very inspired by https://github.com/graphql/dataloader\n* Less configuration, no caching, and allows you to cancel requests\n* When cancelling a single fetch the whole batch will be cancelled only when _all_ items are cancelled\n*/\nfunction dataLoader(batchLoader) {\n\tlet pendingItems = null;\n\tlet dispatchTimer = null;\n\tconst destroyTimerAndPendingItems = () => {\n\t\tclearTimeout(dispatchTimer);\n\t\tdispatchTimer = null;\n\t\tpendingItems = null;\n\t};\n\t/**\n\t* Iterate through the items and split them into groups based on the `batchLoader`'s validate function\n\t*/\n\tfunction groupItems(items) {\n\t\tconst groupedItems = [[]];\n\t\tlet index = 0;\n\t\twhile (true) {\n\t\t\tconst item = items[index];\n\t\t\tif (!item) break;\n\t\t\tconst lastGroup = groupedItems[groupedItems.length - 1];\n\t\t\tif (item.aborted) {\n\t\t\t\tvar _item$reject;\n\t\t\t\t(_item$reject = item.reject) === null || _item$reject === void 0 || _item$reject.call(item, /* @__PURE__ */ new Error(\"Aborted\"));\n\t\t\t\tindex++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlet isValid;\n\t\t\ttry {\n\t\t\t\tisValid = batchLoader.validate(lastGroup.concat(item).map((it) => it.key));\n\t\t\t} catch (cause) {\n\t\t\t\tvar _item$reject2;\n\t\t\t\t(_item$reject2 = item.reject) === null || _item$reject2 === void 0 || _item$reject2.call(item, cause);\n\t\t\t\tindex++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (isValid) {\n\t\t\t\tlastGroup.push(item);\n\t\t\t\tindex++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (lastGroup.length === 0) {\n\t\t\t\tvar _item$reject3;\n\t\t\t\t(_item$reject3 = item.reject) === null || _item$reject3 === void 0 || _item$reject3.call(item, /* @__PURE__ */ new Error(\"Input is too big for a single dispatch\"));\n\t\t\t\tindex++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tgroupedItems.push([]);\n\t\t}\n\t\treturn groupedItems;\n\t}\n\tfunction dispatch() {\n\t\tconst groupedItems = groupItems(pendingItems);\n\t\tdestroyTimerAndPendingItems();\n\t\tfor (const items of groupedItems) {\n\t\t\tif (!items.length) continue;\n\t\t\tconst batch = { items };\n\t\t\tfor (const item of items) item.batch = batch;\n\t\t\tbatchLoader.fetch(batch.items.map((_item) => _item.key)).then(async (result) => {\n\t\t\t\tawait Promise.all(result.map(async (valueOrPromise, index) => {\n\t\t\t\t\tconst item = batch.items[index];\n\t\t\t\t\ttry {\n\t\t\t\t\t\tvar _item$resolve;\n\t\t\t\t\t\tconst value = await Promise.resolve(valueOrPromise);\n\t\t\t\t\t\t(_item$resolve = item.resolve) === null || _item$resolve === void 0 || _item$resolve.call(item, value);\n\t\t\t\t\t} catch (cause) {\n\t\t\t\t\t\tvar _item$reject4;\n\t\t\t\t\t\t(_item$reject4 = item.reject) === null || _item$reject4 === void 0 || _item$reject4.call(item, cause);\n\t\t\t\t\t}\n\t\t\t\t\titem.batch = null;\n\t\t\t\t\titem.reject = null;\n\t\t\t\t\titem.resolve = null;\n\t\t\t\t}));\n\t\t\t\tfor (const item of batch.items) {\n\t\t\t\t\tvar _item$reject5;\n\t\t\t\t\t(_item$reject5 = item.reject) === null || _item$reject5 === void 0 || _item$reject5.call(item, /* @__PURE__ */ new Error(\"Missing result\"));\n\t\t\t\t\titem.batch = null;\n\t\t\t\t}\n\t\t\t}).catch((cause) => {\n\t\t\t\tfor (const item of batch.items) {\n\t\t\t\t\tvar _item$reject6;\n\t\t\t\t\t(_item$reject6 = item.reject) === null || _item$reject6 === void 0 || _item$reject6.call(item, cause);\n\t\t\t\t\titem.batch = null;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\tfunction load(key) {\n\t\tvar _dispatchTimer;\n\t\tconst item = {\n\t\t\taborted: false,\n\t\t\tkey,\n\t\t\tbatch: null,\n\t\t\tresolve: throwFatalError,\n\t\t\treject: throwFatalError\n\t\t};\n\t\tconst promise = new Promise((resolve, reject) => {\n\t\t\tvar _pendingItems;\n\t\t\titem.reject = reject;\n\t\t\titem.resolve = resolve;\n\t\t\t(_pendingItems = pendingItems) !== null && _pendingItems !== void 0 || (pendingItems = []);\n\t\t\tpendingItems.push(item);\n\t\t});\n\t\t(_dispatchTimer = dispatchTimer) !== null && _dispatchTimer !== void 0 || (dispatchTimer = setTimeout(dispatch));\n\t\treturn promise;\n\t}\n\treturn { load };\n}\n// src/links/httpBatchLink.ts\n/**\n* A terminating link that batches calls made in the same tick into one HTTP\n* request.\n*\n* @see https://trpc.io/docs/client/links/httpBatchLink\n*/\nfunction httpBatchLink(opts) {\n\tvar _opts$maxURLLength, _opts$maxItems;\n\tconst resolvedOpts = resolveHTTPLinkOptions(opts);\n\tconst maxURLLength = (_opts$maxURLLength = opts.maxURLLength) !== null && _opts$maxURLLength !== void 0 ? _opts$maxURLLength : Infinity;\n\tconst maxItems = (_opts$maxItems = opts.maxItems) !== null && _opts$maxItems !== void 0 ? _opts$maxItems : Infinity;\n\treturn () => {\n\t\tconst batchLoader = (type) => {\n\t\t\treturn {\n\t\t\t\tvalidate(batchOps) {\n\t\t\t\t\tif (maxURLLength === Infinity && maxItems === Infinity) return true;\n\t\t\t\t\tif (batchOps.length > maxItems) return false;\n\t\t\t\t\tconst path = batchOps.map((op) => op.path).join(\",\");\n\t\t\t\t\tconst inputs = batchOps.map((op) => op.input);\n\t\t\t\t\treturn getUrl(_objectSpread2(_objectSpread2({}, resolvedOpts), {}, {\n\t\t\t\t\t\ttype,\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\tinputs,\n\t\t\t\t\t\tsignal: null\n\t\t\t\t\t})).length <= maxURLLength;\n\t\t\t\t},\n\t\t\t\tasync fetch(batchOps) {\n\t\t\t\t\tconst path = batchOps.map((op) => op.path).join(\",\");\n\t\t\t\t\tconst inputs = batchOps.map((op) => op.input);\n\t\t\t\t\tconst signal = allAbortSignals(...batchOps.map((op) => op.signal));\n\t\t\t\t\tconst res = await jsonHttpRequester(_objectSpread2(_objectSpread2({}, resolvedOpts), {}, {\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\tinputs,\n\t\t\t\t\t\ttype,\n\t\t\t\t\t\theaders() {\n\t\t\t\t\t\t\tif (!opts.headers) return {};\n\t\t\t\t\t\t\tif (typeof opts.headers === \"function\") return opts.headers({ opList: batchOps });\n\t\t\t\t\t\t\treturn opts.headers;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsignal\n\t\t\t\t\t}));\n\t\t\t\t\treturn (Array.isArray(res.json) ? res.json : batchOps.map(() => res.json)).map((item) => ({\n\t\t\t\t\t\tmeta: res.meta,\n\t\t\t\t\t\tjson: item\n\t\t\t\t\t}));\n\t\t\t\t}\n\t\t\t};\n\t\t};\n\t\tconst loaders = {\n\t\t\tquery: dataLoader(batchLoader(\"query\")),\n\t\t\tmutation: dataLoader(batchLoader(\"mutation\"))\n\t\t};\n\t\treturn ({ op }) => {\n\t\t\treturn observable((observer) => {\n\t\t\t\t/* istanbul ignore if -- @preserve */\n\t\t\t\tif (op.type === \"subscription\") throw new Error(\"Subscriptions are unsupported by `httpLink` - use `httpSubscriptionLink` or `wsLink`\");\n\t\t\t\tconst ac = new AbortController();\n\t\t\t\tconst { signal, cleanup } = raceAbortSignalsWithCleanup(op.signal, ac.signal);\n\t\t\t\tconst promise = loaders[op.type].load(_objectSpread2(_objectSpread2({}, op), {}, { signal }));\n\t\t\t\tlet isDone = false;\n\t\t\t\tlet _res = void 0;\n\t\t\t\tpromise.then((res) => {\n\t\t\t\t\tisDone = true;\n\t\t\t\t\t_res = res;\n\t\t\t\t\tconst transformed = transformResult(res.json, resolvedOpts.transformer.output);\n\t\t\t\t\tif (!transformed.ok) {\n\t\t\t\t\t\tobserver.error(TRPCClientError.from(transformed.error, { meta: res.meta }));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tobserver.next({\n\t\t\t\t\t\tcontext: res.meta,\n\t\t\t\t\t\tresult: transformed.result\n\t\t\t\t\t});\n\t\t\t\t\tobserver.complete();\n\t\t\t\t}).catch((err) => {\n\t\t\t\t\tisDone = true;\n\t\t\t\t\tobserver.error(TRPCClientError.from(err, { meta: _res === null || _res === void 0 ? void 0 : _res.meta }));\n\t\t\t\t});\n\t\t\t\treturn () => {\n\t\t\t\t\tif (!isDone) ac.abort();\n\t\t\t\t\tcleanup();\n\t\t\t\t};\n\t\t\t});\n\t\t};\n\t};\n}\nexport { dataLoader as n, httpBatchLink as t };\n\n//# sourceMappingURL=httpBatchLink-BkVNtNND.mjs.map", "import { getTransformer } from \"./unstable-internals.mjs\";\nimport { t as TRPCClientError } from \"./TRPCClientError-DE6-fd1n.mjs\";\nimport { n as _defineProperty, t as _objectSpread2 } from \"./objectSpread2-pyA4QVO4.mjs\";\nimport { behaviorSubject, observable } from \"@trpc/server/observable\";\nimport { run, sleep, transformResult } from \"@trpc/server/unstable-core-do-not-import\";\n// src/links/wsLink/wsClient/encoder.ts\n/**\n* The default WebSocket encoder. Sends messages as JSON text frames.\n*/\nconst jsonEncoder = {\n\tencode: (data) => JSON.stringify(data),\n\tdecode: (data) => {\n\t\tif (typeof data !== \"string\") throw new Error(\"jsonEncoder received binary data. JSON uses text frames. Use a binary encoder for binary data.\");\n\t\treturn JSON.parse(data);\n\t}\n};\n// src/links/wsLink/wsClient/options.ts\nconst lazyDefaults = {\n\tenabled: false,\n\tcloseMs: 0\n};\nconst keepAliveDefaults = {\n\tenabled: false,\n\tpongTimeoutMs: 1e3,\n\tintervalMs: 5e3\n};\n/**\n* Calculates a delay for exponential backoff based on the retry attempt index.\n* The delay starts at 0 for the first attempt and doubles for each subsequent attempt,\n* capped at 30 seconds.\n*/\nconst exponentialBackoff = (attemptIndex) => {\n\treturn attemptIndex === 0 ? 0 : Math.min(1e3 * 2 ** attemptIndex, 3e4);\n};\n// src/links/internals/urlWithConnectionParams.ts\n/**\n* Get the result of a value or function that returns a value\n* It also optionally accepts typesafe arguments for the function\n*/\nconst resultOf = (value, ...args) => {\n\treturn typeof value === \"function\" ? value(...args) : value;\n};\n// src/links/wsLink/wsClient/utils.ts\nvar TRPCWebSocketClosedError = class TRPCWebSocketClosedError extends Error {\n\tconstructor(opts) {\n\t\tsuper(opts.message, { cause: opts.cause });\n\t\tthis.name = \"TRPCWebSocketClosedError\";\n\t\tObject.setPrototypeOf(this, TRPCWebSocketClosedError.prototype);\n\t}\n};\n/**\n* Calls a user callback, including `connectionState` subscribers. A throw\n* would skip the rest of the client's bookkeeping (e.g. end the reconnect\n* loop, or, with event-emitter based WebSockets such as `ws`, skip the other\n* listeners for that event), so it is rethrown asynchronously instead.\n*/\nfunction callUserCallback(callback) {\n\ttry {\n\t\tcallback();\n\t} catch (error) {\n\t\tsetTimeout(() => {\n\t\t\tthrow error;\n\t\t});\n\t}\n}\n/**\n* Utility class for managing a timeout that can be started, stopped, and reset.\n* Useful for scenarios where the timeout duration is reset dynamically based on events.\n*/\nvar ResettableTimeout = class {\n\tconstructor(onTimeout, timeoutMs) {\n\t\tthis.onTimeout = onTimeout;\n\t\tthis.timeoutMs = timeoutMs;\n\t\t_defineProperty(this, \"timeout\", void 0);\n\t}\n\t/**\n\t* Resets the current timeout, restarting it with the same duration.\n\t* Does nothing if no timeout is active.\n\t*/\n\treset() {\n\t\tif (!this.timeout) return;\n\t\tclearTimeout(this.timeout);\n\t\tthis.timeout = setTimeout(this.onTimeout, this.timeoutMs);\n\t}\n\tstart() {\n\t\tclearTimeout(this.timeout);\n\t\tthis.timeout = setTimeout(this.onTimeout, this.timeoutMs);\n\t}\n\tstop() {\n\t\tclearTimeout(this.timeout);\n\t\tthis.timeout = void 0;\n\t}\n};\nfunction withResolvers() {\n\tlet resolve;\n\tlet reject;\n\treturn {\n\t\tpromise: new Promise((res, rej) => {\n\t\t\tresolve = res;\n\t\t\treject = rej;\n\t\t}),\n\t\tresolve,\n\t\treject\n\t};\n}\n/**\n* Resolves a WebSocket URL and optionally appends connection parameters.\n*\n* If connectionParams are provided, appends 'connectionParams=1' query parameter.\n*/\nasync function prepareUrl(urlOptions) {\n\tconst url = await resultOf(urlOptions.url);\n\tif (!urlOptions.connectionParams) return url;\n\treturn url + `${url.includes(\"?\") ? \"&\" : \"?\"}connectionParams=1`;\n}\nasync function buildConnectionMessage(connectionParams, encoder) {\n\tconst message = {\n\t\tmethod: \"connectionParams\",\n\t\tdata: await resultOf(connectionParams)\n\t};\n\treturn encoder.encode(message);\n}\n// src/links/wsLink/wsClient/requestManager.ts\n/**\n* Manages WebSocket requests, tracking their lifecycle and providing utility methods\n* for handling outgoing and pending requests.\n*\n* - **Outgoing requests**: Requests that are queued and waiting to be sent.\n* - **Pending requests**: Requests that have been sent and are in flight awaiting a response.\n* For subscriptions, multiple responses may be received until the subscription is closed.\n*/\nvar RequestManager = class {\n\tconstructor() {\n\t\t_defineProperty(this, \"outgoingRequests\", new Array());\n\t\t_defineProperty(this, \"pendingRequests\", {});\n\t\t_defineProperty(this, \"drainingRequests\", {});\n\t}\n\t/**\n\t* Registers a new request by adding it to the outgoing queue and setting up\n\t* callbacks for lifecycle events such as completion or error.\n\t*\n\t* @param message - The outgoing message to be sent.\n\t* @param callbacks - Callback functions to observe the request's state.\n\t* @returns A cleanup function to manually remove the request.\n\t*/\n\tregister(message, callbacks) {\n\t\tconst { promise: end, resolve } = withResolvers();\n\t\tthis.outgoingRequests.push({\n\t\t\tid: String(message.id),\n\t\t\tmessage,\n\t\t\tend,\n\t\t\tws: null,\n\t\t\tsuccessor: null,\n\t\t\toverlapEventIds: null,\n\t\t\tmovedFrom: /* @__PURE__ */ new Set(),\n\t\t\tcallbacks: {\n\t\t\t\tnext: callbacks.next,\n\t\t\t\tcomplete: () => {\n\t\t\t\t\tcallbacks.complete();\n\t\t\t\t\tresolve();\n\t\t\t\t},\n\t\t\t\terror: (e) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcallbacks.error(e);\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\treturn () => {\n\t\t\tthis.delete(message);\n\t\t\tcallbacks.complete();\n\t\t\tresolve();\n\t\t};\n\t}\n\t/**\n\t* Deletes a request from both the outgoing and pending collections, if it exists.\n\t*\n\t* Matches the message itself rather than its id: a retry reuses the id, and\n\t* registers its request before the failed request with that id is deleted.\n\t*/\n\tdelete(message) {\n\t\tvar _this$pendingRequests;\n\t\tthis.outgoingRequests = this.outgoingRequests.filter((request) => request.message !== message);\n\t\tconst id = String(message.id);\n\t\tif (((_this$pendingRequests = this.pendingRequests[id]) === null || _this$pendingRequests === void 0 ? void 0 : _this$pendingRequests.message) === message) delete this.pendingRequests[id];\n\t\tfor (const [drainingId, request] of Object.entries(this.drainingRequests)) if (request.message === message) delete this.drainingRequests[drainingId];\n\t}\n\t/**\n\t* Moves all outgoing requests to the pending state and clears the outgoing queue.\n\t*\n\t* The caller is expected to handle the actual sending of the requests\n\t* (e.g., sending them over the network) after this method is called.\n\t*\n\t* @param ws - The socket the requests are sent on.\n\t* @returns The list of requests that were transitioned to the pending state.\n\t*/\n\tflush(ws = null) {\n\t\tconst requests = this.outgoingRequests;\n\t\tthis.outgoingRequests = [];\n\t\tfor (const request of requests) {\n\t\t\trequest.ws = ws;\n\t\t\trequest.successor = null;\n\t\t\trequest.movedFrom = /* @__PURE__ */ new Set();\n\t\t\tthis.pendingRequests[request.id] = request;\n\t\t}\n\t\treturn requests;\n\t}\n\t/**\n\t* Moves a pending request back to the outgoing queue, to be sent again\n\t* with `id`. Its earlier id then matches only the sockets it's still\n\t* draining; see `getDrainingRequest()`.\n\t*/\n\trequeue(message, id) {\n\t\tconst earlierId = String(message.id);\n\t\tconst request = this.pendingRequests[earlierId];\n\t\tif ((request === null || request === void 0 ? void 0 : request.message) !== message) return;\n\t\tdelete this.pendingRequests[earlierId];\n\t\tif (request.movedFrom.size) this.drainingRequests[earlierId] = request;\n\t\tmessage.id = id;\n\t\tthis.outgoingRequests.push(_objectSpread2(_objectSpread2({}, request), {}, {\n\t\t\tid: String(id),\n\t\t\tws: null,\n\t\t\tsuccessor: null,\n\t\t\toverlapEventIds: null,\n\t\t\tmovedFrom: /* @__PURE__ */ new Set()\n\t\t}));\n\t}\n\t/**\n\t* Retrieves all currently pending requests, which are in flight awaiting responses\n\t* or handling ongoing subscriptions.\n\t*/\n\tgetPendingRequests() {\n\t\treturn Object.values(this.pendingRequests);\n\t}\n\t/**\n\t* Retrieves a specific pending request by its message ID.\n\t*/\n\tgetPendingRequest(messageId) {\n\t\tif (messageId === null) return null;\n\t\treturn this.pendingRequests[String(messageId)];\n\t}\n\t/**\n\t* Retrieves a subscription sent again under a new id by its earlier id,\n\t* while a socket it moved from may still send events under that one.\n\t*/\n\tgetDrainingRequest(messageId) {\n\t\tif (messageId === null) return null;\n\t\treturn this.drainingRequests[String(messageId)];\n\t}\n\t/**\n\t* Retrieves the subscriptions sent again under a new id whose earlier id\n\t* is still in use on a socket they moved from.\n\t*/\n\tgetDrainingRequests() {\n\t\treturn Object.values(this.drainingRequests);\n\t}\n\t/**\n\t* Forgets the earlier ids of subscriptions no longer draining any socket.\n\t*/\n\tdeleteDrained() {\n\t\tfor (const [id, request] of Object.entries(this.drainingRequests)) if (!request.movedFrom.size) delete this.drainingRequests[id];\n\t}\n\t/**\n\t* Retrieves all outgoing requests, which are waiting to be sent.\n\t*/\n\tgetOutgoingRequests() {\n\t\treturn this.outgoingRequests;\n\t}\n\t/**\n\t* Retrieves all requests, both outgoing and pending, with their respective states.\n\t*\n\t* @returns An array of all requests with their state (\"outgoing\" or \"pending\").\n\t*/\n\tgetRequests() {\n\t\treturn [...this.getOutgoingRequests().map((request) => ({\n\t\t\tstate: \"outgoing\",\n\t\t\tmessage: request.message,\n\t\t\tend: request.end,\n\t\t\tcallbacks: request.callbacks\n\t\t})), ...this.getPendingRequests().map((request) => ({\n\t\t\tstate: \"pending\",\n\t\t\tmessage: request.message,\n\t\t\tend: request.end,\n\t\t\tcallbacks: request.callbacks\n\t\t}))];\n\t}\n\t/**\n\t* Checks if there are any pending requests, including ongoing subscriptions.\n\t*/\n\thasPendingRequests() {\n\t\treturn this.getPendingRequests().length > 0;\n\t}\n\t/**\n\t* Checks if there are any pending subscriptions\n\t*/\n\thasPendingSubscriptions() {\n\t\treturn this.getPendingRequests().some((request) => request.message.method === \"subscription\");\n\t}\n\t/**\n\t* Checks if a message is still waiting to be sent.\n\t*/\n\tisOutgoing(message) {\n\t\treturn this.outgoingRequests.some((request) => request.message === message);\n\t}\n\t/**\n\t* Checks if there are any outgoing requests waiting to be sent.\n\t*/\n\thasOutgoingRequests() {\n\t\treturn this.outgoingRequests.length > 0;\n\t}\n};\n// src/links/wsLink/wsClient/wsConnection.ts\n/**\n* Opens a WebSocket connection asynchronously and returns a promise\n* that resolves when the connection is successfully established.\n* The promise rejects if an error occurs during the connection attempt.\n*/\nfunction asyncWsOpen(ws) {\n\tconst { promise, resolve, reject } = withResolvers();\n\tws.addEventListener(\"open\", () => {\n\t\tws.removeEventListener(\"error\", reject);\n\t\tresolve();\n\t});\n\tws.addEventListener(\"error\", reject);\n\treturn promise;\n}\nconst pongCallbacks = /* @__PURE__ */ new WeakMap();\n/**\n* Sends \"PING\" on `ws` and calls `onPong`, if given, once its \"PONG\"\n* arrives. The server answers in order, so by then everything it sent before\n* it read this \"PING\" has arrived too.\n*/\nfunction sendPing(ws, onPong) {\n\tlet callbacks = pongCallbacks.get(ws);\n\tif (!callbacks) {\n\t\tconst queue = [];\n\t\tcallbacks = queue;\n\t\tpongCallbacks.set(ws, queue);\n\t\tws.addEventListener(\"message\", ({ data }) => {\n\t\t\tvar _queue$shift;\n\t\t\tif (data === \"PONG\") (_queue$shift = queue.shift()) === null || _queue$shift === void 0 || _queue$shift();\n\t\t});\n\t}\n\tcallbacks.push(onPong);\n\tws.send(\"PING\");\n}\n/**\n* Sets up a periodic ping-pong mechanism to keep the WebSocket connection alive.\n*\n* - Sends \"PING\" messages at regular intervals defined by `intervalMs`.\n* - If a \"PONG\" response is not received within the `pongTimeoutMs`, the WebSocket is closed.\n* - The ping timer resets upon receiving any message to maintain activity.\n* - Automatically starts the ping process when the WebSocket connection is opened.\n* - Cleans up timers when the WebSocket is closed.\n*\n* @param ws - The WebSocket instance to manage.\n* @param options - Configuration options for ping-pong intervals and timeouts.\n*/\nfunction setupPingInterval(ws, { intervalMs, pongTimeoutMs }) {\n\tlet pingTimeout;\n\tlet pongTimeout;\n\tfunction start() {\n\t\tpingTimeout = setTimeout(() => {\n\t\t\tsendPing(ws, null);\n\t\t\tpongTimeout = setTimeout(() => {\n\t\t\t\tws.close();\n\t\t\t}, pongTimeoutMs);\n\t\t}, intervalMs);\n\t}\n\tfunction reset() {\n\t\tclearTimeout(pingTimeout);\n\t\tstart();\n\t}\n\tfunction pong() {\n\t\tclearTimeout(pongTimeout);\n\t\treset();\n\t}\n\tws.addEventListener(\"open\", start);\n\tws.addEventListener(\"message\", ({ data }) => {\n\t\tclearTimeout(pingTimeout);\n\t\tstart();\n\t\tif (data === \"PONG\") pong();\n\t});\n\tws.addEventListener(\"close\", () => {\n\t\tclearTimeout(pingTimeout);\n\t\tclearTimeout(pongTimeout);\n\t});\n}\n/**\n* Manages a WebSocket connection with support for reconnection, keep-alive mechanisms,\n* and observable state tracking.\n*/\nvar WsConnection = class WsConnection {\n\tconstructor(opts) {\n\t\tvar _opts$WebSocketPonyfi;\n\t\t_defineProperty(this, \"id\", ++WsConnection.connectCount);\n\t\t_defineProperty(this, \"WebSocketPonyfill\", void 0);\n\t\t_defineProperty(this, \"urlOptions\", void 0);\n\t\t_defineProperty(this, \"keepAliveOpts\", void 0);\n\t\t_defineProperty(this, \"encoder\", void 0);\n\t\t_defineProperty(this, \"wsObservable\", behaviorSubject(null));\n\t\t_defineProperty(this, \"openPromise\", null);\n\t\tthis.WebSocketPonyfill = (_opts$WebSocketPonyfi = opts.WebSocketPonyfill) !== null && _opts$WebSocketPonyfi !== void 0 ? _opts$WebSocketPonyfi : WebSocket;\n\t\tif (!this.WebSocketPonyfill) throw new Error(\"No WebSocket implementation found - you probably don't want to use this on the server, but if you do you need to pass a `WebSocket`-ponyfill\");\n\t\tthis.urlOptions = opts.urlOptions;\n\t\tthis.keepAliveOpts = opts.keepAlive;\n\t\tthis.encoder = opts.encoder;\n\t}\n\tget ws() {\n\t\treturn this.wsObservable.get();\n\t}\n\tset ws(ws) {\n\t\tthis.wsObservable.next(ws);\n\t}\n\t/**\n\t* Checks if the WebSocket connection is open and ready to communicate.\n\t*/\n\tisOpen() {\n\t\treturn !!this.ws && this.ws.readyState === this.WebSocketPonyfill.OPEN && !this.openPromise;\n\t}\n\t/**\n\t* Checks if the WebSocket connection is closed or in the process of closing.\n\t*/\n\tisClosed() {\n\t\treturn !!this.ws && (this.ws.readyState === this.WebSocketPonyfill.CLOSING || this.ws.readyState === this.WebSocketPonyfill.CLOSED);\n\t}\n\tasync open() {\n\t\tif (this.openPromise) return this.openPromise;\n\t\tthis.id = ++WsConnection.connectCount;\n\t\tconst wsPromise = prepareUrl(this.urlOptions).then((url) => new this.WebSocketPonyfill(url));\n\t\tthis.openPromise = wsPromise.then(async (ws) => {\n\t\t\tthis.ws = ws;\n\t\t\tws.binaryType = \"arraybuffer\";\n\t\t\tws.addEventListener(\"message\", function({ data }) {\n\t\t\t\tif (data === \"PING\") this.send(\"PONG\");\n\t\t\t});\n\t\t\tif (this.keepAliveOpts.enabled) setupPingInterval(ws, this.keepAliveOpts);\n\t\t\tws.addEventListener(\"close\", () => {\n\t\t\t\tif (this.ws === ws) this.ws = null;\n\t\t\t});\n\t\t\tawait asyncWsOpen(ws);\n\t\t\tif (this.urlOptions.connectionParams) ws.send(await buildConnectionMessage(this.urlOptions.connectionParams, this.encoder));\n\t\t});\n\t\ttry {\n\t\t\tawait this.openPromise;\n\t\t} finally {\n\t\t\tthis.openPromise = null;\n\t\t}\n\t}\n\t/**\n\t* Closes the WebSocket connection gracefully.\n\t* Waits for any ongoing open operation to complete before closing.\n\t*/\n\tasync close() {\n\t\ttry {\n\t\t\tawait this.openPromise;\n\t\t} finally {\n\t\t\tvar _this$ws;\n\t\t\t(_this$ws = this.ws) === null || _this$ws === void 0 || _this$ws.close();\n\t\t}\n\t}\n};\n_defineProperty(WsConnection, \"connectCount\", 0);\n/**\n* Provides a backward-compatible representation of the connection state.\n*/\nfunction backwardCompatibility(connection) {\n\tif (connection.isOpen()) return {\n\t\tid: connection.id,\n\t\tstate: \"open\",\n\t\tws: connection.ws\n\t};\n\tif (connection.isClosed()) return {\n\t\tid: connection.id,\n\t\tstate: \"closed\",\n\t\tws: connection.ws\n\t};\n\tif (!connection.ws) return null;\n\treturn {\n\t\tid: connection.id,\n\t\tstate: \"connecting\",\n\t\tws: connection.ws\n\t};\n}\n// src/links/wsLink/wsClient/wsClient.ts\n/**\n* A WebSocket client for managing TRPC operations, supporting lazy initialization,\n* reconnection, keep-alive, and request management.\n*/\nvar WsClient = class {\n\tconstructor(opts) {\n\t\tvar _opts$experimental_en, _opts$retryDelayMs;\n\t\t_defineProperty(this, \"connectionState\", void 0);\n\t\t_defineProperty(this, \"allowReconnect\", false);\n\t\t_defineProperty(this, \"requestManager\", new RequestManager());\n\t\t_defineProperty(this, \"lastRequestId\", 0);\n\t\t_defineProperty(this, \"connectionOptions\", void 0);\n\t\t_defineProperty(this, \"activeConnection\", void 0);\n\t\t_defineProperty(this, \"reconnectRetryDelay\", void 0);\n\t\t_defineProperty(this, \"inactivityTimeout\", void 0);\n\t\t_defineProperty(this, \"callbacks\", void 0);\n\t\t_defineProperty(this, \"lazyMode\", void 0);\n\t\t_defineProperty(this, \"encoder\", void 0);\n\t\t_defineProperty(this, \"reconnecting\", null);\n\t\t_defineProperty(this, \"nextConnection\", null);\n\t\t_defineProperty(this, \"retiredConnection\", null);\n\t\t_defineProperty(this, \"replacementError\", null);\n\t\t_defineProperty(this, \"connectionAttemptIndex\", 0);\n\t\t_defineProperty(this, \"connectionRejected\", false);\n\t\t_defineProperty(this, \"started\", /* @__PURE__ */ new WeakSet());\n\t\tthis.encoder = (_opts$experimental_en = opts.experimental_encoder) !== null && _opts$experimental_en !== void 0 ? _opts$experimental_en : jsonEncoder;\n\t\tthis.callbacks = {\n\t\t\tonOpen: opts.onOpen,\n\t\t\tonClose: opts.onClose,\n\t\t\tonError: opts.onError\n\t\t};\n\t\tconst lazyOptions = _objectSpread2(_objectSpread2({}, lazyDefaults), opts.lazy);\n\t\tthis.inactivityTimeout = new ResettableTimeout(() => {\n\t\t\tif (this.requestManager.hasOutgoingRequests() || this.requestManager.hasPendingRequests()) {\n\t\t\t\tthis.inactivityTimeout.reset();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.close().catch(() => null);\n\t\t}, lazyOptions.closeMs);\n\t\tthis.connectionOptions = {\n\t\t\tWebSocketPonyfill: opts.WebSocket,\n\t\t\turlOptions: opts,\n\t\t\tkeepAlive: _objectSpread2(_objectSpread2({}, keepAliveDefaults), opts.keepAlive),\n\t\t\tencoder: this.encoder\n\t\t};\n\t\tthis.activeConnection = this.createConnection();\n\t\tthis.reconnectRetryDelay = (_opts$retryDelayMs = opts.retryDelayMs) !== null && _opts$retryDelayMs !== void 0 ? _opts$retryDelayMs : exponentialBackoff;\n\t\tthis.lazyMode = lazyOptions.enabled;\n\t\tthis.connectionState = behaviorSubject({\n\t\t\ttype: \"state\",\n\t\t\tstate: lazyOptions.enabled ? \"idle\" : \"connecting\",\n\t\t\terror: null\n\t\t});\n\t\tif (!this.lazyMode) this.open().catch(() => null);\n\t}\n\tcreateConnection() {\n\t\tconst connection = new WsConnection(this.connectionOptions);\n\t\tconnection.wsObservable.subscribe({ next: (ws) => {\n\t\t\tif (!ws) return;\n\t\t\tthis.setupWebSocketListeners(ws);\n\t\t} });\n\t\treturn connection;\n\t}\n\t/**\n\t* Opens the WebSocket connection. Handles reconnection attempts and updates\n\t* the connection state accordingly.\n\t*/\n\tasync open() {\n\t\tthis.allowReconnect = true;\n\t\tif (this.reconnecting) return this.reconnecting;\n\t\tthis.connectionAttemptIndex = 0;\n\t\tif (this.connectionState.get().state === \"idle\") callUserCallback(() => this.connectionState.next({\n\t\t\ttype: \"state\",\n\t\t\tstate: \"connecting\",\n\t\t\terror: null\n\t\t}));\n\t\ttry {\n\t\t\tawait this.activeConnection.open();\n\t\t} catch (error) {\n\t\t\tthis.reconnect(new TRPCWebSocketClosedError({\n\t\t\t\tmessage: \"Initialization error\",\n\t\t\t\tcause: error\n\t\t\t}));\n\t\t\tawait this.activeConnection.close().catch(() => null);\n\t\t\treturn this.reconnecting;\n\t\t}\n\t}\n\t/**\n\t* Closes the WebSocket connection and stops managing requests.\n\t* Ensures all outgoing and pending requests are properly finalized.\n\t*/\n\tasync close() {\n\t\tvar _this$nextConnection;\n\t\tthis.allowReconnect = false;\n\t\tthis.replacementError = null;\n\t\tthis.retiredConnection = null;\n\t\tthis.inactivityTimeout.stop();\n\t\tconst requestsToAwait = [];\n\t\tfor (const request of this.requestManager.getRequests()) if (request.message.method === \"subscription\") callUserCallback(() => request.callbacks.complete());\n\t\telse if (request.state === \"outgoing\") callUserCallback(() => request.callbacks.error(TRPCClientError.from(new TRPCWebSocketClosedError({ message: \"Closed before connection was established\" }))));\n\t\telse requestsToAwait.push(request.end);\n\t\tawait Promise.all(requestsToAwait).catch(() => null);\n\t\t(_this$nextConnection = this.nextConnection) === null || _this$nextConnection === void 0 || (_this$nextConnection = _this$nextConnection.ws) === null || _this$nextConnection === void 0 || _this$nextConnection.close();\n\t\tawait this.activeConnection.close().catch(() => null);\n\t\tcallUserCallback(() => this.connectionState.next({\n\t\t\ttype: \"state\",\n\t\t\tstate: \"idle\",\n\t\t\terror: null\n\t\t}));\n\t}\n\t/**\n\t* Method to request the server.\n\t* Handles data transformation, batching of requests, and subscription lifecycle.\n\t*\n\t* @param op - The operation details including type, path, input and signal. Each subscription to the returned observable is sent with a new id, not `op.id`.\n\t* @param transformer - Data transformer for serializing requests and deserializing responses\n\t* @param lastEventId - Optional ID of the last received event for subscriptions\n\t*\n\t* @returns An observable that emits operation results and handles cleanup\n\t*/\n\trequest({ op: { type, path, input, signal }, transformer, lastEventId }) {\n\t\treturn observable((observer) => {\n\t\t\tconst message = {\n\t\t\t\tid: ++this.lastRequestId,\n\t\t\t\tmethod: type,\n\t\t\t\tparams: {\n\t\t\t\t\tinput: transformer.input.serialize(input),\n\t\t\t\t\tpath,\n\t\t\t\t\tlastEventId\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst abort = this.batchSend(message, _objectSpread2(_objectSpread2({}, observer), {}, { next(event) {\n\t\t\t\tconst transformed = transformResult(event, transformer.output);\n\t\t\t\tif (!transformed.ok) {\n\t\t\t\t\tobserver.error(TRPCClientError.from(transformed.error));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tobserver.next({ result: transformed.result });\n\t\t\t} }));\n\t\t\tconst onAbort = () => observer.complete();\n\t\t\tif (signal === null || signal === void 0 ? void 0 : signal.aborted) onAbort();\n\t\t\telse signal === null || signal === void 0 || signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\treturn () => {\n\t\t\t\tconst { id } = message;\n\t\t\t\tconst pending = this.requestManager.getPendingRequest(id);\n\t\t\t\tconst draining = this.requestManager.getDrainingRequests().filter((request) => request.message === message);\n\t\t\t\tabort();\n\t\t\t\tif (type === \"subscription\" && pending) {\n\t\t\t\t\tthis.stopSubscription(id, pending.ws);\n\t\t\t\t\tthis.stopSubscription(id, pending.successor);\n\t\t\t\t}\n\t\t\t\tthis.closeIfDrained(pending === null || pending === void 0 ? void 0 : pending.ws);\n\t\t\t\tfor (const request of [pending, ...draining]) {\n\t\t\t\t\tvar _request$movedFrom;\n\t\t\t\t\tfor (const earlier of (_request$movedFrom = request === null || request === void 0 ? void 0 : request.movedFrom) !== null && _request$movedFrom !== void 0 ? _request$movedFrom : []) this.closeIfDrained(earlier);\n\t\t\t\t}\n\t\t\t\tsignal === null || signal === void 0 || signal.removeEventListener(\"abort\", onAbort);\n\t\t\t};\n\t\t});\n\t}\n\t/**\n\t* The current WebSocket and its state, or `null` when there is no socket.\n\t*/\n\tget connection() {\n\t\tvar _this$nextConnection2;\n\t\treturn backwardCompatibility(this.activeConnection.ws ? this.activeConnection : (_this$nextConnection2 = this.nextConnection) !== null && _this$nextConnection2 !== void 0 ? _this$nextConnection2 : this.activeConnection);\n\t}\n\t/**\n\t* Opens a new connection, retrying until one opens. While the current\n\t* socket is open, it keeps serving every request, new ones included, until\n\t* the new one is fully open, `connectionParams` included.\n\t*\n\t* @param closedError - Why the current socket was lost, or `null` when it's\n\t* still open and serving requests, e.g. on a server-requested reconnect.\n\t*/\n\treconnect(closedError) {\n\t\tif (!this.allowReconnect) return;\n\t\tif (closedError) {\n\t\t\tvar _this$replacementErro;\n\t\t\tconst error = (_this$replacementErro = this.replacementError) !== null && _this$replacementErro !== void 0 ? _this$replacementErro : closedError;\n\t\t\tthis.replacementError = null;\n\t\t\tcallUserCallback(() => this.connectionState.next({\n\t\t\t\ttype: \"state\",\n\t\t\t\tstate: \"connecting\",\n\t\t\t\terror: TRPCClientError.from(error)\n\t\t\t}));\n\t\t}\n\t\tif (this.reconnecting) return;\n\t\tconst tryReconnect = async (attemptIndex) => {\n\t\t\ttry {\n\t\t\t\tawait sleep(this.reconnectRetryDelay(attemptIndex));\n\t\t\t\tif (this.allowReconnect) {\n\t\t\t\t\tconst next = this.createConnection();\n\t\t\t\t\tthis.nextConnection = next;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait next.open();\n\t\t\t\t\t\tif (!next.isOpen()) throw new Error(\"WebSocket closed before it was ready\");\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tawait next.close().catch(() => null);\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tthis.nextConnection = null;\n\t\t\t\t\t}\n\t\t\t\t\tif (this.allowReconnect) {\n\t\t\t\t\t\tconst previous = this.activeConnection;\n\t\t\t\t\t\tthis.activeConnection = next;\n\t\t\t\t\t\tthis.retiredConnection = previous.isOpen() ? previous : null;\n\t\t\t\t\t\tthis.connectionAttemptIndex = attemptIndex;\n\t\t\t\t\t\tthis.replacementError = null;\n\t\t\t\t\t\tthis.handOff(previous.ws);\n\t\t\t\t\t} else await next.close();\n\t\t\t\t}\n\t\t\t\tthis.reconnecting = null;\n\t\t\t} catch (error) {\n\t\t\t\tconst closedError = new TRPCWebSocketClosedError({\n\t\t\t\t\tmessage: \"Initialization error\",\n\t\t\t\t\tcause: error\n\t\t\t\t});\n\t\t\t\tif (this.allowReconnect && this.activeConnection.isOpen()) this.replacementError = closedError;\n\t\t\t\telse if (this.allowReconnect) callUserCallback(() => this.connectionState.next({\n\t\t\t\t\ttype: \"state\",\n\t\t\t\t\tstate: \"connecting\",\n\t\t\t\t\terror: TRPCClientError.from(closedError)\n\t\t\t\t}));\n\t\t\t\tawait tryReconnect(attemptIndex + 1);\n\t\t\t}\n\t\t};\n\t\tthis.reconnecting = tryReconnect(this.connectionRejected ? this.connectionAttemptIndex + 1 : 0);\n\t}\n\t/**\n\t* Moves the pending subscriptions to the active socket, which has just\n\t* opened: each is resubscribed with the id of the last event it delivered.\n\t* A subscription whose old socket is still open keeps delivering from it\n\t* until the new socket confirms it with `started`; see `confirmMove()`.\n\t* Closes the previous socket once nothing is left on it.\n\t*/\n\thandOff(previous) {\n\t\tif (this.connectionState.get().state !== \"pending\" && this.activeConnection.isOpen()) callUserCallback(() => this.connectionState.next({\n\t\t\ttype: \"state\",\n\t\t\tstate: \"pending\",\n\t\t\terror: null\n\t\t}));\n\t\tconst ws = this.activeConnection.ws;\n\t\tconst subscriptions = this.requestManager.getPendingRequests().filter((request) => request.message.method === \"subscription\" && request.ws !== ws);\n\t\tif (subscriptions.length) {\n\t\t\tthis.send(subscriptions.map(({ message }) => message));\n\t\t\tfor (const request of subscriptions) {\n\t\t\t\tthis.stopSubscription(request.message.id, request.successor);\n\t\t\t\tif (request.ws && request.ws.readyState === request.ws.OPEN) {\n\t\t\t\t\trequest.successor = ws;\n\t\t\t\t\trequest.overlapEventIds = /* @__PURE__ */ new Set();\n\t\t\t\t} else {\n\t\t\t\t\tthis.started.delete(request.message);\n\t\t\t\t\trequest.ws = ws;\n\t\t\t\t\trequest.successor = null;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.closeIfDrained(previous);\n\t}\n\t/**\n\t* Completes a subscription's move once its new socket has confirmed it:\n\t* stops it on the old socket, whose later messages for it are dropped\n\t* apart from events without ids, and closes that socket once everything it\n\t* sent before the stop has arrived and nothing else is left on it.\n\t*/\n\tconfirmMove(request) {\n\t\tconst previous = request.ws;\n\t\trequest.ws = request.successor;\n\t\trequest.successor = null;\n\t\tif (previous && this.stopSubscription(request.message.id, previous)) {\n\t\t\trequest.movedFrom.add(previous);\n\t\t\tsendPing(previous, () => this.releaseMovedFrom(request, previous));\n\t\t}\n\t\tthis.closeIfDrained(previous);\n\t}\n\treleaseMovedFrom(request, ws) {\n\t\tif (!request.movedFrom.delete(ws)) return;\n\t\tthis.requestManager.deleteDrained();\n\t\tthis.closeIfDrained(ws);\n\t}\n\thasRequestsOn(ws) {\n\t\treturn [...this.requestManager.getPendingRequests(), ...this.requestManager.getDrainingRequests()].some((request) => request.ws === ws || ws !== null && request.movedFrom.has(ws));\n\t}\n\t/**\n\t* Closes `ws` once it's been replaced and nothing is left on it.\n\t*/\n\tcloseIfDrained(ws) {\n\t\tif (!ws || ws === this.activeConnection.ws) return;\n\t\tif (this.hasRequestsOn(ws)) return;\n\t\tws.close();\n\t}\n\t/**\n\t* Stops a subscription on the socket it was sent on, if that's still open.\n\t*\n\t* @returns Whether the stop was sent.\n\t*/\n\tstopSubscription(id, ws) {\n\t\tif (!ws || ws.readyState !== ws.OPEN) return false;\n\t\tws.send(this.encoder.encode({\n\t\t\tid,\n\t\t\tmethod: \"subscription.stop\"\n\t\t}));\n\t\treturn true;\n\t}\n\t/**\n\t* Fails the pending queries and mutations sent on `ws`, and returns its\n\t* pending subscriptions, which are kept to be sent again.\n\t*/\n\tfailPendingRequests(ws, cause) {\n\t\tconst subscriptions = [];\n\t\tfor (const request of this.requestManager.getPendingRequests()) {\n\t\t\tconst { message, callbacks } = request;\n\t\t\tif (request.ws !== ws) continue;\n\t\t\tif (message.method === \"subscription\") {\n\t\t\t\tsubscriptions.push(request);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcallUserCallback(() => callbacks.error(TRPCClientError.from(cause !== null && cause !== void 0 ? cause : new TRPCWebSocketClosedError({\n\t\t\t\tmessage: \"WebSocket closed\",\n\t\t\t\tcause\n\t\t\t}))));\n\t\t\tthis.requestManager.delete(message);\n\t\t}\n\t\treturn subscriptions;\n\t}\n\tsetupWebSocketListeners(ws) {\n\t\tthis.connectionRejected = false;\n\t\t/**\n\t\t* Fails the queries and mutations sent on `ws`. Its subscriptions are\n\t\t* sent again on the active socket if that's open, or else by\n\t\t* `reconnect()` once the next one opens.\n\t\t*/\n\t\tconst handleCloseOrError = (cause) => {\n\t\t\tvar _this$retiredConnecti;\n\t\t\tif (ws === ((_this$retiredConnecti = this.retiredConnection) === null || _this$retiredConnecti === void 0 ? void 0 : _this$retiredConnecti.ws)) this.retiredConnection = null;\n\t\t\tconst retired = this.retiredConnection;\n\t\t\tlet restored = false;\n\t\t\tif (ws === this.activeConnection.ws && (retired === null || retired === void 0 ? void 0 : retired.isOpen())) {\n\t\t\t\trestored = true;\n\t\t\t\tthis.activeConnection = retired;\n\t\t\t\tthis.retiredConnection = null;\n\t\t\t\tthis.replacementError = new TRPCWebSocketClosedError({\n\t\t\t\t\tmessage: \"WebSocket closed\",\n\t\t\t\t\tcause\n\t\t\t\t});\n\t\t\t}\n\t\t\tfor (const request of this.requestManager.getPendingRequests()) {\n\t\t\t\tif (request.successor === ws) {\n\t\t\t\t\trequest.successor = null;\n\t\t\t\t\trequest.overlapEventIds = null;\n\t\t\t\t}\n\t\t\t\trequest.movedFrom.delete(ws);\n\t\t\t}\n\t\t\tfor (const request of this.requestManager.getDrainingRequests()) request.movedFrom.delete(ws);\n\t\t\tthis.requestManager.deleteDrained();\n\t\t\tconst lost = this.failPendingRequests(ws, cause).filter((request) => {\n\t\t\t\tif (!request.successor) return true;\n\t\t\t\trequest.ws = request.successor;\n\t\t\t\trequest.successor = null;\n\t\t\t\treturn false;\n\t\t\t});\n\t\t\tif (ws === this.activeConnection.ws || this.reconnecting && !this.activeConnection.isOpen()) return;\n\t\t\tfor (const { message, callbacks } of lost) {\n\t\t\t\tthis.started.delete(message);\n\t\t\t\tthis.requestManager.requeue(message, ++this.lastRequestId);\n\t\t\t\tthis.flushOutgoing(message, callbacks);\n\t\t\t}\n\t\t\tif (restored) this.reconnect(null);\n\t\t};\n\t\tws.addEventListener(\"open\", () => {\n\t\t\trun(async () => {\n\t\t\t\tvar _this$callbacks$onOpe, _this$callbacks;\n\t\t\t\tif (this.lazyMode) this.inactivityTimeout.start();\n\t\t\t\t(_this$callbacks$onOpe = (_this$callbacks = this.callbacks).onOpen) === null || _this$callbacks$onOpe === void 0 || _this$callbacks$onOpe.call(_this$callbacks);\n\t\t\t\tif (this.connectionState.get().state === \"pending\" || ws !== this.activeConnection.ws && this.activeConnection.isOpen()) return;\n\t\t\t\tcallUserCallback(() => this.connectionState.next({\n\t\t\t\t\ttype: \"state\",\n\t\t\t\t\tstate: \"pending\",\n\t\t\t\t\terror: null\n\t\t\t\t}));\n\t\t\t}).catch((error) => {\n\t\t\t\tws.close(3e3);\n\t\t\t\thandleCloseOrError(error);\n\t\t\t});\n\t\t});\n\t\tconst onMessage = ({ data }) => {\n\t\t\tvar _this$nextConnection3;\n\t\t\tthis.inactivityTimeout.reset();\n\t\t\tif ([\"PING\", \"PONG\"].includes(data)) return;\n\t\t\tconst incomingMessage = this.encoder.decode(data);\n\t\t\tif (\"method\" in incomingMessage) {\n\t\t\t\tif (ws === this.activeConnection.ws) this.handleIncomingRequest(incomingMessage);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst isRetired = ws !== this.activeConnection.ws && ws !== ((_this$nextConnection3 = this.nextConnection) === null || _this$nextConnection3 === void 0 ? void 0 : _this$nextConnection3.ws);\n\t\t\tif (!isRetired && incomingMessage.id === null && \"error\" in incomingMessage) this.connectionRejected = true;\n\t\t\telse if (!isRetired && \"result\" in incomingMessage) this.connectionRejected = false;\n\t\t\tthis.handleResponseMessage(incomingMessage, ws);\n\t\t};\n\t\tws.addEventListener(\"message\", (event) => {\n\t\t\tcallUserCallback(() => onMessage(event));\n\t\t});\n\t\tws.addEventListener(\"close\", (event) => {\n\t\t\thandleCloseOrError(event);\n\t\t\tcallUserCallback(() => {\n\t\t\t\tvar _this$callbacks$onClo, _this$callbacks2;\n\t\t\t\treturn (_this$callbacks$onClo = (_this$callbacks2 = this.callbacks).onClose) === null || _this$callbacks$onClo === void 0 ? void 0 : _this$callbacks$onClo.call(_this$callbacks2, event);\n\t\t\t});\n\t\t\tif (ws === this.activeConnection.ws && (!this.lazyMode || this.requestManager.hasPendingSubscriptions())) this.reconnect(new TRPCWebSocketClosedError({\n\t\t\t\tmessage: \"WebSocket closed\",\n\t\t\t\tcause: event\n\t\t\t}));\n\t\t});\n\t\tws.addEventListener(\"error\", (event) => {\n\t\t\thandleCloseOrError(event);\n\t\t\tcallUserCallback(() => {\n\t\t\t\tvar _this$callbacks$onErr, _this$callbacks3;\n\t\t\t\treturn (_this$callbacks$onErr = (_this$callbacks3 = this.callbacks).onError) === null || _this$callbacks$onErr === void 0 ? void 0 : _this$callbacks$onErr.call(_this$callbacks3, event);\n\t\t\t});\n\t\t\tif (ws !== this.activeConnection.ws) return;\n\t\t\tthis.reconnect(new TRPCWebSocketClosedError({\n\t\t\t\tmessage: \"WebSocket closed\",\n\t\t\t\tcause: event\n\t\t\t}));\n\t\t});\n\t}\n\thandleResponseMessage(message, ws) {\n\t\tvar _this$requestManager$;\n\t\tconst request = (_this$requestManager$ = this.requestManager.getPendingRequest(message.id)) !== null && _this$requestManager$ !== void 0 ? _this$requestManager$ : this.requestManager.getDrainingRequest(message.id);\n\t\tif (!request) return;\n\t\tconst result = \"result\" in message ? message.result : null;\n\t\tif (request.successor === ws) this.confirmMove(request);\n\t\telse if (request.ws !== ws) {\n\t\t\tif (request.movedFrom.has(ws)) {\n\t\t\t\tif ((result === null || result === void 0 ? void 0 : result.type) === \"stopped\") this.releaseMovedFrom(request, ws);\n\t\t\t\telse if ((result === null || result === void 0 ? void 0 : result.type) === \"data\" && result.id === void 0) callUserCallback(() => request.callbacks.next(message));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif ((result === null || result === void 0 ? void 0 : result.type) === \"started\" && this.started.has(request.message)) return;\n\t\tif ((result === null || result === void 0 ? void 0 : result.type) === \"data\" && result.id !== void 0) {\n\t\t\tvar _request$overlapEvent2;\n\t\t\tconst eventId = String(result.id);\n\t\t\tif (request.successor) {\n\t\t\t\tvar _request$overlapEvent;\n\t\t\t\t(_request$overlapEvent = request.overlapEventIds) === null || _request$overlapEvent === void 0 || _request$overlapEvent.add(eventId);\n\t\t\t} else if ((_request$overlapEvent2 = request.overlapEventIds) === null || _request$overlapEvent2 === void 0 ? void 0 : _request$overlapEvent2.delete(eventId)) return;\n\t\t}\n\t\tcallUserCallback(() => request.callbacks.next(message));\n\t\tlet completed = true;\n\t\tif (\"result\" in message && request.message.method === \"subscription\") {\n\t\t\tif (message.result.type === \"data\") request.message.params.lastEventId = message.result.id;\n\t\t\telse if (message.result.type === \"started\") this.started.add(request.message);\n\t\t\tif (message.result.type !== \"stopped\") completed = false;\n\t\t}\n\t\tif (completed) {\n\t\t\tcallUserCallback(() => request.callbacks.complete());\n\t\t\tthis.requestManager.delete(request.message);\n\t\t}\n\t}\n\thandleIncomingRequest(message) {\n\t\tif (message.method === \"reconnect\") this.reconnect(null);\n\t}\n\t/**\n\t* Sends a message or batch of messages directly to the server.\n\t*/\n\tsend(messageOrMessages) {\n\t\tif (!this.activeConnection.isOpen()) throw new Error(\"Active connection is not open\");\n\t\tconst messages = messageOrMessages instanceof Array ? messageOrMessages : [messageOrMessages];\n\t\tthis.activeConnection.ws.send(this.encoder.encode(messages.length === 1 ? messages[0] : messages));\n\t}\n\t/**\n\t* Groups requests for batch sending.\n\t*\n\t* @returns A function to abort the batched request.\n\t*/\n\tbatchSend(message, callbacks) {\n\t\tthis.inactivityTimeout.reset();\n\t\tthis.flushOutgoing(message, callbacks);\n\t\treturn this.requestManager.register(message, callbacks);\n\t}\n\t/**\n\t* Sends `message` with the other outgoing requests once the connection is\n\t* open, batching those queued in the same tick.\n\t*/\n\tflushOutgoing(message, callbacks) {\n\t\trun(async () => {\n\t\t\tdo {\n\t\t\t\tif (!this.activeConnection.isOpen()) await this.open();\n\t\t\t\tawait sleep(0);\n\t\t\t} while (!this.activeConnection.isOpen() && this.reconnecting);\n\t\t\tif (!this.requestManager.hasOutgoingRequests()) return;\n\t\t\tif (!this.activeConnection.isOpen() && !this.requestManager.isOutgoing(message)) return;\n\t\t\tconst requests = this.requestManager.flush(this.activeConnection.ws);\n\t\t\ttry {\n\t\t\t\tthis.send(requests.map((request) => request.message));\n\t\t\t} catch (err) {\n\t\t\t\tfor (const request of requests) {\n\t\t\t\t\tthis.requestManager.delete(request.message);\n\t\t\t\t\tcallUserCallback(() => request.callbacks.error(TRPCClientError.from(err)));\n\t\t\t\t}\n\t\t\t}\n\t\t}).catch((err) => {\n\t\t\tthis.requestManager.delete(message);\n\t\t\tcallUserCallback(() => callbacks.error(TRPCClientError.from(err)));\n\t\t});\n\t}\n};\n// src/links/wsLink/createWsClient.ts\n/**\n* Opens and manages a WebSocket connection to a tRPC server. Pass it to\n* `wsLink`.\n*\n* @see https://trpc.io/docs/client/links/wsLink#wslink--createwsclient-options\n*/\nfunction createWSClient(opts) {\n\treturn new WsClient(opts);\n}\n// src/links/wsLink/wsLink.ts\n/**\n* A terminating link that sends calls over a WebSocket.\n*\n* @see https://trpc.io/docs/client/links/wsLink\n*/\nfunction wsLink(opts) {\n\tconst { client } = opts;\n\tconst transformer = getTransformer(opts.transformer);\n\treturn () => {\n\t\treturn ({ op }) => {\n\t\t\treturn observable((observer) => {\n\t\t\t\tlet connStateSubscription = null;\n\t\t\t\tif (op.type === \"subscription\") {\n\t\t\t\t\tlet isSubscribing = true;\n\t\t\t\t\tconnStateSubscription = client.connectionState.subscribe({ next(result) {\n\t\t\t\t\t\tconst emit = () => observer.next({\n\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\tcontext: op.context\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (isSubscribing) callUserCallback(emit);\n\t\t\t\t\t\telse emit();\n\t\t\t\t\t} });\n\t\t\t\t\tisSubscribing = false;\n\t\t\t\t}\n\t\t\t\tconst requestSubscription = client.request({\n\t\t\t\t\top,\n\t\t\t\t\ttransformer\n\t\t\t\t}).subscribe(observer);\n\t\t\t\treturn () => {\n\t\t\t\t\trequestSubscription.unsubscribe();\n\t\t\t\t\tconnStateSubscription === null || connStateSubscription === void 0 || connStateSubscription.unsubscribe();\n\t\t\t\t};\n\t\t\t});\n\t\t};\n\t};\n}\nexport { jsonEncoder as i, createWSClient as n, resultOf as r, wsLink as t };\n\n//# sourceMappingURL=wsLink-BiIe_j6D.mjs.map", "import { n as createChain, t as splitLink } from \"./splitLink-PFsRy7Mf.mjs\";\nimport { n as isTRPCClientError, t as TRPCClientError } from \"./TRPCClientError-DE6-fd1n.mjs\";\nimport { n as _defineProperty, t as _objectSpread2 } from \"./objectSpread2-pyA4QVO4.mjs\";\nimport { c as allAbortSignals, d as throwIfAborted, f as getFetch, l as raceAbortSignals, n as getBody, o as resolveHTTPLinkOptions, r as getUrl, s as abortSignalToPromise, t as fetchHTTPResponse } from \"./httpUtils-CtMuyl9j.mjs\";\nimport { n as dataLoader, t as httpBatchLink } from \"./httpBatchLink-BkVNtNND.mjs\";\nimport { i as isOctetType, n as isFormData, r as isNonJsonSerializable, t as httpLink } from \"./httpLink-B4UwXApa.mjs\";\nimport { loggerLink } from \"./links/loggerLink.mjs\";\nimport { i as jsonEncoder, n as createWSClient, r as resultOf, t as wsLink } from \"./wsLink-BiIe_j6D.mjs\";\nimport { getTransformer } from \"./unstable-internals.mjs\";\nimport { behaviorSubject, observable, observableToAsyncIterable, observableToPromise, share } from \"@trpc/server/observable\";\nimport { callProcedure, createFlatProxy, createRecursiveProxy, isAbortError, isAsyncIterable, isObject, iteratorResource, jsonlStreamConsumer, makeResource, resolvePathSeparator, retryableRpcCodes, run, sseStreamConsumer } from \"@trpc/server/unstable-core-do-not-import\";\nimport { getTRPCErrorFromUnknown, getTRPCErrorShape, isTrackedEnvelope } from \"@trpc/server\";\nimport { TRPC_ERROR_CODES_BY_KEY } from \"@trpc/server/rpc\";\n// src/internals/TRPCUntypedClient.ts\nconst observerKeys = [\n\t\"onStarted\",\n\t\"onData\",\n\t\"onError\",\n\t\"onStopped\",\n\t\"onComplete\",\n\t\"onConnectionStateChange\"\n];\n/**\n* A client that calls procedures by path string, without types.\n* `createTRPCClient` wraps one.\n*/\nvar TRPCUntypedClient = class {\n\tconstructor(opts) {\n\t\t_defineProperty(this, \"links\", void 0);\n\t\t_defineProperty(this, \"runtime\", void 0);\n\t\t_defineProperty(this, \"requestId\", void 0);\n\t\tthis.requestId = 0;\n\t\tthis.runtime = {};\n\t\tthis.links = opts.links.map((link) => link(this.runtime));\n\t}\n\t$request(opts) {\n\t\tvar _opts$context;\n\t\treturn createChain({\n\t\t\tlinks: this.links,\n\t\t\top: _objectSpread2(_objectSpread2({}, opts), {}, {\n\t\t\t\tcontext: (_opts$context = opts.context) !== null && _opts$context !== void 0 ? _opts$context : {},\n\t\t\t\tid: ++this.requestId\n\t\t\t})\n\t\t}).pipe(share());\n\t}\n\tasync requestAsPromise(opts) {\n\t\ttry {\n\t\t\tconst req$ = this.$request(opts);\n\t\t\treturn (await observableToPromise(req$)).result.data;\n\t\t} catch (err) {\n\t\t\tthrow TRPCClientError.from(err);\n\t\t}\n\t}\n\t/** Calls a query. */\n\tquery(path, input, opts) {\n\t\treturn this.requestAsPromise({\n\t\t\ttype: \"query\",\n\t\t\tpath,\n\t\t\tinput,\n\t\t\tcontext: opts === null || opts === void 0 ? void 0 : opts.context,\n\t\t\tsignal: opts === null || opts === void 0 ? void 0 : opts.signal\n\t\t});\n\t}\n\t/** Calls a mutation. */\n\tmutation(path, input, opts) {\n\t\treturn this.requestAsPromise({\n\t\t\ttype: \"mutation\",\n\t\t\tpath,\n\t\t\tinput,\n\t\t\tcontext: opts === null || opts === void 0 ? void 0 : opts.context,\n\t\t\tsignal: opts === null || opts === void 0 ? void 0 : opts.signal\n\t\t});\n\t}\n\tsubscription(path, input, opts = {}) {\n\t\tconst hasCallbacks = observerKeys.some((key) => typeof opts[key] === \"function\");\n\t\tconst observable$ = this.$request({\n\t\t\ttype: \"subscription\",\n\t\t\tpath,\n\t\t\tinput,\n\t\t\tcontext: opts.context,\n\t\t\tsignal: opts.signal\n\t\t});\n\t\tif (!hasCallbacks) {\n\t\t\tvar _opts$signal;\n\t\t\tconst data$ = observable((observer) => observable$.subscribe({\n\t\t\t\tnext(envelope) {\n\t\t\t\t\tif (envelope.result.type === \"data\" || envelope.result.type === void 0) observer.next(envelope.result.data);\n\t\t\t\t},\n\t\t\t\terror: (err) => observer.error(err),\n\t\t\t\tcomplete: () => observer.complete()\n\t\t\t}));\n\t\t\tconst iterator = observableToAsyncIterable(data$, (_opts$signal = opts.signal) !== null && _opts$signal !== void 0 ? _opts$signal : new AbortController().signal);\n\t\t\tlet iterated = false;\n\t\t\titerator[Symbol.asyncIterator] = () => {\n\t\t\t\tif (iterated) throw new Error(\"A subscription can only be iterated once. Call subscribe() again for another loop.\");\n\t\t\t\titerated = true;\n\t\t\t\treturn iterator;\n\t\t\t};\n\t\t\treturn iterator;\n\t\t}\n\t\treturn observable$.subscribe({\n\t\t\tnext(envelope) {\n\t\t\t\tswitch (envelope.result.type) {\n\t\t\t\t\tcase \"state\":\n\t\t\t\t\t\tvar _opts$onConnectionSta;\n\t\t\t\t\t\t(_opts$onConnectionSta = opts.onConnectionStateChange) === null || _opts$onConnectionSta === void 0 || _opts$onConnectionSta.call(opts, envelope.result);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"started\":\n\t\t\t\t\t\tvar _opts$onStarted;\n\t\t\t\t\t\t(_opts$onStarted = opts.onStarted) === null || _opts$onStarted === void 0 || _opts$onStarted.call(opts, { context: envelope.context });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"stopped\":\n\t\t\t\t\t\tvar _opts$onStopped;\n\t\t\t\t\t\t(_opts$onStopped = opts.onStopped) === null || _opts$onStopped === void 0 || _opts$onStopped.call(opts);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"data\":\n\t\t\t\t\tcase void 0:\n\t\t\t\t\t\tvar _opts$onData;\n\t\t\t\t\t\t(_opts$onData = opts.onData) === null || _opts$onData === void 0 || _opts$onData.call(opts, envelope.result.data);\n\t\t\t\t}\n\t\t\t},\n\t\t\terror(err) {\n\t\t\t\tvar _opts$onError;\n\t\t\t\t(_opts$onError = opts.onError) === null || _opts$onError === void 0 || _opts$onError.call(opts, err);\n\t\t\t},\n\t\t\tcomplete() {\n\t\t\t\tvar _opts$onComplete;\n\t\t\t\t(_opts$onComplete = opts.onComplete) === null || _opts$onComplete === void 0 || _opts$onComplete.call(opts);\n\t\t\t}\n\t\t});\n\t}\n};\n// src/createTRPCUntypedClient.ts\n/**\n* Creates a client that calls procedures by path string, without types.\n* Meant for libraries built on tRPC; apps should use `createTRPCClient`.\n*/\nfunction createTRPCUntypedClient(opts) {\n\treturn new TRPCUntypedClient(opts);\n}\n// src/createTRPCClient.ts\nconst untypedClientSymbol = Symbol.for(\"trpc_untypedClient\");\nconst clientCallTypeMap = {\n\tquery: \"query\",\n\tmutate: \"mutation\",\n\tsubscribe: \"subscription\"\n};\n/**\n* The procedure type of a client method: `query`, `mutate` or `subscribe`.\n* @internal\n*/\nconst clientCallTypeToProcedureType = (clientCallType) => {\n\treturn clientCallTypeMap[clientCallType];\n};\n/**\n* Wraps an untyped client in the typed proxy `createTRPCClient` returns.\n* @internal\n*/\nfunction createTRPCClientProxy(client) {\n\tconst proxy = createRecursiveProxy(({ path, args }) => {\n\t\tconst pathCopy = [...path];\n\t\tconst procedureType = clientCallTypeToProcedureType(pathCopy.pop());\n\t\tconst fullPath = pathCopy.join(\".\");\n\t\treturn client[procedureType](fullPath, ...args);\n\t});\n\treturn createFlatProxy((key) => {\n\t\tif (key === untypedClientSymbol) return client;\n\t\treturn proxy[key];\n\t});\n}\n/**\n* Creates a typed client for a router. Pass the router's type, and the\n* links that send its calls.\n* @example\n* ```ts\n* const client = createTRPCClient<AppRouter>({\n* links: [httpBatchLink({ url: 'http://localhost:3000/trpc' })],\n* });\n* const post = await client.post.byId.query({ id: '1' });\n* ```\n* @see https://trpc.io/docs/client/vanilla/setup#3-initialize-the-trpc-client\n*/\nfunction createTRPCClient(opts) {\n\treturn createTRPCClientProxy(new TRPCUntypedClient(opts));\n}\n/**\n* The untyped client behind a typed client, which calls procedures by\n* path string.\n* @internal\n*/\nfunction getUntypedClient(client) {\n\treturn client[untypedClientSymbol];\n}\n// src/links/httpBatchStreamLink.ts\n/**\n* A terminating link that batches calls like `httpBatchLink`, but streams each\n* response back as soon as it is ready.\n*\n* @see https://trpc.io/docs/client/links/httpBatchStreamLink\n*/\nfunction httpBatchStreamLink(opts) {\n\tvar _opts$maxURLLength, _opts$maxItems;\n\tconst resolvedOpts = resolveHTTPLinkOptions(opts);\n\tconst maxURLLength = (_opts$maxURLLength = opts.maxURLLength) !== null && _opts$maxURLLength !== void 0 ? _opts$maxURLLength : Infinity;\n\tconst maxItems = (_opts$maxItems = opts.maxItems) !== null && _opts$maxItems !== void 0 ? _opts$maxItems : Infinity;\n\treturn () => {\n\t\tconst batchLoader = (type) => {\n\t\t\treturn {\n\t\t\t\tvalidate(batchOps) {\n\t\t\t\t\tif (maxURLLength === Infinity && maxItems === Infinity) return true;\n\t\t\t\t\tif (batchOps.length > maxItems) return false;\n\t\t\t\t\tconst path = batchOps.map((op) => op.path).join(\",\");\n\t\t\t\t\tconst inputs = batchOps.map((op) => op.input);\n\t\t\t\t\treturn getUrl(_objectSpread2(_objectSpread2({}, resolvedOpts), {}, {\n\t\t\t\t\t\ttype,\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\tinputs,\n\t\t\t\t\t\tsignal: null\n\t\t\t\t\t})).length <= maxURLLength;\n\t\t\t\t},\n\t\t\t\tasync fetch(batchOps) {\n\t\t\t\t\tvar _opts$streamHeader;\n\t\t\t\t\tconst path = batchOps.map((op) => op.path).join(\",\");\n\t\t\t\t\tconst inputs = batchOps.map((op) => op.input);\n\t\t\t\t\tconst batchSignals = allAbortSignals(...batchOps.map((op) => op.signal));\n\t\t\t\t\tconst abortController = new AbortController();\n\t\t\t\t\tconst res = await fetchHTTPResponse(_objectSpread2(_objectSpread2({}, resolvedOpts), {}, {\n\t\t\t\t\t\tsignal: raceAbortSignals(batchSignals, abortController.signal),\n\t\t\t\t\t\ttype,\n\t\t\t\t\t\tcontentTypeHeader: \"application/json\",\n\t\t\t\t\t\ttrpcAcceptHeader: \"application/jsonl\",\n\t\t\t\t\t\ttrpcAcceptHeaderKey: (_opts$streamHeader = opts.streamHeader) !== null && _opts$streamHeader !== void 0 ? _opts$streamHeader : \"trpc-accept\",\n\t\t\t\t\t\tgetUrl,\n\t\t\t\t\t\tgetBody,\n\t\t\t\t\t\tinputs,\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\theaders() {\n\t\t\t\t\t\t\tif (!opts.headers) return {};\n\t\t\t\t\t\t\tif (typeof opts.headers === \"function\") return opts.headers({ opList: batchOps });\n\t\t\t\t\t\t\treturn opts.headers;\n\t\t\t\t\t\t}\n\t\t\t\t\t}));\n\t\t\t\t\tif (!res.ok) {\n\t\t\t\t\t\tconst json = await res.json();\n\t\t\t\t\t\tif (\"error\" in json) json.error = resolvedOpts.transformer.output.deserialize(json.error);\n\t\t\t\t\t\treturn batchOps.map(() => Promise.resolve({\n\t\t\t\t\t\t\tjson,\n\t\t\t\t\t\t\tmeta: { response: res }\n\t\t\t\t\t\t}));\n\t\t\t\t\t}\n\t\t\t\t\tconst [head] = await jsonlStreamConsumer({\n\t\t\t\t\t\tfrom: res.body,\n\t\t\t\t\t\tdeserialize: (data) => resolvedOpts.transformer.output.deserialize(data),\n\t\t\t\t\t\tformatError(opts) {\n\t\t\t\t\t\t\tconst error = opts.error;\n\t\t\t\t\t\t\treturn TRPCClientError.from({ error });\n\t\t\t\t\t\t},\n\t\t\t\t\t\tabortController\n\t\t\t\t\t});\n\t\t\t\t\treturn Object.keys(batchOps).map(async (key) => {\n\t\t\t\t\t\tlet json = await Promise.resolve(head[key]);\n\t\t\t\t\t\tif (\"result\" in json) {\n\t\t\t\t\t\t\t/**\n\t\t\t\t\t\t\t* Not very pretty, but we need to unwrap nested data as promises\n\t\t\t\t\t\t\t* Our stream producer will only resolve top-level async values or async values that are directly nested in another async value\n\t\t\t\t\t\t\t*/\n\t\t\t\t\t\t\tconst result = await Promise.resolve(json.result);\n\t\t\t\t\t\t\tjson = { result: { data: await Promise.resolve(result.data) } };\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tjson,\n\t\t\t\t\t\t\tmeta: { response: res }\n\t\t\t\t\t\t};\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t};\n\t\t};\n\t\tconst loaders = {\n\t\t\tquery: dataLoader(batchLoader(\"query\")),\n\t\t\tmutation: dataLoader(batchLoader(\"mutation\"))\n\t\t};\n\t\treturn ({ op }) => {\n\t\t\treturn observable((observer) => {\n\t\t\t\t/* istanbul ignore if -- @preserve */\n\t\t\t\tif (op.type === \"subscription\") throw new Error(\"Subscriptions are unsupported by `httpBatchStreamLink` - use `httpSubscriptionLink` or `wsLink`\");\n\t\t\t\tconst ac = new AbortController();\n\t\t\t\tconst promise = loaders[op.type].load(_objectSpread2(_objectSpread2({}, op), {}, { signal: raceAbortSignals(op.signal, ac.signal) }));\n\t\t\t\tlet isDone = false;\n\t\t\t\tlet _res = void 0;\n\t\t\t\tpromise.then((res) => {\n\t\t\t\t\tisDone = true;\n\t\t\t\t\t_res = res;\n\t\t\t\t\tif (\"error\" in res.json) {\n\t\t\t\t\t\tobserver.error(TRPCClientError.from(res.json, { meta: res.meta }));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t} else if (\"result\" in res.json) {\n\t\t\t\t\t\tobserver.next({\n\t\t\t\t\t\t\tcontext: res.meta,\n\t\t\t\t\t\t\tresult: res.json.result\n\t\t\t\t\t\t});\n\t\t\t\t\t\tobserver.complete();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tobserver.complete();\n\t\t\t\t}).catch((err) => {\n\t\t\t\t\tisDone = true;\n\t\t\t\t\tobserver.error(TRPCClientError.from(err, { meta: _res === null || _res === void 0 ? void 0 : _res.meta }));\n\t\t\t\t});\n\t\t\t\treturn () => {\n\t\t\t\t\tif (!isDone) ac.abort();\n\t\t\t\t};\n\t\t\t});\n\t\t};\n\t};\n}\n/**\n* @deprecated Use {@link httpBatchStreamLink} instead.\n*/\nconst unstable_httpBatchStreamLink = httpBatchStreamLink;\n// src/internals/inputWithTrackedEventId.ts\nfunction inputWithTrackedEventId(input, lastEventId) {\n\tif (!lastEventId) return input;\n\tif (input != null && !isObject(input)) return input;\n\treturn _objectSpread2(_objectSpread2({}, input !== null && input !== void 0 ? input : {}), {}, { lastEventId });\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/asyncIterator.js\nfunction _asyncIterator(r) {\n\tvar n, t, o, e = 2;\n\tfor (\"undefined\" != typeof Symbol && (t = Symbol.asyncIterator, o = Symbol.iterator); e--;) {\n\t\tif (t && null != (n = r[t])) return n.call(r);\n\t\tif (o && null != (n = r[o])) return new AsyncFromSyncIterator(n.call(r));\n\t\tt = \"@@asyncIterator\", o = \"@@iterator\";\n\t}\n\tthrow new TypeError(\"Object is not async iterable\");\n}\nfunction AsyncFromSyncIterator(r) {\n\tfunction AsyncFromSyncIteratorContinuation(r) {\n\t\tif (Object(r) !== r) return Promise.reject(/* @__PURE__ */ new TypeError(r + \" is not an object.\"));\n\t\tvar n = r.done;\n\t\treturn Promise.resolve(r.value).then(function(r) {\n\t\t\treturn {\n\t\t\t\tvalue: r,\n\t\t\t\tdone: n\n\t\t\t};\n\t\t});\n\t}\n\treturn AsyncFromSyncIterator = function AsyncFromSyncIterator(r) {\n\t\tthis.s = r, this.n = r.next;\n\t}, AsyncFromSyncIterator.prototype = {\n\t\ts: null,\n\t\tn: null,\n\t\tnext: function next() {\n\t\t\treturn AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));\n\t\t},\n\t\t\"return\": function _return(r) {\n\t\t\tvar n = this.s[\"return\"];\n\t\t\treturn void 0 === n ? Promise.resolve({\n\t\t\t\tvalue: r,\n\t\t\t\tdone: !0\n\t\t\t}) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));\n\t\t},\n\t\t\"throw\": function _throw(r) {\n\t\t\tvar n = this.s[\"throw\"];\n\t\t\treturn void 0 === n ? Promise.reject(r) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));\n\t\t}\n\t}, new AsyncFromSyncIterator(r);\n}\n// src/links/httpSubscriptionLink.ts\nasync function urlWithConnectionParams(opts) {\n\tlet url = await resultOf(opts.url);\n\tif (opts.connectionParams) {\n\t\tconst params = await resultOf(opts.connectionParams);\n\t\tconst prefix = url.includes(\"?\") ? \"&\" : \"?\";\n\t\turl += prefix + \"connectionParams=\" + encodeURIComponent(JSON.stringify(params));\n\t}\n\treturn url;\n}\n/**\n* A terminating link that runs subscriptions over Server-Sent Events.\n*\n* @see https://trpc.io/docs/client/links/httpSubscriptionLink\n*/\nfunction httpSubscriptionLink(opts) {\n\tconst transformer = getTransformer(opts.transformer);\n\tconst pathSeparator = resolvePathSeparator(opts.pathSeparator);\n\treturn () => {\n\t\treturn ({ op }) => {\n\t\t\treturn observable((observer) => {\n\t\t\t\tvar _opts$EventSource;\n\t\t\t\tconst { type, path, input } = op;\n\t\t\t\t/* istanbul ignore if -- @preserve */\n\t\t\t\tif (type !== \"subscription\") throw new Error(\"httpSubscriptionLink only supports subscriptions\");\n\t\t\t\tlet lastEventId = void 0;\n\t\t\t\tconst ac = new AbortController();\n\t\t\t\tconst signal = raceAbortSignals(op.signal, ac.signal);\n\t\t\t\tconst eventSourceStream = sseStreamConsumer({\n\t\t\t\t\turl: async () => getUrl({\n\t\t\t\t\t\ttransformer,\n\t\t\t\t\t\turl: await urlWithConnectionParams(opts),\n\t\t\t\t\t\tinput: inputWithTrackedEventId(input, lastEventId),\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\tpathSeparator,\n\t\t\t\t\t\ttype,\n\t\t\t\t\t\tsignal: null\n\t\t\t\t\t}),\n\t\t\t\t\tinit: () => resultOf(opts.eventSourceOptions, { op }),\n\t\t\t\t\tsignal,\n\t\t\t\t\tdeserialize: (data) => transformer.output.deserialize(data),\n\t\t\t\t\tEventSource: (_opts$EventSource = opts.EventSource) !== null && _opts$EventSource !== void 0 ? _opts$EventSource : globalThis.EventSource\n\t\t\t\t});\n\t\t\t\tconst connectionState = behaviorSubject({\n\t\t\t\t\ttype: \"state\",\n\t\t\t\t\tstate: \"connecting\",\n\t\t\t\t\terror: null\n\t\t\t\t});\n\t\t\t\tconst connectionSub = connectionState.subscribe({ next(state) {\n\t\t\t\t\tobserver.next({ result: state });\n\t\t\t\t} });\n\t\t\t\trun(async () => {\n\t\t\t\t\tvar _iteratorAbruptCompletion = false;\n\t\t\t\t\tvar _didIteratorError = false;\n\t\t\t\t\tvar _iteratorError;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tfor (var _iterator = _asyncIterator(eventSourceStream), _step; _iteratorAbruptCompletion = !(_step = await _iterator.next()).done; _iteratorAbruptCompletion = false) {\n\t\t\t\t\t\t\tconst chunk = _step.value;\n\t\t\t\t\t\t\tswitch (chunk.type) {\n\t\t\t\t\t\t\t\tcase \"ping\": break;\n\t\t\t\t\t\t\t\tcase \"data\":\n\t\t\t\t\t\t\t\t\tconst chunkData = chunk.data;\n\t\t\t\t\t\t\t\t\tlet result;\n\t\t\t\t\t\t\t\t\tif (chunkData.id) {\n\t\t\t\t\t\t\t\t\t\tlastEventId = chunkData.id;\n\t\t\t\t\t\t\t\t\t\tresult = {\n\t\t\t\t\t\t\t\t\t\t\tid: chunkData.id,\n\t\t\t\t\t\t\t\t\t\t\tdata: chunkData\n\t\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\t} else result = { data: chunkData.data };\n\t\t\t\t\t\t\t\t\tobserver.next({\n\t\t\t\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\t\t\t\tcontext: { eventSource: chunk.eventSource }\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"connected\":\n\t\t\t\t\t\t\t\t\tobserver.next({\n\t\t\t\t\t\t\t\t\t\tresult: { type: \"started\" },\n\t\t\t\t\t\t\t\t\t\tcontext: { eventSource: chunk.eventSource }\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tconnectionState.next({\n\t\t\t\t\t\t\t\t\t\ttype: \"state\",\n\t\t\t\t\t\t\t\t\t\tstate: \"pending\",\n\t\t\t\t\t\t\t\t\t\terror: null\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"serialized-error\": {\n\t\t\t\t\t\t\t\t\tconst error = TRPCClientError.from({ error: chunk.error });\n\t\t\t\t\t\t\t\t\tif (retryableRpcCodes.includes(chunk.error.code)) {\n\t\t\t\t\t\t\t\t\t\tconnectionState.next({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"state\",\n\t\t\t\t\t\t\t\t\t\t\tstate: \"connecting\",\n\t\t\t\t\t\t\t\t\t\t\terror\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcase \"connecting\": {\n\t\t\t\t\t\t\t\t\tconst lastState = connectionState.get();\n\t\t\t\t\t\t\t\t\tconst error = chunk.event && TRPCClientError.from(chunk.event);\n\t\t\t\t\t\t\t\t\tif (!error && lastState.state === \"connecting\") break;\n\t\t\t\t\t\t\t\t\tconnectionState.next({\n\t\t\t\t\t\t\t\t\t\ttype: \"state\",\n\t\t\t\t\t\t\t\t\t\tstate: \"connecting\",\n\t\t\t\t\t\t\t\t\t\terror\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcase \"timeout\": connectionState.next({\n\t\t\t\t\t\t\t\t\ttype: \"state\",\n\t\t\t\t\t\t\t\t\tstate: \"connecting\",\n\t\t\t\t\t\t\t\t\terror: new TRPCClientError(`Timeout of ${chunk.ms}ms reached while waiting for a response`)\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t_didIteratorError = true;\n\t\t\t\t\t\t_iteratorError = err;\n\t\t\t\t\t} finally {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (_iteratorAbruptCompletion && _iterator.return != null) await _iterator.return();\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\tif (_didIteratorError) throw _iteratorError;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tobserver.next({ result: { type: \"stopped\" } });\n\t\t\t\t\tconnectionState.next({\n\t\t\t\t\t\ttype: \"state\",\n\t\t\t\t\t\tstate: \"idle\",\n\t\t\t\t\t\terror: null\n\t\t\t\t\t});\n\t\t\t\t\tobserver.complete();\n\t\t\t\t}).catch((error) => {\n\t\t\t\t\tobserver.error(TRPCClientError.from(error));\n\t\t\t\t});\n\t\t\t\treturn () => {\n\t\t\t\t\tobserver.complete();\n\t\t\t\t\tac.abort();\n\t\t\t\t\tconnectionSub.unsubscribe();\n\t\t\t\t};\n\t\t\t});\n\t\t};\n\t};\n}\n/**\n* @deprecated Use {@link httpSubscriptionLink} instead.\n*/\nconst unstable_httpSubscriptionLink = httpSubscriptionLink;\n// src/links/retryLink.ts\n/* istanbul ignore file -- @preserve */\n/**\n* Retries failed operations. Subscriptions resume from the last tracked event\n* id.\n*\n* @see https://trpc.io/docs/client/links/retryLink\n*/\nfunction retryLink(opts) {\n\treturn () => {\n\t\treturn (callOpts) => {\n\t\t\treturn observable((observer) => {\n\t\t\t\tlet next$;\n\t\t\t\tlet currentAttempt = 0;\n\t\t\t\tlet disposed = false;\n\t\t\t\tlet callNextTimeout = void 0;\n\t\t\t\tlet lastEventId = void 0;\n\t\t\t\tattempt(1);\n\t\t\t\tfunction opWithLastEventId() {\n\t\t\t\t\tconst op = callOpts.op;\n\t\t\t\t\tif (!lastEventId) return op;\n\t\t\t\t\treturn _objectSpread2(_objectSpread2({}, op), {}, { input: inputWithTrackedEventId(op.input, lastEventId) });\n\t\t\t\t}\n\t\t\t\tfunction attempt(attempts) {\n\t\t\t\t\tif (disposed) return;\n\t\t\t\t\tcurrentAttempt = attempts;\n\t\t\t\t\tconst op = opWithLastEventId();\n\t\t\t\t\tconst subscription = callOpts.next(op).subscribe({\n\t\t\t\t\t\terror(error) {\n\t\t\t\t\t\t\tvar _opts$retryDelayMs, _opts$retryDelayMs2;\n\t\t\t\t\t\t\tconst shouldRetry = opts.retry({\n\t\t\t\t\t\t\t\top,\n\t\t\t\t\t\t\t\tattempts,\n\t\t\t\t\t\t\t\terror\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (disposed) return;\n\t\t\t\t\t\t\tif (!shouldRetry) {\n\t\t\t\t\t\t\t\tobserver.error(error);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst delayMs = (_opts$retryDelayMs = (_opts$retryDelayMs2 = opts.retryDelayMs) === null || _opts$retryDelayMs2 === void 0 ? void 0 : _opts$retryDelayMs2.call(opts, attempts)) !== null && _opts$retryDelayMs !== void 0 ? _opts$retryDelayMs : 0;\n\t\t\t\t\t\t\tif (disposed) return;\n\t\t\t\t\t\t\tif (delayMs <= 0) {\n\t\t\t\t\t\t\t\tattempt(attempts + 1);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcallNextTimeout = setTimeout(() => attempt(attempts + 1), delayMs);\n\t\t\t\t\t\t},\n\t\t\t\t\t\tnext(envelope) {\n\t\t\t\t\t\t\tif ((!envelope.result.type || envelope.result.type === \"data\") && envelope.result.id) lastEventId = envelope.result.id;\n\t\t\t\t\t\t\tobserver.next(envelope);\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcomplete() {\n\t\t\t\t\t\t\tobserver.complete();\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tif (disposed) subscription.unsubscribe();\n\t\t\t\t\telse if (currentAttempt === attempts) next$ = subscription;\n\t\t\t\t}\n\t\t\t\treturn () => {\n\t\t\t\t\tdisposed = true;\n\t\t\t\t\tnext$.unsubscribe();\n\t\t\t\t\tclearTimeout(callNextTimeout);\n\t\t\t\t};\n\t\t\t});\n\t\t};\n\t};\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/usingCtx.js\nfunction _usingCtx() {\n\tvar r = \"function\" == typeof SuppressedError ? SuppressedError : function(r, e) {\n\t\tvar n = Error();\n\t\treturn n.name = \"SuppressedError\", n.error = r, n.suppressed = e, n;\n\t}, e = {}, n = [];\n\tfunction using(r, e) {\n\t\tif (null != e) {\n\t\t\tif (Object(e) !== e) throw new TypeError(\"using declarations can only be used with objects, functions, null, or undefined.\");\n\t\t\tif (r) var o = e[Symbol.asyncDispose || Symbol[\"for\"](\"Symbol.asyncDispose\")];\n\t\t\tif (void 0 === o && (o = e[Symbol.dispose || Symbol[\"for\"](\"Symbol.dispose\")], r)) var t = o;\n\t\t\tif (\"function\" != typeof o) throw new TypeError(\"Object is not disposable.\");\n\t\t\tt && (o = function o() {\n\t\t\t\ttry {\n\t\t\t\t\tt.call(e);\n\t\t\t\t} catch (r) {\n\t\t\t\t\treturn Promise.reject(r);\n\t\t\t\t}\n\t\t\t}), n.push({\n\t\t\t\tv: e,\n\t\t\t\td: o,\n\t\t\t\ta: r\n\t\t\t});\n\t\t} else r && n.push({\n\t\t\td: e,\n\t\t\ta: r\n\t\t});\n\t\treturn e;\n\t}\n\treturn {\n\t\te,\n\t\tu: using.bind(null, !1),\n\t\ta: using.bind(null, !0),\n\t\td: function d() {\n\t\t\tvar o, t = this.e, s = 0;\n\t\t\tfunction next() {\n\t\t\t\tfor (; o = n.pop();) try {\n\t\t\t\t\tif (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next);\n\t\t\t\t\tif (o.d) {\n\t\t\t\t\t\tvar r = o.d.call(o.v);\n\t\t\t\t\t\tif (o.a) return s |= 2, Promise.resolve(r).then(next, err);\n\t\t\t\t\t} else s |= 1;\n\t\t\t\t} catch (r) {\n\t\t\t\t\treturn err(r);\n\t\t\t\t}\n\t\t\t\tif (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve();\n\t\t\t\tif (t !== e) throw t;\n\t\t\t}\n\t\t\tfunction err(n) {\n\t\t\t\treturn t = t !== e ? new r(n, t) : n, next();\n\t\t\t}\n\t\t\treturn next();\n\t\t}\n\t};\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/OverloadYield.js\nfunction _OverloadYield(e, d) {\n\tthis.v = e, this.k = d;\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/awaitAsyncGenerator.js\nfunction _awaitAsyncGenerator(e) {\n\treturn new _OverloadYield(e, 0);\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/wrapAsyncGenerator.js\nfunction _wrapAsyncGenerator(e) {\n\treturn function() {\n\t\treturn new AsyncGenerator(e.apply(this, arguments));\n\t};\n}\nfunction AsyncGenerator(e) {\n\tvar t, n;\n\tfunction resume(t, n) {\n\t\ttry {\n\t\t\tvar r = e[t](n), o = r.value, u = o instanceof _OverloadYield;\n\t\t\tPromise.resolve(u ? o.v : o).then(function(n) {\n\t\t\t\tif (u) {\n\t\t\t\t\tvar i = \"return\" === t && o.k ? t : \"next\";\n\t\t\t\t\tif (!o.k || n.done) return resume(i, n);\n\t\t\t\t\tn = e[i](n).value;\n\t\t\t\t}\n\t\t\t\tsettle(!!r.done, n);\n\t\t\t}, function(e) {\n\t\t\t\tresume(\"throw\", e);\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tsettle(2, e);\n\t\t}\n\t}\n\tfunction settle(e, r) {\n\t\t2 === e ? t.reject(r) : t.resolve({\n\t\t\tvalue: r,\n\t\t\tdone: e\n\t\t}), (t = t.next) ? resume(t.key, t.arg) : n = null;\n\t}\n\tthis._invoke = function(e, r) {\n\t\treturn new Promise(function(o, u) {\n\t\t\tvar i = {\n\t\t\t\tkey: e,\n\t\t\t\targ: r,\n\t\t\t\tresolve: o,\n\t\t\t\treject: u,\n\t\t\t\tnext: null\n\t\t\t};\n\t\t\tn ? n = n.next = i : (t = n = i, resume(e, r));\n\t\t});\n\t}, \"function\" != typeof e[\"return\"] && (this[\"return\"] = void 0);\n}\nAsyncGenerator.prototype[\"function\" == typeof Symbol && Symbol.asyncIterator || \"@@asyncIterator\"] = function() {\n\treturn this;\n}, AsyncGenerator.prototype.next = function(e) {\n\treturn this._invoke(\"next\", e);\n}, AsyncGenerator.prototype[\"throw\"] = function(e) {\n\treturn this._invoke(\"throw\", e);\n}, AsyncGenerator.prototype[\"return\"] = function(e) {\n\treturn this._invoke(\"return\", e);\n};\n// src/links/localLink.ts\n/**\n* A terminating link that calls procedures on a router in the same process,\n* without HTTP.\n*\n* @see https://trpc.io/docs/client/links/localLink\n*/\nfunction localLink(opts) {\n\tconst transformer = getTransformer(opts.transformer);\n\tconst transformChunk = (chunk) => {\n\t\tif (opts.transformer) return chunk;\n\t\tif (chunk === void 0) return chunk;\n\t\tconst serialized = JSON.stringify(transformer.input.serialize(chunk));\n\t\treturn JSON.parse(transformer.output.deserialize(serialized));\n\t};\n\treturn () => ({ op }) => observable((observer) => {\n\t\tlet ctx = void 0;\n\t\tconst ac = new AbortController();\n\t\tconst signal = raceAbortSignals(op.signal, ac.signal);\n\t\tconst signalPromise = abortSignalToPromise(signal);\n\t\tsignalPromise.catch(() => {});\n\t\tlet input = op.input;\n\t\tasync function runProcedure(newInput) {\n\t\t\tinput = newInput;\n\t\t\tthrowIfAborted(signal);\n\t\t\tctx = await opts.createContext({ info: { signal } });\n\t\t\tthrowIfAborted(signal);\n\t\t\treturn callProcedure({\n\t\t\t\trouter: opts.router,\n\t\t\t\tpath: op.path,\n\t\t\t\tgetRawInput: async () => newInput,\n\t\t\t\tctx,\n\t\t\t\ttype: op.type,\n\t\t\t\tsignal,\n\t\t\t\tbatchIndex: 0\n\t\t\t});\n\t\t}\n\t\tfunction onErrorCallback(cause) {\n\t\t\tvar _opts$onError;\n\t\t\tif (isAbortError(cause)) return;\n\t\t\t(_opts$onError = opts.onError) === null || _opts$onError === void 0 || _opts$onError.call(opts, {\n\t\t\t\terror: getTRPCErrorFromUnknown(cause),\n\t\t\t\ttype: op.type,\n\t\t\t\tpath: op.path,\n\t\t\t\tinput,\n\t\t\t\tctx\n\t\t\t});\n\t\t}\n\t\tfunction coerceToTRPCClientError(cause) {\n\t\t\tif (isTRPCClientError(cause)) return cause;\n\t\t\tconst error = getTRPCErrorFromUnknown(cause);\n\t\t\tconst shape = getTRPCErrorShape({\n\t\t\t\tconfig: opts.router._def._config,\n\t\t\t\tctx,\n\t\t\t\terror,\n\t\t\t\tinput,\n\t\t\t\tpath: op.path,\n\t\t\t\ttype: op.type\n\t\t\t});\n\t\t\treturn TRPCClientError.from({ error: transformChunk(shape) }, { cause: cause instanceof Error ? cause : void 0 });\n\t\t}\n\t\trun(async () => {\n\t\t\tswitch (op.type) {\n\t\t\t\tcase \"query\":\n\t\t\t\tcase \"mutation\": {\n\t\t\t\t\tconst result = await Promise.race([runProcedure(op.input), signalPromise]);\n\t\t\t\t\tif (!isAsyncIterable(result)) {\n\t\t\t\t\t\tobserver.next({ result: { data: transformChunk(result) } });\n\t\t\t\t\t\tobserver.complete();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tobserver.next({ result: { data: _wrapAsyncGenerator(function* () {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tvar _usingCtx$1 = _usingCtx();\n\t\t\t\t\t\t\tconst iterator = _usingCtx$1.a(iteratorResource(result));\n\t\t\t\t\t\t\t_usingCtx$1.u(makeResource({}, () => {\n\t\t\t\t\t\t\t\tobserver.complete();\n\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\twhile (true) {\n\t\t\t\t\t\t\t\t\tconst res = yield _awaitAsyncGenerator(Promise.race([iterator.next(), signalPromise]));\n\t\t\t\t\t\t\t\t\tif (res.done) return transformChunk(res.value);\n\t\t\t\t\t\t\t\t\tyield transformChunk(res.value);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} catch (cause) {\n\t\t\t\t\t\t\t\tonErrorCallback(cause);\n\t\t\t\t\t\t\t\tthrow coerceToTRPCClientError(cause);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (_) {\n\t\t\t\t\t\t\t_usingCtx$1.e = _;\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\tyield _awaitAsyncGenerator(_usingCtx$1.d());\n\t\t\t\t\t\t}\n\t\t\t\t\t})() } });\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"subscription\": try {\n\t\t\t\t\tvar _usingCtx3 = _usingCtx();\n\t\t\t\t\tconst connectionState = behaviorSubject({\n\t\t\t\t\t\ttype: \"state\",\n\t\t\t\t\t\tstate: \"connecting\",\n\t\t\t\t\t\terror: null\n\t\t\t\t\t});\n\t\t\t\t\tconst connectionSub = connectionState.subscribe({ next(state) {\n\t\t\t\t\t\tobserver.next({ result: state });\n\t\t\t\t\t} });\n\t\t\t\t\tlet lastEventId = void 0;\n\t\t\t\t\t_usingCtx3.u(makeResource({}, async () => {\n\t\t\t\t\t\tconnectionState.next({\n\t\t\t\t\t\t\ttype: \"state\",\n\t\t\t\t\t\t\tstate: \"idle\",\n\t\t\t\t\t\t\terror: null\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconnectionSub.unsubscribe();\n\t\t\t\t\t}));\n\t\t\t\t\tawait run(async () => {\n\t\t\t\t\t\twhile (true) try {\n\t\t\t\t\t\t\tvar _usingCtx4 = _usingCtx();\n\t\t\t\t\t\t\tconst result = await runProcedure(inputWithTrackedEventId(op.input, lastEventId));\n\t\t\t\t\t\t\tif (!isAsyncIterable(result)) throw new Error(\"Expected an async iterable\");\n\t\t\t\t\t\t\tconst iterator = _usingCtx4.a(iteratorResource(result));\n\t\t\t\t\t\t\tobserver.next({ result: { type: \"started\" } });\n\t\t\t\t\t\t\tconnectionState.next({\n\t\t\t\t\t\t\t\ttype: \"state\",\n\t\t\t\t\t\t\t\tstate: \"pending\",\n\t\t\t\t\t\t\t\terror: null\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\twhile (true) {\n\t\t\t\t\t\t\t\tlet res;\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tres = await Promise.race([iterator.next(), signalPromise]);\n\t\t\t\t\t\t\t\t} catch (cause) {\n\t\t\t\t\t\t\t\t\tif (isAbortError(cause)) return;\n\t\t\t\t\t\t\t\t\tconst error = getTRPCErrorFromUnknown(cause);\n\t\t\t\t\t\t\t\t\tif (!retryableRpcCodes.includes(TRPC_ERROR_CODES_BY_KEY[error.code])) throw coerceToTRPCClientError(error);\n\t\t\t\t\t\t\t\t\tonErrorCallback(error);\n\t\t\t\t\t\t\t\t\tconnectionState.next({\n\t\t\t\t\t\t\t\t\t\ttype: \"state\",\n\t\t\t\t\t\t\t\t\t\tstate: \"connecting\",\n\t\t\t\t\t\t\t\t\t\terror: coerceToTRPCClientError(error)\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (res.done) return;\n\t\t\t\t\t\t\t\tlet chunk;\n\t\t\t\t\t\t\t\tif (isTrackedEnvelope(res.value)) {\n\t\t\t\t\t\t\t\t\tlastEventId = res.value[0];\n\t\t\t\t\t\t\t\t\tchunk = {\n\t\t\t\t\t\t\t\t\t\tid: res.value[0],\n\t\t\t\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\t\t\t\tid: res.value[0],\n\t\t\t\t\t\t\t\t\t\t\tdata: res.value[1]\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t} else chunk = { data: res.value };\n\t\t\t\t\t\t\t\tobserver.next({ result: _objectSpread2(_objectSpread2({}, chunk), {}, { data: transformChunk(chunk.data) }) });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (_) {\n\t\t\t\t\t\t\t_usingCtx4.e = _;\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\tawait _usingCtx4.d();\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tobserver.complete();\n\t\t\t\t\tbreak;\n\t\t\t\t} catch (_) {\n\t\t\t\t\t_usingCtx3.e = _;\n\t\t\t\t} finally {\n\t\t\t\t\t_usingCtx3.d();\n\t\t\t\t}\n\t\t\t}\n\t\t}).catch((cause) => {\n\t\t\tonErrorCallback(cause);\n\t\t\tobserver.error(coerceToTRPCClientError(cause));\n\t\t});\n\t\treturn () => {\n\t\t\tac.abort();\n\t\t};\n\t});\n}\n/**\n* @deprecated Use {@link localLink} instead.\n* @function\n*/\nconst unstable_localLink = localLink;\n/**\n* @deprecated Use {@link localLink} instead. This alias will be removed in a\n* future major release.\n*/\nconst experimental_localLink = localLink;\n// src/safe.ts\n/**\n* Awaits a client `.query()` or `.mutate()` call without throwing, and\n* returns a `[data, error]` pair typed with the procedure's error shape.\n*\n* @example\n* ```ts\n* const [post, error] = await safe(client.post.byId.query({ id }));\n* if (error) {\n* console.error(error);\n* }\n*\n* const id = post.id;\n* ```\n* @see https://trpc.io/docs/client/vanilla/error-handling#errors-as-values-with-safe\n*/\nasync function safe(promise) {\n\ttry {\n\t\treturn [await promise, void 0];\n\t} catch (cause) {\n\t\treturn [void 0, cause];\n\t}\n}\nexport { TRPCClientError, TRPCUntypedClient, clientCallTypeToProcedureType, createTRPCClient, createTRPCClient as createTRPCProxyClient, createTRPCClientProxy, createTRPCUntypedClient, createWSClient, experimental_localLink, getFetch, getUntypedClient, httpBatchLink, httpBatchStreamLink, httpLink, httpSubscriptionLink, isFormData, isNonJsonSerializable, isOctetType, isTRPCClientError, jsonEncoder, localLink, loggerLink, retryLink, safe, splitLink, unstable_httpBatchStreamLink, unstable_httpSubscriptionLink, unstable_localLink, wsLink };\n\n//# sourceMappingURL=index.mjs.map", "import type {\n\tAppRouter,\n\tRouterInputs,\n\tRouterOutputs,\n} from \"@go-labs/event-tech-api\";\nimport {\n\tcreateTRPCProxyClient,\n\thttpBatchLink,\n\ttype TRPCClient,\n} from \"@trpc/client\";\nimport SuperJSON from \"superjson\";\nimport {\n\tCliConfigurationError,\n\tDEFAULT_EVENT_TECH_API_BASE_URL,\n\tnormalizeApiBaseUrl,\n} from \"./config.js\";\n\nexport {\n\tCliConfigurationError,\n\tDEFAULT_EVENT_TECH_API_BASE_URL,\n\tnormalizeApiBaseUrl,\n} from \"./config.js\";\n\nexport type EventTechClient = TRPCClient<AppRouter>;\nexport type { RouterInputs, RouterOutputs };\n\ntype FetchImplementation = (\n\tinput: Parameters<typeof fetch>[0],\n\tinit?: Parameters<typeof fetch>[1],\n) => ReturnType<typeof fetch>;\ntype TrpcFetch = NonNullable<Parameters<typeof httpBatchLink>[0][\"fetch\"]>;\n\nexport const createEventTechClient = (\n\tapiBaseUrl: string,\n\treadAccessToken: () => string,\n\tfetchImplementation: FetchImplementation = fetch,\n): EventTechClient =>\n\tcreateTRPCProxyClient<AppRouter>({\n\t\tlinks: [\n\t\t\thttpBatchLink({\n\t\t\t\turl: `${apiBaseUrl}/api/trpc`,\n\t\t\t\ttransformer: SuperJSON,\n\t\t\t\tfetch: fetchImplementation as unknown as TrpcFetch,\n\t\t\t\theaders: () => ({\n\t\t\t\t\tAuthorization: `Bearer ${readAccessToken()}`,\n\t\t\t\t\t\"x-trpc-source\": \"event-tech-cli\",\n\t\t\t\t}),\n\t\t\t}),\n\t\t],\n\t});\n\nexport const createEventTechPublicClient = (\n\tapiBaseUrl: string,\n\tfetchImplementation: FetchImplementation = fetch,\n): EventTechClient =>\n\tcreateTRPCProxyClient<AppRouter>({\n\t\tlinks: [\n\t\t\thttpBatchLink({\n\t\t\t\turl: `${apiBaseUrl}/api/trpc`,\n\t\t\t\ttransformer: SuperJSON,\n\t\t\t\tfetch: fetchImplementation as unknown as TrpcFetch,\n\t\t\t\theaders: () => ({\n\t\t\t\t\t\"x-trpc-source\": \"event-tech-cli\",\n\t\t\t\t}),\n\t\t\t}),\n\t\t],\n\t});\n\nlet activeApiBaseUrl = DEFAULT_EVENT_TECH_API_BASE_URL;\nlet activeAccessToken: string | undefined;\nconst readActiveAccessToken = (): string => {\n\tif (!activeAccessToken) {\n\t\tthrow new CliConfigurationError(\n\t\t\t\"Not authenticated. Run `et auth login` first.\",\n\t\t);\n\t}\n\treturn activeAccessToken;\n};\nlet activeClient = createEventTechClient(\n\tactiveApiBaseUrl,\n\treadActiveAccessToken,\n);\nlet activePublicClient = createEventTechPublicClient(activeApiBaseUrl);\nlet testingClient: EventTechClient | undefined;\n\nexport const configureEventTechApiBaseUrl = (value: string): string => {\n\tactiveApiBaseUrl = normalizeApiBaseUrl(value);\n\tactiveClient = createEventTechClient(activeApiBaseUrl, readActiveAccessToken);\n\tactivePublicClient = createEventTechPublicClient(activeApiBaseUrl);\n\treturn activeApiBaseUrl;\n};\n\nexport const configureEventTechApiFromEnvironment = (): string =>\n\tconfigureEventTechApiBaseUrl(\n\t\tprocess.env.EVENT_TECH_API_URL ?? DEFAULT_EVENT_TECH_API_BASE_URL,\n\t);\n\nexport const getEventTechApiBaseUrl = (): string => activeApiBaseUrl;\n\nexport const configureEventTechAccessToken = (accessToken: string): void => {\n\tactiveAccessToken = accessToken;\n};\n\nexport const api = new Proxy({} as EventTechClient, {\n\tget: (_target, property, receiver) =>\n\t\tReflect.get(\n\t\t\tproperty === \"public\"\n\t\t\t\t? (testingClient ?? activePublicClient)\n\t\t\t\t: (testingClient ?? activeClient),\n\t\t\tproperty,\n\t\t\treceiver,\n\t\t),\n});\n\nexport const setEventTechClientForTesting = (\n\tclient: EventTechClient,\n): (() => void) => {\n\tconst previousClient = testingClient;\n\ttestingClient = client;\n\treturn () => {\n\t\ttestingClient = previousClient;\n\t};\n};\n", "export const DEFAULT_EVENT_TECH_API_BASE_URL = \"https://app.getout.events\";\n\nexport class CliConfigurationError extends Error {\n\treadonly code = \"CONFIGURATION\";\n\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"CliConfigurationError\";\n\t}\n}\n\nexport const normalizeApiBaseUrl = (value: string): string => {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(value);\n\t} catch {\n\t\tthrow new CliConfigurationError(\"Event Tech API URL must be a valid URL.\");\n\t}\n\n\tconst isLocalHttp =\n\t\turl.protocol === \"http:\" &&\n\t\t(url.hostname === \"localhost\" || url.hostname === \"127.0.0.1\");\n\tif (url.protocol !== \"https:\" && !isLocalHttp) {\n\t\tthrow new CliConfigurationError(\n\t\t\t\"Event Tech API URL must use HTTPS, except for localhost development.\",\n\t\t);\n\t}\n\n\turl.pathname = url.pathname.replace(/\\/$/, \"\");\n\treturn url.toString().replace(/\\/$/, \"\");\n};\n", "import { readFile } from \"node:fs/promises\";\nimport { CliUsageError } from \"@go-labs-sg/event-tech/runtime\";\n\nexport type FlagValue = string | true;\n\nconst booleanFlags = new Set([\n\t\"allow-delete\",\n\t\"allow-email\",\n\t\"allow-state-change\",\n\t\"archive-missing\",\n\t\"dry-run\",\n\t\"force\",\n\t\"help\",\n\t\"no-browser\",\n\t\"password-stdin\",\n\t\"public\",\n\t\"version\",\n]);\n\nexport interface ParsedArguments {\n\tpositionals: string[];\n\tflags: Map<string, FlagValue>;\n}\n\n/**\n * Records one `--flag` token and returns the index of the last token it\n * consumed (the next token is consumed when it supplies the flag's value).\n */\nconst recordFlag = (\n\targs: readonly string[],\n\tindex: number,\n\ttoken: string,\n\tflags: Map<string, FlagValue>,\n): number => {\n\tconst [rawName, inlineValue] = token.slice(2).split(\"=\", 2);\n\tif (!rawName) throw new CliUsageError(\"Flag names cannot be empty.\");\n\tif (booleanFlags.has(rawName)) {\n\t\t// Fail closed: `--dry-run=true` or `--allow-state-change=false` must\n\t\t// never be read as a string and fall through to a real write.\n\t\tif (inlineValue !== undefined) {\n\t\t\tthrow new CliUsageError(\n\t\t\t\t`--${rawName} is a bare flag and does not take a value.`,\n\t\t\t);\n\t\t}\n\t\tflags.set(rawName, true);\n\t\treturn index;\n\t}\n\tif (inlineValue !== undefined) {\n\t\tflags.set(rawName, inlineValue);\n\t\treturn index;\n\t}\n\n\tconst nextValue = args[index + 1];\n\tif (nextValue && !nextValue.startsWith(\"--\")) {\n\t\tflags.set(rawName, nextValue);\n\t\treturn index + 1;\n\t}\n\tflags.set(rawName, true);\n\treturn index;\n};\n\nexport const parseArguments = (args: readonly string[]): ParsedArguments => {\n\tconst positionals: string[] = [];\n\tconst flags = new Map<string, FlagValue>();\n\n\tfor (let index = 0; index < args.length; index += 1) {\n\t\tconst token = args[index];\n\t\tif (!token) continue;\n\t\tif (!token.startsWith(\"--\")) {\n\t\t\tpositionals.push(token);\n\t\t\tcontinue;\n\t\t}\n\t\tindex = recordFlag(args, index, token, flags);\n\t}\n\n\treturn { positionals, flags };\n};\n\nexport const getOptionalFlag = (\n\tparsed: ParsedArguments,\n\tname: string,\n): string | undefined => {\n\tconst value = parsed.flags.get(name);\n\tif (value === undefined) return undefined;\n\tif (value === true) throw new CliUsageError(`--${name} requires a value.`);\n\treturn value;\n};\n\nexport const getRequiredFlag = (\n\tparsed: ParsedArguments,\n\tname: string,\n): string => {\n\tconst value = getOptionalFlag(parsed, name);\n\tif (!value) throw new CliUsageError(`--${name} is required.`);\n\treturn value;\n};\n\nexport const assertOnlyFlags = (\n\tparsed: ParsedArguments,\n\tallowedFlags: readonly string[],\n): void => {\n\tconst allowed = new Set([\"api-url\", ...allowedFlags]);\n\tconst unknown = [...parsed.flags.keys()].filter((name) => !allowed.has(name));\n\tif (unknown.length > 0) {\n\t\tthrow new CliUsageError(\n\t\t\t`Unknown option${unknown.length === 1 ? \"\" : \"s\"}: ${unknown.map((name) => `--${name}`).join(\", \")}.`,\n\t\t);\n\t}\n};\n\nexport const assertPositionalCount = (\n\tparsed: ParsedArguments,\n\texpectedCount: number,\n): void => {\n\tif (parsed.positionals.length === expectedCount) return;\n\tthrow new CliUsageError(\"Unexpected positional arguments.\");\n};\n\n/** Requires a bare `--allow-state-change` and `--target` equal to the event ID. */\nexport const assertStateChangeTarget = (\n\tparsed: ParsedArguments,\n\teventId: string,\n): void => {\n\tif (parsed.flags.get(\"allow-state-change\") !== true) {\n\t\tthrow new CliUsageError(\n\t\t\t\"--allow-state-change is required as an explicit acknowledgement.\",\n\t\t);\n\t}\n\tif (getRequiredFlag(parsed, \"target\") !== eventId) {\n\t\tthrow new CliUsageError(\"--target must exactly match --event-id.\");\n\t}\n};\n\n/** Reads exactly one of an inline JSON flag or a file flag. */\nexport const readInlineOrFile = async (\n\tparsed: ParsedArguments,\n\tinlineFlag: string,\n\tfileFlag: string,\n): Promise<string> => {\n\tconst inlineValue = getOptionalFlag(parsed, inlineFlag);\n\tconst filePath = getOptionalFlag(parsed, fileFlag);\n\tif ((inlineValue === undefined) === (filePath === undefined)) {\n\t\tthrow new CliUsageError(\n\t\t\t`Provide exactly one of --${inlineFlag} or --${fileFlag}.`,\n\t\t);\n\t}\n\tif (inlineValue !== undefined) return inlineValue;\n\ttry {\n\t\treturn await readFile(filePath as string, \"utf8\");\n\t} catch {\n\t\tthrow new CliUsageError(`--${fileFlag} could not be read.`);\n\t}\n};\n\nexport const parseJsonValue = (value: string, name: string): unknown => {\n\ttry {\n\t\treturn JSON.parse(value) as unknown;\n\t} catch {\n\t\tthrow new CliUsageError(`--${name} must be valid JSON.`);\n\t}\n};\n\nexport const parsePositiveInteger = (value: string, name: string): number => {\n\tconst parsed = Number(value);\n\tif (!Number.isSafeInteger(parsed) || parsed <= 0) {\n\t\tthrow new CliUsageError(`--${name} must be a positive integer.`);\n\t}\n\treturn parsed;\n};\n\nexport const parseNonnegativeInteger = (\n\tvalue: string,\n\tname: string,\n): number => {\n\tconst parsed = Number(value);\n\tif (!Number.isSafeInteger(parsed) || parsed < 0) {\n\t\tthrow new CliUsageError(`--${name} must be a non-negative integer.`);\n\t}\n\treturn parsed;\n};\n\nexport const parseBoundedInteger = (\n\tvalue: string,\n\tname: string,\n\tminimum: number,\n\tmaximum: number,\n): number => {\n\tconst parsed = parsePositiveInteger(value, name);\n\tif (parsed > maximum || parsed < minimum) {\n\t\tthrow new CliUsageError(\n\t\t\t`--${name} must be an integer from ${minimum} to ${maximum}.`,\n\t\t);\n\t}\n\treturn parsed;\n};\n\n/** Splits a comma-separated list, rejecting blanks and duplicates. */\nexport const parseIdList = (value: string, name: string): string[] => {\n\tconst ids = value.split(\",\").map((id) => id.trim());\n\tif (ids.some((id) => id.length === 0)) {\n\t\tthrow new CliUsageError(`--${name} must not contain blank entries.`);\n\t}\n\tif (new Set(ids).size !== ids.length) {\n\t\tthrow new CliUsageError(`--${name} must not contain duplicates.`);\n\t}\n\treturn ids;\n};\n", "import { getCliStorageError } from \"@go-labs/cli-auth/client\";\nimport { CliConfigurationError } from \"@go-labs-sg/event-tech/config\";\n\nexport interface CliRuntime {\n\tstdout: { write(value: string): unknown };\n\tstderr: { write(value: string): unknown };\n}\n\nexport const processRuntime: CliRuntime = {\n\tstdout: process.stdout,\n\tstderr: process.stderr,\n};\n\nexport class CliUsageError extends Error {\n\treadonly code = \"USAGE\";\n\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"CliUsageError\";\n\t}\n}\n\nconst canonicalize = (value: unknown): unknown => {\n\tif (Array.isArray(value)) return value.map(canonicalize);\n\tif (value instanceof Date) return value.toJSON();\n\tif (typeof value === \"object\" && value !== null) {\n\t\treturn Object.fromEntries(\n\t\t\tObject.entries(value)\n\t\t\t\t.sort(([left], [right]) => left.localeCompare(right))\n\t\t\t\t.map(([key, nested]) => [key, canonicalize(nested)]),\n\t\t);\n\t}\n\treturn value;\n};\n\nconst serialize = (value: unknown): string =>\n\t`${JSON.stringify(canonicalize(value), null, 2)}\\n`;\n\nexport const writeSuccess = (runtime: CliRuntime, data: unknown): void => {\n\truntime.stdout.write(serialize({ ok: true, data }));\n};\n\nconst sanitizeErrorMessage = (message: string): string =>\n\tmessage.replace(/\\bBearer\\s+\\S+/giu, \"Bearer [REDACTED]\");\n\nconst errorCode = (error: unknown): string => {\n\tif (error instanceof CliUsageError) return error.code;\n\tif (error instanceof CliConfigurationError) return error.code;\n\tif (typeof error === \"object\" && error !== null && \"data\" in error) {\n\t\tconst data = error.data;\n\t\tif (\n\t\t\ttypeof data === \"object\" &&\n\t\t\tdata !== null &&\n\t\t\t\"code\" in data &&\n\t\t\ttypeof data.code === \"string\"\n\t\t) {\n\t\t\treturn data.code;\n\t\t}\n\t}\n\treturn \"INTERNAL_ERROR\";\n};\n\nexport const writeError = (runtime: CliRuntime, error: unknown): void => {\n\tconst storageError = getCliStorageError(error);\n\tif (storageError) {\n\t\truntime.stderr.write(serialize({ ok: false, error: storageError }));\n\t\treturn;\n\t}\n\tconst message =\n\t\terror instanceof Error\n\t\t\t? sanitizeErrorMessage(error.message)\n\t\t\t: \"Unknown error.\";\n\truntime.stderr.write(\n\t\tserialize({ ok: false, error: { code: errorCode(error), message } }),\n\t);\n};\n", "import { DEFAULT_EVENT_TECH_API_BASE_URL } from \"@go-labs-sg/event-tech/config\";\n\nexport const usage = `Event Tech CLI\n\nFirst step before each task: update to the latest published release with 'bun add --global @go-labs-sg/event-tech@latest', then run 'et version' and 'et --help' before using commands. Update once per task. If updating fails, stop and report it. Preserve an explicitly requested pinned or development/staging version.\n\nUsage:\n et auth login [--no-browser]\n et auth status\n et auth logout\n et auth whoami\n et organization list\n et organization get --organization-id <id>\n et organization create --name <text> --owner-email <email> [--allowed-event-types <TYPE,...>]\n et event list --organization-id <id> [--page <n>] [--per-page <n>] [--name <text>] [--status <status>] [--archive-status <status>]\n et event get --event-id <id>\n et event create --organization-id <id> --name <text> --type <type> --location <text> --start <iso> [--end <iso>]\n et event appearance get --event-id <id> [--public]\n et event appearance update --event-id <id> --appearance-version <n> --appearance <json>\n et event appearance reset --event-id <id> --appearance-version <n>\n et event appearance upload --event-id <id> --file <path> --media-type <image|video> --content-type <mime>\n et event photo-wall display-items --event-id <id> [--limit <n>] [--cursor <json>] [--retained-ids <json>]\n et lucky-draw config get --event-id <id>\n et lucky-draw config update --event-id <id> (--config <json> | --config-file <path>) [--dry-run]\n et lucky-draw background upload --event-id <id> --file <path> --content-type <image-mime>\n et lucky-draw background clear --event-id <id> --allow-state-change --target <same-event-id>\n et lucky-draw prizes list --event-id <id>\n et lucky-draw prizes create --event-id <id> (--name <text> [--description <text>] | --prizes <json-array> | --prizes-file <path>)\n et lucky-draw prizes update --event-id <id> --prize-id <id> --name <text> [--description <text>]\n et lucky-draw prizes delete --event-id <id> --prize-ids <id,...> --allow-state-change --target <same-event-id>\n et lucky-draw prizes reorder --event-id <id> --prize-ids <id,...>\n et lucky-draw pre-draw --event-id <id> --prize-count <n>\n et lucky-draw participants replace --event-id <id> (--participants <json-array> | --participants-file <path>) --allow-state-change --target <same-event-id>\n et lucky-draw participants list --event-id <id> [--page <n>] [--per-page <n>]\n et passport overview --event-id <id>\n et passport mine --event-id <id>\n et passport menu-stock --event-id <id> [--station-id <id>] [--site <building>] (guest stock; --station-id reads organizer stock; includes building pools)\n et passport login-options --event-id <id>\n et passport queue-status --event-id <id> (what guests see: enabled, staleMinutes and the crew-set waits in stations, plus defaultStatus and defaultStationIds for visible stations crew set none for, which read \"< 10 mins\"; overview gives each station's queueStatus and queueStatusDefault)\n et passport bingo enable --event-id <id> (host: creates the hidden Bingo station and the HumanBingo)\n et passport bingo rename --event-id <id> --name <name> (host: the game's display name guests see; 1-100 chars, default \"Human Bingo\")\n et passport bingo join --event-id <id> (guest, passport participants only)\n et passport bingo claim-stamp --event-id <id> (guest: catch-up award for a completed card)\n et passport bingo status --event-id <id> (guest: own bingo progress and stamp)\n et passport export --event-id <id>\n et passport settings update --event-id <id> --settings-json <json> (maxRedemptionsPerParticipant 0 = no cap; optional guestScan and simplifiedChinese true|false; optional staffIdLabel string|null; optional categoryLabels object|null; optional queueStatus true|false and queueStatusStaleMinutes 1-240|null)\n et passport station upsert --event-id <id> --station-json <json> (collection.stampValue 0-1000, default 1; collection.category GAME|FOOD|DRINK|BINGO, default GAME; collection.prizeDeskAward true|false on SELF_SCAN/STAFF_SCAN, default false; collection.showHowToCollect true|false and collection.showMyQr true|false, default true; collection.collectionLimit ONCE|UNLIMITED for food/drink menus, default ONCE)\n et passport station-access get --event-id <id>\n et passport station-access set-password --event-id <id> --password-stdin --allow-state-change --target <same-event-id> (password read from stdin; 6-128 chars; ends every station session)\n et passport station-access clear-password --event-id <id> --allow-state-change --target <same-event-id> (turns station links off; ends every station session)\n et passport stamps stats --event-id <id>\n et passport stamps recipients --event-id <id> --station-id <id> [--search <text>] [--limit <1-100>] [--cursor <cursor>] [--direction <forward|backward>]\n et passport stamps recipient-counts --event-id <id> --station-id <id> [--search <text>]\n et passport skin get --event-id <id>\n et passport skin set --event-id <id> --appearance-version <n> --skin-json <json>\n et passport skin clear --event-id <id> --appearance-version <n>\n et passport skin upload --event-id <id> --kind <hero|logo> --file <path> --content-type <image-mime>\n et passport station image-set --event-id <id> --station-id <id> --file <path> --content-type <image-mime>\n et passport station image-clear --event-id <id> --station-id <id>\n et passport station hidden --event-id <id> --station-id <id> --hidden <true|false>\n et passport station queue-status --event-id <id> --station-id <id> --status <under-10|under-30|over-30|clear> (set or clear the wait guests see; clear returns the station to the \"< 10 mins\" default; needs queueStatus on; re-sending a wait refreshes its time)\n et passport station archive --event-id <id> --station-id <id> --allow-state-change --target <same-event-id>\n et passport station print-get --event-id <id> --station-id <id>\n et passport station print-issue --event-id <id> --station-id <id> --expected-printed-qr-version <n>\n et passport station print-revoke --event-id <id> --station-id <id> --expected-printed-qr-version <n> --allow-state-change --target <same-event-id>\n et passport station start-qr --event-id <id> --station-id <id>\n et passport station qr-status --event-id <id> --session-id <id>\n et passport collect --event-id <id> --station-id <id> --profile-code <code> [--points <n>] [--item <menu-item>] [--site <building>] [--request-id <uuid>]\n et passport claim --event-id <id> --code <code>\n et passport participant search --event-id <id> [--query <text>]\n et passport participant detail --event-id <id> --participant-id <id>\n et passport stamp correct --event-id <id> --station-id <id> --participant-id <id> --stamped <true|false> --reason <text> [--points <n>] [--item <menu-item>] [--site <building>] [--collection-id <id>] --allow-state-change --target <same-event-id>\n et passport prize upsert --event-id <id> --prize-json <json> (stampCost: stamps per unit, default 0; imageKey: omit keeps the photo, null clears it)\n et passport prize image-set --event-id <id> --prize-id <id> --file <path> --content-type <image-mime>\n et passport prize image-clear --event-id <id> --prize-id <id>\n et passport prize archive --event-id <id> --prize-id <id> --allow-state-change --target <same-event-id>\n et passport redemption create --event-id <id> --participant-id <id> --prize-id <id> [--quantity <1-20>] [--award-station-id <id>] [--bonus-stamps <0-1000>] [--request-id <uuid>]\n et passport redemption reverse --event-id <id> --redemption-id <id> --reason <text> --allow-state-change --target <same-event-id>\n et passport tally record --event-id <id> --station-id <id> --profile-code <code> --item <name> [--quantity <1-20>]\n et passport tally reverse --event-id <id> --tally-id <id> --reason <text> --allow-state-change --target <same-event-id>\n et passport tally summary --event-id <id>\n et passport tally list --event-id <id> --station-id <id>\n et passport roster list --event-id <id> [--search <text>] [--limit <1-100>] [--cursor <cursor>]\n et passport roster counts --event-id <id> [--search <text>]\n et passport roster import --event-id <id> --file <path.csv|path.xlsx> [--staff-id-column <header>] [--last-name-column <header|none>] [--full-name-column <header|none>] [--display-name-column <header|none>] [--surname-position <last|first>]\n et passport roster upsert --event-id <id> --entry-json <json> ({id?,staffId,lastName,displayName}; lastName may be null only when the event does not require it)\n et passport roster remove --event-id <id> --entry-id <id> --allow-state-change --target <same-event-id>\n et passport roster purge --event-id <id> --allow-state-change --target <same-event-id>\n et staff-redemption roster import --event-id <id> --file <path.csv|path.xlsx> [--sheet <name>] [--employee-id-column <header>] [--name-column <header|none>] [--site-column <header|none>] [--shift-column <header|none>] [--work-shift-column <header|none>] [--allowance-column <header|none>] [--archive-missing] --allow-state-change --target <same-event-id>\n et staff-redemption export --event-id <id> [--search <text>] [--site-id <id>] [--session-id <id>] [--status <active|voided|all>] [--csv-file <path> [--force]]\n\nEvent Passport:\n Uses the same typed procedures and event permissions as the web app.\n Station collection modes: SELF_SCAN, STAFF_SCAN, STAFF_SCORE, STAFF_TALLY.\n STAFF_TALLY needs collection.tallyItems (1-30 unique names) and optional tallyEarnsStamp (default false).\n collection.showMyQr false hides the station sheet's Show my QR action (including the self-scan alternative); omit preserves the stored value (default true).\n collection.showHowToCollect false hides the guest instructions panel in any mode; omit preserves the stored value (default true).\n FOOD/DRINK STAFF_SCAN may set collection.menuItems to 1-30 {name,stock,siteStocks?} entries; names are unique ignoring case and surrounding whitespace, max 60 chars. stock is 0..2147483647 or null for unlimited; omit menuItems to preserve, null to clear. Optional siteStocks is [{site,stock}]; every item needs the same sites. Building pools replace the single pool, and collect requires --site for them.\n collection.collectionLimit ONCE (default) blocks a second collection per person across buildings; UNLIMITED allows repeats. Omit preserves the stored limit. Each new collection uses one unit; repeats add no stamp credit. collect --request-id <uuid> is required for UNLIMITED and must be reused for a retry; a new deliberate give needs a new UUID. stamp correct --stamped false --collection-id <id> reverses that specific collection and restores its unit; --stamped true with the same collection ID restores the serving from its original stock. Omit item/site/points with collection-id. mine, participant detail, tally list and export include collections with item and site.\n Include collection.maxPoints only for STAFF_SCORE; zero is a valid score.\n collection.category groups stations for guests: GAME, FOOD, DRINK or BINGO. Omit it to keep the stored one.\n Omit collection on an existing station to preserve its current mode.\n Station JSON supports id/name/description/location/address/imageKey/order/opensAt/closesAt/collection.\n imageKey is the cover art: omit it to keep the stored image, null clears it.\n location is the in-venue spot (\"Level 2 pantry\"); address is the street or site address (up to 300 chars, null clears it, omit keeps it).\n Station links: one shared password per passport lets staff without accounts open /events/<id>/event-passport/station,\n pick a station and stamp guests. station-access get shows whether a password is set and how many station sessions are\n active; set-password (stdin only) and clear-password both end every existing station session; no password means links are\n off. stamps stats reports per-station stamp counts; stamps recipients lists who each station stamped and how\n (issuedBy.kind: participant self-scan, station-link, staff by name, bingo for a bingo award, or prize-desk for a stamp\n awarded with a prize redemption; page with\n --cursor, backward needs a cursor). Station sessions themselves are browser-only.\n Prize-desk award: collection.prizeDeskAward (true|false, SELF_SCAN and STAFF_SCAN only, not the Bingo category; omit\n to keep, absent means off) lets crew give that station's stamp with a prize. redemption create --award-station-id\n <id> gives one such station's stamp (its stampValue, source PRIZE_DESK) in the same transaction as the redemption;\n its stamps count toward this redemption's threshold and cost; a failure awards neither the stamp nor the prize.\n A station the participant already holds is refused, and\n --bonus-stamps awards 0-1000 extra stamps (default 0) once per redemption, alongside any station award;\n they count toward earned and spendable stamps and the lucky draw. Reversal removes the bonus.\n redemption reverse revokes the awarded stamp. participant detail lists awardStations (alreadyCollected,\n blockedReason) and redemptions[].awardedStation and bonusStamps. --request-id makes a retry safe (a retry of a since-reversed redemption is refused; use a new id).\n Station cover art: image-set uploads a jpeg/png/webp/gif (up to 25 MB) to the event's station-art folder and\n saves it as the station's imageKey, keeping every other station setting; image-clear removes it. A new\n imageKey given in station JSON must be an upload to this event's event-passport/stations folder.\n Prize photos work the same way: prize image-set uploads a jpeg/png/webp/gif (up to 25 MB) to the event's prize folder and\n saves it as the prize's imageKey, keeping every other prize setting; image-clear removes it (guests then see the gift\n illustration). A new imageKey given in prize JSON must be an upload to this event's event-passport/prizes folder.\n Passport skin (optional per-event look; no skin renders the Go Labs default): lives in the event\n appearance as the optional passport block {heroImage:{key,focalX,focalY}|null, logo:{key}|null,\n colors:{graphic,dark}, emphasis:accent|ink}. skin get reads it with the version and image URLs.\n skin set is a version-fenced merge patch: --skin-json '{\"heroImage\":{\"focalX\":30}}' changes only the\n focal point; null clears heroImage or logo. skin upload --kind hero|logo returns the key to reference\n in skin set. skin clear returns the event to the Go Labs default look and keeps the rest of the appearance.\n Other appearance saves that omit passport keep the stored skin. colors.dark needs 4.5:1 contrast with white.\n Staff Redemption events use the same block and commands: colors.graphic, colors.dark and emphasis (with the event\n theme) also theme the crew counter and its prize wheel (Settings > Appearance > Counter look). heroImage and logo are\n Passport-only: the counter ignores them; skin set keeps stored ones unless the patch names them, skin clear resets\n the whole block.\n Date-time fields are ISO strings or null; order defaults to zero.\n Settings JSON requires linkedDrawEventId, luckyDrawStampThreshold, prizeStampThreshold,\n maxRedemptionsPerParticipant; optional loginMethods is {emailOtp,google,guest,staffId,staffIdRequiresLastName}.\n Keep email OTP, Google or roster sign-in (staffId) enabled for recovery; staffId defaults to false and\n staffIdRequiresLastName to true, so set it false again whenever you resend loginMethods.\n Omit loginMethods to preserve it. Optional guestScan (boolean) turns guest station QR scanning\n on or off; omit it to keep the stored value (absent means on). When off, guests cannot self-scan\n (staff and station crew still stamp) and the guest passport hides the Scan tab. overview shows\n passport.guestScan and mine shows settings.guestScanEnabled. Optional simplifiedChinese (boolean,\n absent means off) offers a Simplified Chinese option on the guest passport; organiser-entered text\n stays as entered. overview shows passport.simplifiedChinese and login-options shows simplifiedChinese.\n Optional staffIdLabel (string up to 40 chars, or null to reset) names the roster identifier guests,\n station crew and organisers see; it defaults to \"Employee Number\", so send \"Staff ID\" for events\n that call it that. Omit it to keep the stored label; the Chinese passport keeps 员工编号. overview\n shows passport.staffIdLabel, login-options shows staffIdLabel, mine shows settings.staffIdLabel and\n export returns staffIdLabel. Only the wording changes; the staffId fields and flags keep their names.\n Optional categoryLabels ({GAME,FOOD,DRINK,BINGO: {en,\"zh-CN\"}}, each name 1-40 chars after trimming, or null\n to clear) renames the station categories guests, crew and organisers see; omit it to keep the stored names,\n send an object to replace them all (a blank name means the built-in wording) and null to clear them. A\n Simplified Chinese guest sees the zh-CN name, else the built-in Chinese, never the English one. overview\n shows passport.categoryLabels, login-options shows categoryLabels and mine shows settings.categoryLabels.\n Optional queueStatus (boolean, absent means off) lets station crew set a wait per station that guests\n see in their passport: under-10, under-30 or over-30 minutes. Optional queueStatusStaleMinutes (1-240,\n or null to reset to 10) is how long a set wait stays trusted before guests see \"Not updated recently\".\n overview shows passport.queueStatus, passport.queueStatusStaleMinutes and each station's queueStatus\n ({status,updatedAt} for a crew-set wait, else null) and queueStatusDefault; queue-status shows the guest\n view. While queueStatus is on, every visible station shows a wait: a station crew never set (or cleared)\n has queueStatus null and queueStatusDefault UNDER_10_MIN (\"< 10 mins\"), a default that never goes stale; a\n crew-set wait overrides it (queueStatusDefault null) and reads \"Not updated recently\" after\n queueStatusStaleMinutes. queueStatusDefault is null while queueStatus is off and for hidden stations.\n station queue-status sets or clears one wait as an event operator (crew do the same in the browser; clear\n prints queueStatus null and queueStatusDefault UNDER_10_MIN), is refused while queueStatus is off, and\n every change is recorded in the activity log. Turning queueStatus off hides waits from guests but keeps them.\n Staff roster: event Helpdesk can list/count and add new entries with roster upsert (omit id).\n Helpdesk cannot edit an existing entry, import, remove, purge, export, or use other event tools.\n Managers retain full roster access. Assign/invite HELPDESK with expiresAt for event-day access;\n normal verified-email login and event assignment/revocation apply, not the station password.\n Host-only import replaces the roster and returns imported, replaced and\n rejected rows (blank, too long, or a Staff ID repeated in the file). Columns are matched from\n header names; override with the column flags. Without a last-name column, the last name is\n taken from the full name (--surname-position last|first, default last). Files over 20,000 data\n rows or 200 columns, or with no importable rows, are refused and the roster is unchanged. A blank\n last name is rejected only when the event requires one; counts reports missingLastNameCount.\n Staff ID sign-in matches case-insensitively, ignoring spaces and punctuation, and needs the browser.\n Printed QR issue/revoke requires the last observed print version; stale versions conflict.\n claim scans a station QR; collect scans a participant profile QR as an event operator.\n Repeat scans never add a second stamp or change its original points.\n Destructive corrections, archive, reverse and print revoke require explicit target confirmation.\n Points are scores only; existing stamp-based Lucky Draw and prize thresholds still apply.\n Guest enrollment and account-linking require the browser; CLI uses existing device-approved auth.\n\nStaff redemption (STAFF_REDEMPTION events; most commands are registry commands, see below):\n Crew look up an Employee ID at a site counter, record the food items handed over and reveal a prize\n outcome the server decides in the same transaction. Setup is: settings, sites, crew passwords,\n sessions (one per shift), slots (sets per session and site), item groups and items, prizes, prize\n stock, roster. Run 'et staff-redemption setup get' for the IDs and what is still missing.\n roster import reads a CSV, or an XLSX sheet (the first unless --sheet <name> names another; an unknown\n name lists the workbook's sheets; a CSV has no sheets and refuses --sheet), matches columns from header names (override\n with the column flags; \"none\" clears an optional column), adds new Employee IDs and updates existing\n ones, and reports created, updated, unchanged, archived, rejectedCount, rejected rows and\n unmatchedSites. Existing rows are never deleted, so redemptions survive a re-import; --archive-missing archives active entries that are not in the file.\n Use --sheet \"Master list\" to import that tab of a workbook (exact name, else ignoring case and spaces).\n export prints the redemption rows as JSON, or with --csv-file writes a CSV (UTF-8 with BOM, CRLF,\n one row per claim, oldest first, text that would run as a spreadsheet formula gets a leading\n apostrophe) and prints { file, rows }. It never overwrites a file unless --force. It needs event.export\n and fails above 20,000 rows; narrow the filters.\n Crew sign-in with a site password and the counter access check are browser-only; the CLI operates\n counters as event staff (event.operate) and names the site with siteId.\n Archive and unarchive use 'staff-redemption archive set' with archived true or false.\n Every write repeats the event ID as --target. Lookup needs no confirmation (it writes nothing\n but failed-lookup throttle records). Redeem takes a clientRequestId UUID you generate;\n retrying with the same UUID returns the stored receipt and never redeems twice.\n\nOrganization and event setup:\n organization create is global-admin only. It provisions the org and emails an owner invitation\n to --owner-email after it is saved; deliveryStatus (sent/failed) and\n ownerInvitation.emailDeliveryStatus report the outcome. Names must be unique.\n event create needs org owner/admin (or global admin). --type is an active event type such as\n LUCKY_DRAW; a LUCKY_DRAW event gets its board with default config automatically.\n --start/--end are ISO 8601 date-times with an offset, for example 2026-11-20T18:00:00+08:00.\n\nLucky draw:\n config, background and prize writes need event.setup, the same as the web board settings.\n config update is a merge patch: only the given keys change. Unknown keys and wrong value types\n are rejected before any request. Arrays (includeDomains etc.) are replaced, not appended.\n --dry-run prints the merged config without saving it.\n Keys: title, titleColor, isTitleVisible, titleFontSize, titleFont, prizeColor, prizeFontSize,\n isPrizeVisible, prizeFont, luckyDrawType (WHEEL|SLOT), slotBackgroundColor, slotBorderColor,\n slotTextColor, slotFontSize, slotTextFont, backgroundPreset, customBackgroundImage,\n numberOfSegments, segmentPreset, segmentText (NAME|LUCKY_DRAW_ID|BOTH), wheelSegmentFont,\n wheelSegmentFontSize, wheelSegmentColorsPreset, includeDomains, excludeDomains, includeEmails,\n excludeEmails, titlePositionX/Y, slotPositionX/Y, prizePositionX/Y, prizeDivWidth, prizeDivHeight.\n Positions are pixels on the 1920x1080 board.\n background upload stores the image (jpeg/png/webp/gif) and sets customBackgroundImage;\n the readback contains a signed /api/attachments URL. background clear unsets it.\n prizes create appends after the last prize; --prizes takes [{\"name\",\"description\"?}].\n prizes delete permanently removes unassigned prizes and renumbers the rest.\n prizes reorder takes every active prize ID once, in the new order.\n pre-draw immediately saves winners for the next unassigned prizes in order.\n Uses the live draw random selection and participant filters in the backend.\n participants replace replaces the imported source roster; it is not an append.\n It requires --allow-state-change and --target exactly equal to --event-id.\n participants list defaults to page 1 with 100 results per page; inspect every page.\n\nRegistry commands (staff and admin operations, one per API procedure):\n et commands List every registry command as JSON.\n et <command> --help Show its input JSON Schema and confirmations.\n et <command> [--input <json> | --input-file <path>]\n et <write command> --input <json> --allow-state-change [--allow-delete] [--allow-email] --target <value>\n Groups: organization member/owner/invitation/update/image/archive/access/dashboard/analytics,\n admin organization/event/member/user/activity/dashboard, event access/details/update/\n status-update/archive/restore/duplicate/export/recent/background/story, activity list,\n lucky-draw winners/boards/participants eligible|delete/wheel/passport-sync,\n passport lucky-draws/operator-metadata, photo-wall, post-it, signature-wall, rating, human-bingo,\n staff-redemption setup/settings/site/crew-password/session/slot/item-group/item/prize/prize-stock/\n archive/roster list|counts|upsert/claims/draw/stock/counter/lookup/redeem.\n --input is passed unchanged to the procedure, so field names match the web app.\n Date fields take ISO 8601 strings and are sent as dates.\n Writes require --allow-state-change and --target equal to the input key shown by --help\n (arrays joined with commas). Hard deletes add --allow-delete; emails add --allow-email.\n Run every write once with --help first and read back the result afterwards.\n\nGlobal options:\n Bare flags (--dry-run, --allow-state-change, --allow-delete, --allow-email, --public,\n --no-browser) take no value;\n --flag=value spellings are rejected before any request.\n --api-url <url> Override EVENT_TECH_API_URL.\n --help Print this help as JSON.\n --version Print the CLI version as JSON.\n\nAuthentication:\n Run et auth login, then approve the matching device in Event Tech.\n Credentials are stored exclusively through Bun.secrets.\n EVENT_TECH_API_URL defaults to ${DEFAULT_EVENT_TECH_API_BASE_URL}.`;\n", "import { readFile } from \"node:fs/promises\";\nimport { basename } from \"node:path\";\nimport {\n\ttype LuckyDrawConfig,\n\tluckyDrawConfigSchema,\n} from \"@go-labs/event-tech-validators/lucky-draw/lucky-draw-config.schema\";\nimport { DEFAULT_LUCKY_DRAW_CONFIG_INPUT_VALUES } from \"@go-labs/event-tech-validators/lucky-draw/lucky-draw-config-input.schema\";\nimport { luckyDrawPrizeInputSchema } from \"@go-labs/event-tech-validators/lucky-draw/lucky-draw-prize-input.schema\";\nimport { api, type RouterInputs } from \"@go-labs-sg/event-tech/api-client\";\nimport {\n\tassertOnlyFlags,\n\tassertPositionalCount,\n\tassertStateChangeTarget,\n\tgetOptionalFlag,\n\tgetRequiredFlag,\n\ttype ParsedArguments,\n\tparseIdList,\n\tparseJsonValue,\n\treadInlineOrFile,\n} from \"@go-labs-sg/event-tech/arguments\";\nimport {\n\ttype CliRuntime,\n\tCliUsageError,\n\twriteSuccess,\n} from \"@go-labs-sg/event-tech/runtime\";\n\ntype LuckyDrawInputs = RouterInputs[\"event\"][\"luckyDraw\"];\ntype PrizeCreateInput = LuckyDrawInputs[\"createLuckyDrawPrize\"];\n\n/** Same folder the web preview form uses for lucky draw backgrounds. */\nconst LUCKY_DRAW_BACKGROUND_FOLDER = \"lucky-draw/backgrounds\";\n\nconst luckyDrawConfigPatchSchema = luckyDrawConfigSchema.partial().strict();\n\ninterface ValidationIssue {\n\tpath: readonly PropertyKey[];\n\tmessage: string;\n}\n\nconst formatIssues = (label: string, issues: readonly ValidationIssue[]) =>\n\t`${label} is invalid: ${issues\n\t\t.map((issue) => {\n\t\t\tconst path = issue.path.map(String).join(\".\");\n\t\t\treturn path ? `${path}: ${issue.message}` : issue.message;\n\t\t})\n\t\t.join(\"; \")}.`;\n\n/**\n * Validates a partial config patch, rejecting unknown keys and wrong value\n * types before anything is sent to the API.\n */\nexport const parseLuckyDrawConfigPatch = (\n\traw: string,\n): Partial<LuckyDrawConfig> => {\n\tconst value = parseJsonValue(raw, \"config\");\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow new CliUsageError(\"--config must be a JSON object.\");\n\t}\n\tconst result = luckyDrawConfigPatchSchema.safeParse(value);\n\tif (!result.success) {\n\t\tthrow new CliUsageError(formatIssues(\"--config\", result.error.issues));\n\t}\n\tif (Object.keys(result.data).length === 0) {\n\t\tthrow new CliUsageError(\"--config must change at least one field.\");\n\t}\n\treturn result.data;\n};\n\n/**\n * Merge-patches config onto the stored value. Missing stored fields fall back\n * to the same defaults the web preview form uses, so legacy rows stay valid.\n * Arrays such as includeDomains are replaced, not concatenated.\n */\nexport const mergeLuckyDrawConfig = (\n\tcurrent: Partial<LuckyDrawConfig> | null | undefined,\n\tpatch: Partial<LuckyDrawConfig>,\n): LuckyDrawConfig => {\n\tconst merged = {\n\t\t...DEFAULT_LUCKY_DRAW_CONFIG_INPUT_VALUES,\n\t\t...(current ?? {}),\n\t\t...patch,\n\t};\n\tconst result = luckyDrawConfigSchema.safeParse(merged);\n\tif (!result.success) {\n\t\tthrow new CliUsageError(\n\t\t\tformatIssues(\"Merged lucky draw config\", result.error.issues),\n\t\t);\n\t}\n\treturn result.data;\n};\n\nexport const parsePrizeList = (raw: string): PrizeCreateInput[\"prizes\"] => {\n\tconst value = parseJsonValue(raw, \"prizes\");\n\tif (!Array.isArray(value) || value.length === 0) {\n\t\tthrow new CliUsageError(\"--prizes must be a non-empty JSON array.\");\n\t}\n\tif (value.length > 500) {\n\t\tthrow new CliUsageError(\"--prizes must contain at most 500 prizes.\");\n\t}\n\treturn value.map((item: unknown, index) => {\n\t\tconst result = luckyDrawPrizeInputSchema.strict().safeParse(item);\n\t\tif (!result.success) {\n\t\t\tthrow new CliUsageError(\n\t\t\t\tformatIssues(`--prizes[${index}]`, result.error.issues),\n\t\t\t);\n\t\t}\n\t\treturn result.data;\n\t});\n};\n\nconst loadCurrentConfig = async (eventId: string) =>\n\t(await api.event.luckyDraw.getLuckyDrawByEventId.query({ eventId })).config;\n\nconst loadPrizes = async (eventId: string) =>\n\t(await api.event.luckyDraw.getLuckyDrawPrizesByEventId.query({ eventId }))\n\t\t.prizes;\n\n/** Rejects prize IDs that are not active prizes of the targeted event. */\nconst assertPrizesBelongToEvent = (\n\tprizes: readonly { id: string }[],\n\tprizeIds: readonly string[],\n\teventId: string,\n) => {\n\tconst known = new Set(prizes.map((prize) => prize.id));\n\tconst missing = prizeIds.filter((id) => !known.has(id));\n\tif (missing.length > 0) {\n\t\tthrow new CliUsageError(\n\t\t\t`Prize ID(s) not found on event ${eventId}: ${missing.join(\", \")}.`,\n\t\t);\n\t}\n};\n\nconst saveConfig = (eventId: string, config: LuckyDrawConfig) =>\n\tapi.event.luckyDraw.updateLuckyDrawConfigJson.mutate({ eventId, config });\n\ninterface LuckyDrawSetupContext {\n\tparsed: ParsedArguments;\n\truntime: CliRuntime;\n\tauthenticate: () => Promise<void>;\n}\n\nconst runConfigGet = async ({\n\tparsed,\n\truntime,\n\tauthenticate,\n}: LuckyDrawSetupContext) => {\n\tassertPositionalCount(parsed, 3);\n\tassertOnlyFlags(parsed, [\"event-id\"]);\n\tconst eventId = getRequiredFlag(parsed, \"event-id\");\n\tawait authenticate();\n\twriteSuccess(\n\t\truntime,\n\t\tawait api.event.luckyDraw.getLuckyDrawByEventId.query({ eventId }),\n\t);\n};\n\nconst runConfigUpdate = async ({\n\tparsed,\n\truntime,\n\tauthenticate,\n}: LuckyDrawSetupContext) => {\n\tassertPositionalCount(parsed, 3);\n\tassertOnlyFlags(parsed, [\"event-id\", \"config\", \"config-file\", \"dry-run\"]);\n\tconst eventId = getRequiredFlag(parsed, \"event-id\");\n\tconst patch = parseLuckyDrawConfigPatch(\n\t\tawait readInlineOrFile(parsed, \"config\", \"config-file\"),\n\t);\n\tawait authenticate();\n\tconst config = mergeLuckyDrawConfig(await loadCurrentConfig(eventId), patch);\n\tif (parsed.flags.get(\"dry-run\") === true) {\n\t\twriteSuccess(runtime, {\n\t\t\tdryRun: true,\n\t\t\tchangedFields: Object.keys(patch).sort(),\n\t\t\tconfig,\n\t\t});\n\t\treturn;\n\t}\n\twriteSuccess(runtime, await saveConfig(eventId, config));\n};\n\nconst runBackgroundUpload = async ({\n\tparsed,\n\truntime,\n\tauthenticate,\n}: LuckyDrawSetupContext) => {\n\tassertPositionalCount(parsed, 3);\n\tassertOnlyFlags(parsed, [\"event-id\", \"file\", \"content-type\"]);\n\tconst eventId = getRequiredFlag(parsed, \"event-id\");\n\tconst filePath = getRequiredFlag(parsed, \"file\");\n\tconst contentType = getRequiredFlag(parsed, \"content-type\");\n\tif (!contentType.startsWith(\"image/\")) {\n\t\tthrow new CliUsageError(\"--content-type must be an image MIME type.\");\n\t}\n\tlet file: Buffer<ArrayBuffer>;\n\ttry {\n\t\tfile = await readFile(filePath);\n\t} catch {\n\t\tthrow new CliUsageError(\"--file could not be read.\");\n\t}\n\tawait authenticate();\n\tconst signed = await api.attachment.getPresignedUrlToUpload.mutate({\n\t\tfolder: LUCKY_DRAW_BACKGROUND_FOLDER,\n\t\tfileName: basename(filePath),\n\t\tcontentType,\n\t\tsize: file.byteLength,\n\t\teventId,\n\t});\n\tconst uploadResponse = await fetch(signed.uploadUrl, {\n\t\tmethod: \"PUT\",\n\t\theaders: { \"content-type\": contentType },\n\t\tbody: file,\n\t});\n\tif (!uploadResponse.ok) {\n\t\tthrow new Error(\n\t\t\t`Lucky draw background upload failed with HTTP ${uploadResponse.status}.`,\n\t\t);\n\t}\n\tconst config = mergeLuckyDrawConfig(await loadCurrentConfig(eventId), {\n\t\tcustomBackgroundImage: signed.key,\n\t});\n\tawait saveConfig(eventId, config);\n\twriteSuccess(\n\t\truntime,\n\t\tawait api.event.luckyDraw.getLuckyDrawByEventId.query({ eventId }),\n\t);\n};\n\nconst runBackgroundClear = async ({\n\tparsed,\n\truntime,\n\tauthenticate,\n}: LuckyDrawSetupContext) => {\n\tassertPositionalCount(parsed, 3);\n\tassertOnlyFlags(parsed, [\"event-id\", \"allow-state-change\", \"target\"]);\n\tconst eventId = getRequiredFlag(parsed, \"event-id\");\n\tassertStateChangeTarget(parsed, eventId);\n\tawait authenticate();\n\tconst config = mergeLuckyDrawConfig(await loadCurrentConfig(eventId), {\n\t\tcustomBackgroundImage: null,\n\t});\n\twriteSuccess(runtime, await saveConfig(eventId, config));\n};\n\nconst runPrizesList = async ({\n\tparsed,\n\truntime,\n\tauthenticate,\n}: LuckyDrawSetupContext) => {\n\tassertPositionalCount(parsed, 3);\n\tassertOnlyFlags(parsed, [\"event-id\"]);\n\tconst eventId = getRequiredFlag(parsed, \"event-id\");\n\tawait authenticate();\n\twriteSuccess(\n\t\truntime,\n\t\tawait api.event.luckyDraw.getLuckyDrawPrizesByEventId.query({ eventId }),\n\t);\n};\n\nconst runPrizesCreate = async ({\n\tparsed,\n\truntime,\n\tauthenticate,\n}: LuckyDrawSetupContext) => {\n\tassertPositionalCount(parsed, 3);\n\tassertOnlyFlags(parsed, [\n\t\t\"event-id\",\n\t\t\"name\",\n\t\t\"description\",\n\t\t\"prizes\",\n\t\t\"prizes-file\",\n\t]);\n\tconst eventId = getRequiredFlag(parsed, \"event-id\");\n\tconst name = getOptionalFlag(parsed, \"name\");\n\tconst description = getOptionalFlag(parsed, \"description\");\n\tconst hasList = parsed.flags.has(\"prizes\") || parsed.flags.has(\"prizes-file\");\n\tif (hasList === (name !== undefined)) {\n\t\tthrow new CliUsageError(\n\t\t\t\"Provide either --name [--description] or one of --prizes / --prizes-file.\",\n\t\t);\n\t}\n\tif (hasList && description !== undefined) {\n\t\tthrow new CliUsageError(\n\t\t\t\"--description is only valid with --name; include descriptions in the --prizes JSON.\",\n\t\t);\n\t}\n\tconst prizes = hasList\n\t\t? parsePrizeList(await readInlineOrFile(parsed, \"prizes\", \"prizes-file\"))\n\t\t: parsePrizeList(\n\t\t\t\tJSON.stringify([\n\t\t\t\t\t{ name, ...(description === undefined ? {} : { description }) },\n\t\t\t\t]),\n\t\t\t);\n\tawait authenticate();\n\twriteSuccess(\n\t\truntime,\n\t\tawait api.event.luckyDraw.createLuckyDrawPrize.mutate({\n\t\t\teventId,\n\t\t\tprizes,\n\t\t}),\n\t);\n};\n\nconst runPrizesUpdate = async ({\n\tparsed,\n\truntime,\n\tauthenticate,\n}: LuckyDrawSetupContext) => {\n\tassertPositionalCount(parsed, 3);\n\tassertOnlyFlags(parsed, [\"event-id\", \"prize-id\", \"name\", \"description\"]);\n\tconst eventId = getRequiredFlag(parsed, \"event-id\");\n\tconst prizeId = getRequiredFlag(parsed, \"prize-id\");\n\tconst name = getRequiredFlag(parsed, \"name\");\n\tconst description = getOptionalFlag(parsed, \"description\");\n\tawait authenticate();\n\tassertPrizesBelongToEvent(await loadPrizes(eventId), [prizeId], eventId);\n\twriteSuccess(\n\t\truntime,\n\t\tawait api.event.luckyDraw.updateLuckyDrawPrize.mutate({\n\t\t\tid: prizeId,\n\t\t\tname,\n\t\t\t...(description === undefined ? {} : { description }),\n\t\t}),\n\t);\n};\n\nconst runPrizesDelete = async ({\n\tparsed,\n\truntime,\n\tauthenticate,\n}: LuckyDrawSetupContext) => {\n\tassertPositionalCount(parsed, 3);\n\tassertOnlyFlags(parsed, [\n\t\t\"event-id\",\n\t\t\"prize-ids\",\n\t\t\"allow-state-change\",\n\t\t\"target\",\n\t]);\n\tconst eventId = getRequiredFlag(parsed, \"event-id\");\n\tconst prizeIds = parseIdList(\n\t\tgetRequiredFlag(parsed, \"prize-ids\"),\n\t\t\"prize-ids\",\n\t);\n\tassertStateChangeTarget(parsed, eventId);\n\tawait authenticate();\n\tassertPrizesBelongToEvent(await loadPrizes(eventId), prizeIds, eventId);\n\twriteSuccess(\n\t\truntime,\n\t\tawait api.event.luckyDraw.deleteLuckyDrawPrize.mutate({ prizeIds }),\n\t);\n};\n\nconst runPrizesReorder = async ({\n\tparsed,\n\truntime,\n\tauthenticate,\n}: LuckyDrawSetupContext) => {\n\tassertPositionalCount(parsed, 3);\n\tassertOnlyFlags(parsed, [\"event-id\", \"prize-ids\"]);\n\tconst eventId = getRequiredFlag(parsed, \"event-id\");\n\tconst prizeIds = parseIdList(\n\t\tgetRequiredFlag(parsed, \"prize-ids\"),\n\t\t\"prize-ids\",\n\t);\n\tawait authenticate();\n\tconst prizes = await loadPrizes(eventId);\n\tassertPrizesBelongToEvent(prizes, prizeIds, eventId);\n\tif (prizeIds.length !== prizes.length) {\n\t\tthrow new CliUsageError(\n\t\t\t`--prize-ids must list all ${prizes.length} active prizes in the new order.`,\n\t\t);\n\t}\n\tconst namesById = new Map(prizes.map((prize) => [prize.id, prize.name]));\n\twriteSuccess(\n\t\truntime,\n\t\tawait api.event.luckyDraw.updateLuckyDrawPrizesOrder.mutate({\n\t\t\teventId,\n\t\t\tprizes: prizeIds.map((id, order) => ({\n\t\t\t\tid,\n\t\t\t\torder,\n\t\t\t\tname: namesById.get(id) ?? \"\",\n\t\t\t})),\n\t\t}),\n\t);\n};\n\nconst LUCKY_DRAW_SETUP_HANDLERS = new Map<\n\tstring,\n\t(context: LuckyDrawSetupContext) => Promise<void>\n>([\n\t[\"config get\", runConfigGet],\n\t[\"config update\", runConfigUpdate],\n\t[\"background upload\", runBackgroundUpload],\n\t[\"background clear\", runBackgroundClear],\n\t[\"prizes list\", runPrizesList],\n\t[\"prizes create\", runPrizesCreate],\n\t[\"prizes update\", runPrizesUpdate],\n\t[\"prizes delete\", runPrizesDelete],\n\t[\"prizes reorder\", runPrizesReorder],\n]);\n\nexport const runLuckyDrawSetupCommand = async (input: {\n\tparsed: ParsedArguments;\n\truntime: CliRuntime;\n\tauthenticate: () => Promise<void>;\n}): Promise<boolean> => {\n\tconst { parsed, runtime, authenticate } = input;\n\tconst [, action, subAction] = parsed.positionals;\n\tconst handler = LUCKY_DRAW_SETUP_HANDLERS.get(`${action} ${subAction}`);\n\tif (!handler) return false;\n\tawait handler({ parsed, runtime, authenticate });\n\treturn true;\n};\n", "/** Wheel / slot label mode for `LuckyDraw.config` JSON (not the legacy `LuckyDrawConfig.wheelSegmentText` column). */\nexport const LuckyDrawSegmentText = {\n\tNAME: \"NAME\",\n\tLUCKY_DRAW_ID: \"LUCKY_DRAW_ID\",\n\tBOTH: \"BOTH\",\n} as const;\n\nexport type LuckyDrawSegmentText =\n\t(typeof LuckyDrawSegmentText)[keyof typeof LuckyDrawSegmentText];\n\n/** Wheel vs slot counter UI for `LuckyDraw.config` JSON (not the Prisma `LuckyDrawType` enum). */\nexport const LuckyDrawType = {\n\tWHEEL: \"WHEEL\",\n\tSLOT: \"SLOT\",\n} as const;\n\nexport type LuckyDrawType = (typeof LuckyDrawType)[keyof typeof LuckyDrawType];\n", "import {\n\tLuckyDrawSegmentText,\n\tLuckyDrawType,\n} from \"@go-labs/event-tech-db/lucky-draw-config-json\";\nimport { z } from \"zod\";\n\nexport const luckyDrawConfigSchema = z.object({\n\ttitle: z.string(),\n\ttitleColor: z.string(),\n\tisTitleVisible: z.boolean(),\n\ttitleFontSize: z.number(),\n\tprizeColor: z.string(),\n\tprizeFontSize: z.number(),\n\tisPrizeVisible: z.boolean(),\n\tslotBackgroundColor: z.string(),\n\tslotBorderColor: z.string(),\n\tslotTextColor: z.string(),\n\tslotFontSize: z.number(),\n\twheelSegmentColorsPreset: z.string(),\n\tbackgroundPreset: z.string(),\n\tnumberOfSegments: z.number(),\n\tincludeDomains: z.array(z.string()),\n\texcludeDomains: z.array(z.string()),\n\tincludeEmails: z.array(z.string()),\n\texcludeEmails: z.array(z.string()),\n\tsegmentPreset: z.string(),\n\tsegmentText: z.enum([\n\t\tLuckyDrawSegmentText.NAME,\n\t\tLuckyDrawSegmentText.LUCKY_DRAW_ID,\n\t\tLuckyDrawSegmentText.BOTH,\n\t]),\n\tluckyDrawType: z.enum([LuckyDrawType.WHEEL, LuckyDrawType.SLOT]),\n\ttitleFont: z.string(),\n\tprizeFont: z.string(),\n\t/** Wheel segment label font (canvas); stored as Tailwind font class token. */\n\twheelSegmentFont: z.string(),\n\t/** Wheel segment text size passed to react-custom-roulette (canvas `fontSize` base). */\n\twheelSegmentFontSize: z.number(),\n\t/** Slot counter / rolling text font; stored as Tailwind font class token. */\n\tslotTextFont: z.string(),\n\tcustomBackgroundImage: z.string().optional().nullable(),\n\ttitlePositionX: z.number(),\n\ttitlePositionY: z.number(),\n\tslotPositionX: z.number(),\n\tslotPositionY: z.number(),\n\tprizePositionX: z.number(),\n\tprizePositionY: z.number(),\n\tprizeDivWidth: z.number(),\n\tprizeDivHeight: z.number(),\n});\n\nexport type LuckyDrawConfig = z.infer<typeof luckyDrawConfigSchema>;\n", "import {\n\tLuckyDrawSegmentText,\n\tLuckyDrawType,\n} from \"@go-labs/event-tech-db/lucky-draw-config-json\";\nimport {\n\ttype LuckyDrawConfig,\n\tluckyDrawConfigSchema,\n} from \"@go-labs/event-tech-validators/lucky-draw/lucky-draw-config.schema\";\nimport { z } from \"zod\";\n\n// Server schema - only accepts string (Files must be uploaded before reaching server)\nexport const luckyDrawConfigInputProcedureSchema = z.object({\n\teventId: z.string(),\n\tconfig: luckyDrawConfigSchema,\n});\n\nexport type LuckyDrawConfigProcedureInput = z.infer<\n\ttypeof luckyDrawConfigInputProcedureSchema\n>;\n\n// Client schema - accepts File | string for frontend validation\nexport const luckyDrawConfigInputSchema = z.object({\n\t...luckyDrawConfigSchema.omit({ customBackgroundImage: true }).shape,\n\tcustomBackgroundImage: z\n\t\t.union([z.instanceof(File), z.string()])\n\t\t.optional()\n\t\t.nullable(),\n});\n\nexport type LuckyDrawConfigInput = z.infer<typeof luckyDrawConfigInputSchema>;\n\nexport const DEFAULT_LUCKY_DRAW_CONFIG_INPUT_VALUES: LuckyDrawConfig = {\n\t// use hex values to pass ColorPicker instead of color variables\n\ttitle: \"Lucky Draw Title\",\n\ttitleColor: \"#111111\", // foreground\n\tisTitleVisible: true,\n\ttitleFontSize: 40,\n\tprizeColor: \"#111111\", // foreground\n\tprizeFontSize: 30,\n\tisPrizeVisible: true,\n\tslotBackgroundColor: \"#ffffff\", // background\n\tslotBorderColor: \"#ffffff\", // background\n\tslotTextColor: \"#111111\", // foreground\n\tslotFontSize: 5,\n\tbackgroundPreset: \"#ede9fe\", // secondary\n\tnumberOfSegments: 12,\n\tincludeDomains: [],\n\texcludeDomains: [],\n\tincludeEmails: [],\n\texcludeEmails: [],\n\tsegmentPreset: \"Vibrant\",\n\tsegmentText: LuckyDrawSegmentText.NAME,\n\tluckyDrawType: LuckyDrawType.WHEEL,\n\ttitleFont: \"font-sans\",\n\tprizeFont: \"font-sans\",\n\twheelSegmentFont: \"font-sans\",\n\twheelSegmentFontSize: 12,\n\tslotTextFont: \"font-sans\",\n\tcustomBackgroundImage: null,\n\ttitlePositionX: 750,\n\ttitlePositionY: 100,\n\tslotPositionX: 600,\n\tslotPositionY: 300,\n\tprizePositionX: 800,\n\tprizePositionY: 200,\n\tprizeDivWidth: 500,\n\tprizeDivHeight: 100,\n\twheelSegmentColorsPreset: \"Vibrant\",\n};\n", "import { z } from \"zod\";\n\nexport const luckyDrawPrizeInputSchema = z.object({\n\tname: z.string().min(1),\n\tdescription: z.string().optional(),\n});\n\nexport type LuckyDrawPrizeInput = z.input<typeof luckyDrawPrizeInputSchema>;\n\nexport const multipleLuckyDrawPrizeInputSchema = z.object({\n\teventId: z.string().min(1, \"EventID is required\"),\n\tprizes: z.array(luckyDrawPrizeInputSchema),\n});\n\nexport type MultipleLuckyDrawPrizeInput = z.input<\n\ttypeof multipleLuckyDrawPrizeInputSchema\n>;\n", "import { readFile } from \"node:fs/promises\";\nimport { basename } from \"node:path\";\nimport { readSpreadsheetTable } from \"@go-labs/event-tech-utils/lib/spreadsheet-table\";\nimport {\n\tPASSPORT_QUEUE_STATUS_STALE_MINUTES_MAX,\n\tPASSPORT_QUEUE_STATUS_STALE_MINUTES_MIN,\n\tPASSPORT_STAFF_ID_LABEL_MAX,\n\tPASSPORT_STATION_CATEGORIES,\n\ttype PassportQueueStatus,\n\tpassportCategoryLabelsInputSchema,\n\tpassportMenuItemsSchema,\n\tpassportRedemptionRequestIdSchema,\n\tpassportStationInfoInputSchema,\n\tredeemPassportPrizeSchema,\n\trenamePassportBingoSchema,\n} from \"@go-labs/event-tech-validators/event-passport/passport-input.schema\";\nimport {\n\tguessPassportRosterMapping,\n\tmapPassportRosterTable,\n\tPASSPORT_ROSTER_PAGE_MAX,\n\ttype PassportRosterColumnMapping,\n} from \"@go-labs/event-tech-validators/event-passport/passport-roster.schema\";\nimport {\n\tPASSPORT_STATION_RECIPIENTS_PAGE_MAX,\n\tsetPassportStationPasswordSchema,\n} from \"@go-labs/event-tech-validators/event-passport/passport-station-access.schema\";\nimport { api, type RouterInputs } from \"@go-labs-sg/event-tech/api-client\";\nimport { createPassportMediaOperation } from \"@go-labs-sg/event-tech/commands/passport-media\";\nimport {\n\ttype CliRuntime,\n\tCliUsageError,\n\twriteSuccess,\n} from \"@go-labs-sg/event-tech/runtime\";\n\ntype PassportInputs = RouterInputs[\"event\"][\"passport\"];\ntype Flags = ReadonlyMap<string, string | true>;\n\nconst flag = (flags: Flags, name: string, required = true) => {\n\tconst value = flags.get(name);\n\tif (value === true || (required && !value))\n\t\tthrow new CliUsageError(`--${name} requires a value.`);\n\treturn value;\n};\nconst requiredFlag = (flags: Flags, name: string) => {\n\tconst value = flag(flags, name);\n\tif (!value) throw new CliUsageError(`--${name} is required.`);\n\treturn value;\n};\nconst integer = (\n\tvalue: unknown,\n\tname: string,\n\tminimum = 0,\n\tmaximum = 2_147_483_647,\n) => {\n\tconst parsed =\n\t\ttypeof value === \"string\" && value.trim() !== \"\" ? Number(value) : value;\n\tif (\n\t\ttypeof parsed !== \"number\" ||\n\t\t!Number.isSafeInteger(parsed) ||\n\t\tparsed < minimum ||\n\t\tparsed > maximum\n\t) {\n\t\tthrow new CliUsageError(\n\t\t\t`${name} must be a whole number from ${minimum} to ${maximum}.`,\n\t\t);\n\t}\n\treturn parsed;\n};\nconst stationCategory = (value: unknown) => {\n\tconst match = PASSPORT_STATION_CATEGORIES.find(\n\t\t(category) => category === value,\n\t);\n\tif (!match)\n\t\tthrow new CliUsageError(\n\t\t\t`category must be ${PASSPORT_STATION_CATEGORIES.join(\", \")}.`,\n\t\t);\n\treturn match;\n};\nconst boolean = (value: unknown, name: string) => {\n\tif (value === true || value === \"true\") return true;\n\tif (value === false || value === \"false\") return false;\n\tthrow new CliUsageError(`${name} must be true or false.`);\n};\nconst text = (value: unknown, name: string, maximum: number) => {\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\t!value.trim() ||\n\t\tvalue.trim().length > maximum\n\t)\n\t\tthrow new CliUsageError(\n\t\t\t`${name} must be a non-empty string of at most ${maximum} characters.`,\n\t\t);\n\treturn value.trim();\n};\nconst nullableText = (value: unknown, name: string, maximum: number) => {\n\tif (value == null) return null;\n\tif (typeof value !== \"string\" || value.trim().length > maximum)\n\t\tthrow new CliUsageError(\n\t\t\t`${name} must be a string of at most ${maximum} characters or null.`,\n\t\t);\n\treturn value.trim();\n};\n/** Category names: the shared schema trims, caps names at 40 and drops blanks; null clears them all. */\nconst categoryLabels = (value: unknown) => {\n\tif (value === null) return null;\n\tconst parsed = passportCategoryLabelsInputSchema.safeParse(value);\n\tif (!parsed.success)\n\t\tthrow new CliUsageError(\n\t\t\t`categoryLabels is invalid: ${parsed.error.issues\n\t\t\t\t.map(\n\t\t\t\t\t(issue) =>\n\t\t\t\t\t\t`${issue.path.join(\".\") || \"categoryLabels\"} ${issue.message}`,\n\t\t\t\t)\n\t\t\t\t.join(\"; \")}`,\n\t\t);\n\treturn parsed.data;\n};\n/** Guest info: validated by the shared schema; null clears the stored info. */\nconst stationInfo = (value: unknown) => {\n\tconst parsed = passportStationInfoInputSchema.safeParse(value);\n\tif (!parsed.success)\n\t\tthrow new CliUsageError(\n\t\t\t`info is invalid: ${parsed.error.issues\n\t\t\t\t.map((issue) => `${issue.path.join(\".\") || \"info\"} ${issue.message}`)\n\t\t\t\t.join(\"; \")}`,\n\t\t);\n\treturn parsed.data;\n};\nconst object = (value: unknown, name: string): Record<string, unknown> => {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value))\n\t\tthrow new CliUsageError(`${name} must be an object.`);\n\treturn Object.fromEntries(Object.entries(value));\n};\nconst json = (value: string, name: string) => {\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(value);\n\t\treturn object(parsed, name);\n\t} catch (error) {\n\t\tif (error instanceof CliUsageError) throw error;\n\t\tthrow new CliUsageError(`${name} must be valid JSON.`);\n\t}\n};\nconst keys = (\n\tvalue: Record<string, unknown>,\n\tallowed: readonly string[],\n\tname: string,\n) => {\n\tif (Object.keys(value).some((key) => !allowed.includes(key)))\n\t\tthrow new CliUsageError(`${name} contains unsupported fields.`);\n};\nconst date = (value: unknown, name: string) => {\n\tif (value == null) return null;\n\tif (typeof value !== \"string\" || !/^\\d{4}-\\d\\d-\\d\\dT/.test(value))\n\t\tthrow new CliUsageError(`${name} must be an ISO date-time or null.`);\n\tconst parsed = new Date(value);\n\tif (Number.isNaN(parsed.getTime()))\n\t\tthrow new CliUsageError(`${name} must be a valid ISO date-time.`);\n\treturn parsed;\n};\n\ntype PassportCollection = NonNullable<\n\tPassportInputs[\"upsertPassportStation\"][\"collection\"]\n>;\n\nconst parseStaffTallyCollection = (\n\titem: Record<string, unknown>,\n\textras: {\n\t\tstampValue?: number;\n\t\tcategory?: string;\n\t\tinfo?: unknown;\n\t\tshowHowToCollect?: boolean;\n\t\tshowMyQr?: boolean;\n\t},\n): PassportCollection => {\n\tkeys(\n\t\titem,\n\t\t[\n\t\t\t\"collectionMode\",\n\t\t\t\"showHowToCollect\",\n\t\t\t\"showMyQr\",\n\t\t\t\"tallyItems\",\n\t\t\t\"tallyEarnsStamp\",\n\t\t\t\"stampValue\",\n\t\t\t\"category\",\n\t\t\t\"info\",\n\t\t],\n\t\t\"collection\",\n\t);\n\tif (!Array.isArray(item.tallyItems))\n\t\tthrow new CliUsageError(\"tallyItems must be an array of item names.\");\n\tif (item.tallyItems.length < 1 || item.tallyItems.length > 30)\n\t\tthrow new CliUsageError(\"tallyItems must have 1 to 30 items.\");\n\tconst tallyItems = item.tallyItems.map((name: unknown, index) =>\n\t\ttext(name, `tallyItems[${index}]`, 60),\n\t);\n\tif (\n\t\tnew Set(tallyItems.map((name) => name.toLocaleLowerCase())).size !==\n\t\ttallyItems.length\n\t)\n\t\tthrow new CliUsageError(\"tallyItems must be unique ignoring case.\");\n\tif (\n\t\titem.tallyEarnsStamp !== undefined &&\n\t\ttypeof item.tallyEarnsStamp !== \"boolean\"\n\t)\n\t\tthrow new CliUsageError(\"tallyEarnsStamp must be true or false.\");\n\treturn {\n\t\tcollectionMode: \"STAFF_TALLY\",\n\t\ttallyItems,\n\t\ttallyEarnsStamp: item.tallyEarnsStamp === true,\n\t\t...extras,\n\t} as PassportCollection;\n};\n\nconst parseStaffScanCollection = (\n\titem: Record<string, unknown>,\n\textras: {\n\t\tstampValue?: number;\n\t\tcategory?: string;\n\t\tinfo?: unknown;\n\t\tshowHowToCollect?: boolean;\n\t\tshowMyQr?: boolean;\n\t},\n): PassportCollection => {\n\tkeys(\n\t\titem,\n\t\t[\n\t\t\t\"collectionMode\",\n\t\t\t\"stampValue\",\n\t\t\t\"category\",\n\t\t\t\"prizeDeskAward\",\n\t\t\t\"showHowToCollect\",\n\t\t\t\"showMyQr\",\n\t\t\t\"collectionLimit\",\n\t\t\t\"menuItems\",\n\t\t\t\"info\",\n\t\t],\n\t\t\"collection\",\n\t);\n\tif (\n\t\titem.collectionMode !== \"STAFF_SCAN\" &&\n\t\t(item.menuItems !== undefined || item.collectionLimit !== undefined)\n\t)\n\t\tthrow new CliUsageError(\n\t\t\t\"Only STAFF_SCAN stations can configure menuItems or collectionLimit.\",\n\t\t);\n\tif (\n\t\titem.prizeDeskAward !== undefined &&\n\t\ttypeof item.prizeDeskAward !== \"boolean\"\n\t)\n\t\tthrow new CliUsageError(\"prizeDeskAward must be true or false.\");\n\tif (\n\t\titem.collectionLimit !== undefined &&\n\t\titem.collectionLimit !== \"ONCE\" &&\n\t\titem.collectionLimit !== \"UNLIMITED\"\n\t)\n\t\tthrow new CliUsageError(\"collectionLimit must be ONCE or UNLIMITED.\");\n\treturn {\n\t\tcollectionMode: item.collectionMode as \"SELF_SCAN\" | \"STAFF_SCAN\",\n\t\t...(item.collectionLimit === undefined\n\t\t\t? {}\n\t\t\t: { collectionLimit: item.collectionLimit }),\n\t\t...(item.menuItems === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tmenuItems:\n\t\t\t\t\t\titem.menuItems === null\n\t\t\t\t\t\t\t? null\n\t\t\t\t\t\t\t: parseStaffScanMenuItems(item.menuItems),\n\t\t\t\t}),\n\t\t...extras,\n\t\t...(item.prizeDeskAward === undefined\n\t\t\t? {}\n\t\t\t: { prizeDeskAward: item.prizeDeskAward }),\n\t} as PassportCollection;\n};\n\nconst parseStaffScanMenuItems = (value: unknown) => {\n\tif (!Array.isArray(value))\n\t\tthrow new CliUsageError(\"menuItems must be an array of menu item objects.\");\n\tif (value.length < 1 || value.length > 30)\n\t\tthrow new CliUsageError(\"menuItems must have 1 to 30 items.\");\n\tconst menuItems = value.map((raw, index) => {\n\t\tconst item = object(raw, `menuItems[${index}]`);\n\t\tkeys(item, [\"name\", \"stock\", \"siteStocks\"], `menuItems[${index}]`);\n\t\treturn {\n\t\t\tname: text(item.name, `menuItems[${index}].name`, 60),\n\t\t\t...(item.siteStocks === undefined ? {} : { siteStocks: item.siteStocks }),\n\t\t\tstock:\n\t\t\t\titem.stock === null\n\t\t\t\t\t? null\n\t\t\t\t\t: integer(item.stock, `menuItems[${index}].stock`),\n\t\t};\n\t});\n\tif (\n\t\tnew Set(menuItems.map(({ name }) => name.trim().toLocaleLowerCase()))\n\t\t\t.size !== menuItems.length\n\t)\n\t\tthrow new CliUsageError(\n\t\t\t\"menuItems names must be unique ignoring case and surrounding whitespace.\",\n\t\t);\n\tconst parsed = passportMenuItemsSchema.safeParse(menuItems);\n\tif (!parsed.success)\n\t\tthrow new CliUsageError(\n\t\t\t`menuItems is invalid: ${parsed.error.issues.map((issue) => `${issue.path.join(\".\")} ${issue.message}`).join(\"; \")}`,\n\t\t);\n\treturn parsed.data;\n};\n\nconst parsePassportCollection = (raw: unknown): PassportCollection => {\n\tconst item = object(raw, \"collection\");\n\t// stampValue (0..1000) is the stamps a station awards; omit to keep it.\n\tconst stampValue =\n\t\titem.stampValue === undefined\n\t\t\t? {}\n\t\t\t: { stampValue: integer(item.stampValue, \"stampValue\", 0, 1000) };\n\t// category groups stations for guests; omit to keep it (GAME when unset).\n\tconst category =\n\t\titem.category === undefined\n\t\t\t? {}\n\t\t\t: { category: stationCategory(item.category) };\n\t// info is the guest-facing station information; omit to keep, null clears.\n\tconst info = {\n\t\t...(item.showMyQr === undefined\n\t\t\t? {}\n\t\t\t: { showMyQr: boolean(item.showMyQr, \"showMyQr\") }),\n\t\t...(item.info === undefined ? {} : { info: stationInfo(item.info) }),\n\t\t...(item.showHowToCollect === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tshowHowToCollect: boolean(item.showHowToCollect, \"showHowToCollect\"),\n\t\t\t\t}),\n\t};\n\tif (item.collectionMode === \"STAFF_SCORE\") {\n\t\tkeys(\n\t\t\titem,\n\t\t\t[\n\t\t\t\t\"collectionMode\",\n\t\t\t\t\"maxPoints\",\n\t\t\t\t\"stampValue\",\n\t\t\t\t\"category\",\n\t\t\t\t\"info\",\n\t\t\t\t\"showHowToCollect\",\n\t\t\t\t\"showMyQr\",\n\t\t\t],\n\t\t\t\"collection\",\n\t\t);\n\t\treturn {\n\t\t\tcollectionMode: \"STAFF_SCORE\",\n\t\t\tmaxPoints: integer(item.maxPoints, \"maxPoints\"),\n\t\t\t...stampValue,\n\t\t\t...category,\n\t\t\t...info,\n\t\t};\n\t}\n\tif (item.collectionMode === \"STAFF_TALLY\") {\n\t\treturn parseStaffTallyCollection(item, {\n\t\t\t...stampValue,\n\t\t\t...category,\n\t\t\t...info,\n\t\t});\n\t}\n\tif (\n\t\titem.collectionMode === \"SELF_SCAN\" ||\n\t\titem.collectionMode === \"STAFF_SCAN\"\n\t) {\n\t\treturn parseStaffScanCollection(item, {\n\t\t\t...stampValue,\n\t\t\t...category,\n\t\t\t...info,\n\t\t});\n\t}\n\tthrow new CliUsageError(\n\t\t\"collectionMode must be SELF_SCAN, STAFF_SCAN, STAFF_SCORE or STAFF_TALLY.\",\n\t);\n};\n\nexport const parsePassportStationInput = (\n\traw: string,\n\teventId: string,\n): PassportInputs[\"upsertPassportStation\"] => {\n\tconst value = json(raw, \"--station-json\");\n\tkeys(\n\t\tvalue,\n\t\t[\n\t\t\t\"id\",\n\t\t\t\"name\",\n\t\t\t\"description\",\n\t\t\t\"location\",\n\t\t\t\"address\",\n\t\t\t\"imageKey\",\n\t\t\t\"order\",\n\t\t\t\"opensAt\",\n\t\t\t\"closesAt\",\n\t\t\t\"collection\",\n\t\t],\n\t\t\"Station\",\n\t);\n\tconst collection =\n\t\tvalue.collection === undefined\n\t\t\t? undefined\n\t\t\t: parsePassportCollection(value.collection);\n\treturn {\n\t\teventId,\n\t\t...(value.id === undefined ? {} : { id: text(value.id, \"id\", 200) }),\n\t\tname: text(value.name, \"name\", 100),\n\t\tdescription: nullableText(value.description, \"description\", 1000),\n\t\tlocation: nullableText(value.location, \"location\", 200),\n\t\t...(value.address === undefined\n\t\t\t? {}\n\t\t\t: { address: nullableText(value.address, \"address\", 300) }),\n\t\t// Omitted keeps the stored cover art; null clears it.\n\t\t...(value.imageKey === undefined\n\t\t\t? {}\n\t\t\t: { imageKey: nullableText(value.imageKey, \"imageKey\", 2048) }),\n\t\torder: integer(value.order ?? 0, \"order\"),\n\t\topensAt: date(value.opensAt, \"opensAt\"),\n\t\tclosesAt: date(value.closesAt, \"closesAt\"),\n\t\t...(collection ? { collection } : {}),\n\t};\n};\n\n/** The `--status` words for a station queue wait, and the stored value each means. */\nconst QUEUE_STATUS_FLAGS: Readonly<Record<string, PassportQueueStatus | null>> =\n\t{\n\t\t\"under-10\": \"UNDER_10_MIN\",\n\t\t\"under-30\": \"UNDER_30_MIN\",\n\t\t\"over-30\": \"OVER_30_MIN\",\n\t\tclear: null,\n\t};\n\nconst queueStatusFlag = (value: string) => {\n\tconst status = QUEUE_STATUS_FLAGS[value];\n\tif (status === undefined)\n\t\tthrow new CliUsageError(\n\t\t\t`--status must be one of ${Object.keys(QUEUE_STATUS_FLAGS).join(\", \")}.`,\n\t\t);\n\treturn status;\n};\n\n/**\n * Optional settings switches, the identifier label, the category names and\n * the queue status settings; an omitted one keeps the stored value. A null or\n * blank staffIdLabel, null categoryLabels, or a null queueStatusStaleMinutes,\n * resets it to the default.\n */\nconst parseSettingsSwitches = (value: Record<string, unknown>) => {\n\tconst switches: {\n\t\tguestScan?: boolean;\n\t\tsimplifiedChinese?: boolean;\n\t\tstaffIdLabel?: string | null;\n\t\tcategoryLabels?: ReturnType<typeof categoryLabels>;\n\t\tqueueStatus?: boolean;\n\t\tqueueStatusStaleMinutes?: number | null;\n\t} = {};\n\tif (value.queueStatusStaleMinutes !== undefined)\n\t\tswitches.queueStatusStaleMinutes =\n\t\t\tvalue.queueStatusStaleMinutes === null\n\t\t\t\t? null\n\t\t\t\t: integer(\n\t\t\t\t\t\tvalue.queueStatusStaleMinutes,\n\t\t\t\t\t\t\"queueStatusStaleMinutes\",\n\t\t\t\t\t\tPASSPORT_QUEUE_STATUS_STALE_MINUTES_MIN,\n\t\t\t\t\t\tPASSPORT_QUEUE_STATUS_STALE_MINUTES_MAX,\n\t\t\t\t\t);\n\tif (value.staffIdLabel !== undefined)\n\t\tswitches.staffIdLabel = nullableText(\n\t\t\tvalue.staffIdLabel,\n\t\t\t\"staffIdLabel\",\n\t\t\tPASSPORT_STAFF_ID_LABEL_MAX,\n\t\t);\n\tif (value.categoryLabels !== undefined)\n\t\tswitches.categoryLabels = categoryLabels(value.categoryLabels);\n\tfor (const name of [\n\t\t\"guestScan\",\n\t\t\"simplifiedChinese\",\n\t\t\"queueStatus\",\n\t] as const) {\n\t\tconst item = value[name];\n\t\tif (item === undefined) continue;\n\t\tif (typeof item !== \"boolean\")\n\t\t\tthrow new CliUsageError(`${name} must be a JSON boolean.`);\n\t\tswitches[name] = item;\n\t}\n\treturn switches;\n};\n\nexport const parsePassportSettingsInput = (\n\traw: string,\n\teventId: string,\n): PassportInputs[\"updatePassportSettings\"] => {\n\tconst value = json(raw, \"--settings-json\");\n\tkeys(\n\t\tvalue,\n\t\t[\n\t\t\t\"luckyDrawStampThreshold\",\n\t\t\t\"prizeStampThreshold\",\n\t\t\t\"maxRedemptionsPerParticipant\",\n\t\t\t\"linkedDrawEventId\",\n\t\t\t\"loginMethods\",\n\t\t\t\"guestScan\",\n\t\t\t\"simplifiedChinese\",\n\t\t\t\"staffIdLabel\",\n\t\t\t\"categoryLabels\",\n\t\t\t\"queueStatus\",\n\t\t\t\"queueStatusStaleMinutes\",\n\t\t],\n\t\t\"Settings\",\n\t);\n\tconst switches = parseSettingsSwitches(value);\n\tconst threshold = (item: unknown, name: string) =>\n\t\titem === null ? null : integer(item, name, 1);\n\tlet loginMethods: PassportInputs[\"updatePassportSettings\"][\"loginMethods\"];\n\tif (value.loginMethods !== undefined) {\n\t\tconst methods = object(value.loginMethods, \"loginMethods\");\n\t\tkeys(\n\t\t\tmethods,\n\t\t\t[\"emailOtp\", \"google\", \"guest\", \"staffId\", \"staffIdRequiresLastName\"],\n\t\t\t\"loginMethods\",\n\t\t);\n\t\tif (\n\t\t\ttypeof methods.emailOtp !== \"boolean\" ||\n\t\t\ttypeof methods.google !== \"boolean\" ||\n\t\t\ttypeof methods.guest !== \"boolean\" ||\n\t\t\t(methods.staffId !== undefined && typeof methods.staffId !== \"boolean\") ||\n\t\t\t(methods.staffIdRequiresLastName !== undefined &&\n\t\t\t\ttypeof methods.staffIdRequiresLastName !== \"boolean\")\n\t\t)\n\t\t\tthrow new CliUsageError(\"loginMethods values must be JSON booleans.\");\n\t\tloginMethods = {\n\t\t\temailOtp: methods.emailOtp,\n\t\t\tgoogle: methods.google,\n\t\t\tguest: methods.guest,\n\t\t\tstaffId: methods.staffId === true,\n\t\t\tstaffIdRequiresLastName: methods.staffIdRequiresLastName !== false,\n\t\t};\n\t\tif (!loginMethods.emailOtp && !loginMethods.google && !loginMethods.staffId)\n\t\t\tthrow new CliUsageError(\n\t\t\t\t\"Keep email OTP, Google or roster sign-in available for recovery.\",\n\t\t\t);\n\t}\n\tif (value.linkedDrawEventId === undefined)\n\t\tthrow new CliUsageError(\n\t\t\t\"linkedDrawEventId is required (use null to disable).\",\n\t\t);\n\treturn {\n\t\teventId,\n\t\tluckyDrawStampThreshold: threshold(\n\t\t\tvalue.luckyDrawStampThreshold,\n\t\t\t\"luckyDrawStampThreshold\",\n\t\t),\n\t\tprizeStampThreshold: threshold(\n\t\t\tvalue.prizeStampThreshold,\n\t\t\t\"prizeStampThreshold\",\n\t\t),\n\t\tmaxRedemptionsPerParticipant: integer(\n\t\t\tvalue.maxRedemptionsPerParticipant,\n\t\t\t\"maxRedemptionsPerParticipant\",\n\t\t\t0,\n\t\t),\n\t\tlinkedDrawEventId:\n\t\t\tvalue.linkedDrawEventId === null\n\t\t\t\t? null\n\t\t\t\t: text(value.linkedDrawEventId, \"linkedDrawEventId\", 200),\n\t\t...(loginMethods ? { loginMethods } : {}),\n\t\t...switches,\n\t};\n};\n\nexport const parsePassportRosterEntryInput = (\n\traw: string,\n\teventId: string,\n): PassportInputs[\"upsertPassportRosterEntry\"] => {\n\tconst value = json(raw, \"--entry-json\");\n\tkeys(value, [\"id\", \"staffId\", \"lastName\", \"displayName\"], \"Roster entry\");\n\tif (value.lastName === undefined)\n\t\tthrow new CliUsageError(\"lastName is required (use null for none).\");\n\treturn {\n\t\teventId,\n\t\t...(value.id === undefined ? {} : { id: text(value.id, \"id\", 200) }),\n\t\tstaffId: text(value.staffId, \"staffId\", 64),\n\t\tlastName: nullableText(value.lastName, \"lastName\", 100) || null,\n\t\tdisplayName: nullableText(value.displayName, \"displayName\", 100) || null,\n\t};\n};\n\n/** Finds a header by exact text, ignoring case and surrounding spaces. */\nconst headerIndex = (headers: readonly string[], name: string) => {\n\tconst wanted = name.trim().toLowerCase();\n\tconst index = headers.findIndex(\n\t\t(header) => header.trim().toLowerCase() === wanted,\n\t);\n\tif (index === -1)\n\t\tthrow new CliUsageError(\n\t\t\t`Column \"${name}\" is not in the file. Headers: ${headers.join(\", \")}.`,\n\t\t);\n\treturn index;\n};\n\n/** Column flags override the header guess; \"none\" clears an optional column. */\nexport const resolvePassportRosterMapping = (\n\theaders: readonly string[],\n\tflags: Flags,\n\trequireLastName: boolean,\n): PassportRosterColumnMapping => {\n\tconst guess = guessPassportRosterMapping(headers);\n\tconst column = (name: string, fallback: number | null) => {\n\t\tconst value = flag(flags, name, false);\n\t\tif (value === undefined) return fallback;\n\t\treturn value.trim().toLowerCase() === \"none\"\n\t\t\t? null\n\t\t\t: headerIndex(headers, value);\n\t};\n\tconst staffIdFlag = flag(flags, \"staff-id-column\", false);\n\tconst position = flag(flags, \"surname-position\", false) ?? \"last\";\n\tif (position !== \"last\" && position !== \"first\")\n\t\tthrow new CliUsageError(\"--surname-position must be last or first.\");\n\tconst mapping: PassportRosterColumnMapping = {\n\t\tstaffId:\n\t\t\tstaffIdFlag === undefined\n\t\t\t\t? guess.staffId\n\t\t\t\t: headerIndex(headers, staffIdFlag),\n\t\tlastName: column(\"last-name-column\", guess.lastName),\n\t\tfullName: column(\"full-name-column\", guess.fullName),\n\t\tdisplayName: column(\"display-name-column\", guess.displayName),\n\t\tsurnamePosition: position,\n\t};\n\tif (requireLastName && mapping.lastName === null && mapping.fullName === null)\n\t\tthrow new CliUsageError(\n\t\t\t\"Map a last-name column (--last-name-column) or a full-name column (--full-name-column).\",\n\t\t);\n\treturn mapping;\n};\n\nconst readRosterRows = async (\n\tpath: string,\n\tflags: Flags,\n\trequireLastName: boolean,\n) => {\n\tlet table: string[][];\n\ttry {\n\t\ttable = await readSpreadsheetTable(basename(path), await readFile(path));\n\t} catch (error) {\n\t\tthrow new CliUsageError(\n\t\t\t`Could not read ${path}: ${error instanceof Error ? error.message : \"unknown error\"}`,\n\t\t);\n\t}\n\tconst mapping = resolvePassportRosterMapping(\n\t\ttable[0] ?? [],\n\t\tflags,\n\t\trequireLastName,\n\t);\n\t// Mapping and row-limit errors stop the import before the roster request is sent.\n\ttry {\n\t\treturn mapPassportRosterTable(table, mapping, { requireLastName });\n\t} catch (error) {\n\t\tthrow new CliUsageError(\n\t\t\t`Could not import ${path}: ${error instanceof Error ? error.message : \"unknown error\"}`,\n\t\t);\n\t}\n};\n\n/** `{}` when the value is absent, otherwise `{ [key]: parse(value) }` (parse runs at the call site's position). */\nconst optionalEntry = <Key extends string, Value>(\n\tkey: Key,\n\tvalue: unknown,\n\tparse: (raw: unknown) => Value,\n): { [Property in Key]?: Value } =>\n\tvalue === undefined\n\t\t? {}\n\t\t: ({ [key]: parse(value) } as { [Property in Key]?: Value });\n\n/** Reads the whole of stdin, dropping the single trailing newline that `echo` or a heredoc adds. */\nconst readPasswordFromStdin = async () => {\n\tif (process.stdin.isTTY)\n\t\tthrow new CliUsageError(\n\t\t\t\"--password-stdin reads the password from stdin. Pipe it in, for example: printf '%s' \\\"$PASSWORD\\\" | et passport station-access set-password --event-id <id> --password-stdin ...\",\n\t\t);\n\treturn (await Bun.stdin.text()).replace(/\\r?\\n$/, \"\");\n};\n\nconst searchFilters = (flags: Flags) => {\n\tconst search = flag(flags, \"search\", false);\n\treturn search === undefined ? {} : { search: text(search, \"--search\", 200) };\n};\n\nconst recipientDirection = (\n\tvalue: string | undefined,\n): \"forward\" | \"backward\" | undefined => {\n\tif (value === undefined) return undefined;\n\tif (value === \"forward\" || value === \"backward\") return value;\n\tthrow new CliUsageError(\"--direction must be forward or backward.\");\n};\n\nconst parseStampRecipientsInput = (\n\tflags: Flags,\n\tstation: { eventId: string; stationId: string },\n) => {\n\tconst limit = flag(flags, \"limit\", false);\n\tconst cursor = flag(flags, \"cursor\", false);\n\tconst direction = recipientDirection(flag(flags, \"direction\", false));\n\tif (direction === \"backward\" && cursor === undefined)\n\t\tthrow new CliUsageError(\"--direction backward needs --cursor.\");\n\treturn {\n\t\t...station,\n\t\tfilters: searchFilters(flags),\n\t\t...optionalEntry(\"limit\", limit, (raw) =>\n\t\t\tinteger(raw, \"--limit\", 1, PASSPORT_STATION_RECIPIENTS_PAGE_MAX),\n\t\t),\n\t\t...optionalEntry(\"cursor\", cursor, (raw) => text(raw, \"--cursor\", 8192)),\n\t\t...(direction === undefined ? {} : { direction }),\n\t};\n};\n\ntype StationOperationContext = {\n\teventId: string;\n\tflags: Flags;\n\tallowed: string[];\n\tstation: () => { eventId: string; stationId: string };\n\tconfirm: () => void;\n};\n\n/** Station link password and stamp-report commands; undefined when the action is not one of them. */\nconst createStationAccessOperation = async (\n\taction: string,\n\t{ eventId, flags, allowed, station, confirm }: StationOperationContext,\n): Promise<(() => Promise<unknown>) | undefined> => {\n\tconst event = { eventId };\n\tlet operation: (() => Promise<unknown>) | undefined;\n\tswitch (action) {\n\t\tcase \"station-access get\":\n\t\t\toperation = () =>\n\t\t\t\tapi.event.passport.getPassportStationAccess.query(event);\n\t\t\tbreak;\n\t\tcase \"station-access set-password\": {\n\t\t\tallowed.push(\"password-stdin\");\n\t\t\tconfirm();\n\t\t\tif (flags.get(\"password-stdin\") !== true)\n\t\t\t\tthrow new CliUsageError(\n\t\t\t\t\t\"--password-stdin is required; the password is never accepted as a flag value.\",\n\t\t\t\t);\n\t\t\tconst parsed = setPassportStationPasswordSchema.safeParse({\n\t\t\t\teventId,\n\t\t\t\tpassword: await readPasswordFromStdin(),\n\t\t\t});\n\t\t\tif (!parsed.success)\n\t\t\t\tthrow new CliUsageError(\n\t\t\t\t\tparsed.error.issues[0]?.message ?? \"The password is invalid.\",\n\t\t\t\t);\n\t\t\toperation = () =>\n\t\t\t\tapi.event.passport.setPassportStationPassword.mutate(parsed.data);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"station-access clear-password\":\n\t\t\tconfirm();\n\t\t\toperation = () =>\n\t\t\t\tapi.event.passport.clearPassportStationPassword.mutate(event);\n\t\t\tbreak;\n\t\tcase \"stamps stats\":\n\t\t\toperation = () =>\n\t\t\t\tapi.event.passport.getPassportStationStampStats.query(event);\n\t\t\tbreak;\n\t\tcase \"stamps recipients\": {\n\t\t\tallowed.push(\"station-id\", \"search\", \"limit\", \"cursor\", \"direction\");\n\t\t\tconst payload = parseStampRecipientsInput(flags, station());\n\t\t\toperation = () =>\n\t\t\t\tapi.event.passport.getPassportStationStampRecipients.query(payload);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"stamps recipient-counts\": {\n\t\t\tallowed.push(\"station-id\", \"search\");\n\t\t\tconst payload = { ...station(), filters: searchFilters(flags) };\n\t\t\toperation = () =>\n\t\t\t\tapi.event.passport.getPassportStationStampRecipientCounts.query(\n\t\t\t\t\tpayload,\n\t\t\t\t);\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn operation;\n};\n\nexport const runPassportCommand = async (input: {\n\tpositionals: readonly string[];\n\tflags: Flags;\n\truntime: CliRuntime;\n\tauthenticate: () => Promise<void>;\n}) => {\n\tconst { flags, positionals } = input;\n\tconst action = positionals.slice(1).join(\" \");\n\tconst allowed = [\"event-id\"];\n\tconst eventId = requiredFlag(flags, \"event-id\");\n\tconst event = { eventId };\n\tconst station = () => ({\n\t\teventId,\n\t\tstationId: requiredFlag(flags, \"station-id\"),\n\t});\n\tconst version = () =>\n\t\tinteger(\n\t\t\trequiredFlag(flags, \"expected-printed-qr-version\"),\n\t\t\t\"--expected-printed-qr-version\",\n\t\t);\n\tconst confirm = () => {\n\t\tallowed.push(\"allow-state-change\", \"target\");\n\t\tif (\n\t\t\tflags.get(\"allow-state-change\") !== true ||\n\t\t\trequiredFlag(flags, \"target\") !== eventId\n\t\t)\n\t\t\tthrow new CliUsageError(\n\t\t\t\t\"This operation requires --allow-state-change and --target exactly equal to --event-id.\",\n\t\t\t);\n\t};\n\tlet operation: () => Promise<unknown>;\n\tswitch (action) {\n\t\tcase \"overview\":\n\t\t\toperation = () => api.event.passport.getPassportOverview.query(event);\n\t\t\tbreak;\n\t\tcase \"mine\":\n\t\t\toperation = () => api.event.passport.getMyPassport.query(event);\n\t\t\tbreak;\n\t\tcase \"menu-stock\": {\n\t\t\tallowed.push(\"station-id\", \"site\");\n\t\t\tconst stationId = flag(flags, \"station-id\", false);\n\t\t\tconst site = flag(flags, \"site\", false);\n\t\t\toperation = async () => {\n\t\t\t\tconst rows =\n\t\t\t\t\tstationId === undefined\n\t\t\t\t\t\t? await api.event.passport.getMyPassportMenuStock.query(event)\n\t\t\t\t\t\t: (\n\t\t\t\t\t\t\t\tawait api.event.passport.getPassportOverview.query(event)\n\t\t\t\t\t\t\t).stations\n\t\t\t\t\t\t\t\t.filter((row) => row.id === stationId)\n\t\t\t\t\t\t\t\t.map((row) => ({\n\t\t\t\t\t\t\t\t\tstationId: row.id,\n\t\t\t\t\t\t\t\t\tmenuStock: row.menuStock,\n\t\t\t\t\t\t\t\t}));\n\t\t\t\tif (stationId !== undefined && !rows.length)\n\t\t\t\t\tthrow new CliUsageError(\n\t\t\t\t\t\t\"No station with that ID exists in this passport.\",\n\t\t\t\t\t);\n\t\t\t\tif (site === undefined) return rows;\n\t\t\t\tconst selected = rows.flatMap((row) => {\n\t\t\t\t\tconst menuStock = row.menuStock.flatMap((item) => {\n\t\t\t\t\t\tconst stock = item.siteStocks?.find(\n\t\t\t\t\t\t\t(value) =>\n\t\t\t\t\t\t\t\tvalue.site.toLocaleLowerCase() ===\n\t\t\t\t\t\t\t\tsite.trim().toLocaleLowerCase(),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn stock\n\t\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t...item,\n\t\t\t\t\t\t\t\t\t\tstock: stock.stock,\n\t\t\t\t\t\t\t\t\t\tremainingStock: stock.remainingStock,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t: [];\n\t\t\t\t\t});\n\t\t\t\t\treturn menuStock.length ? [{ ...row, site, menuStock }] : [];\n\t\t\t\t});\n\t\t\t\tif (!selected.length)\n\t\t\t\t\tthrow new CliUsageError(\"No menu stock is configured for that site.\");\n\t\t\t\treturn selected;\n\t\t\t};\n\t\t\tbreak;\n\t\t}\n\t\tcase \"bingo enable\":\n\t\t\toperation = () => api.event.passport.enablePassportBingo.mutate(event);\n\t\t\tbreak;\n\t\tcase \"bingo join\":\n\t\t\toperation = () => api.event.passport.joinPassportBingo.mutate(event);\n\t\t\tbreak;\n\t\tcase \"bingo claim-stamp\":\n\t\t\toperation = () =>\n\t\t\t\tapi.event.passport.claimPassportBingoStamp.mutate(event);\n\t\t\tbreak;\n\t\tcase \"bingo status\":\n\t\t\toperation = () => api.event.passport.getMyPassportBingo.query(event);\n\t\t\tbreak;\n\t\tcase \"bingo rename\": {\n\t\t\tallowed.push(\"name\");\n\t\t\tconst parsed = renamePassportBingoSchema.safeParse({\n\t\t\t\teventId,\n\t\t\t\tname: requiredFlag(flags, \"name\"),\n\t\t\t});\n\t\t\tif (!parsed.success)\n\t\t\t\tthrow new CliUsageError(\n\t\t\t\t\t`--name ${parsed.error.issues[0]?.message ?? \"is invalid\"}.`,\n\t\t\t\t);\n\t\t\toperation = () =>\n\t\t\t\tapi.event.passport.renamePassportBingo.mutate(parsed.data);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"login-options\":\n\t\t\toperation = () => api.event.passport.getPassportLoginOptions.query(event);\n\t\t\tbreak;\n\t\tcase \"queue-status\":\n\t\t\toperation = () =>\n\t\t\t\tapi.event.passport.getPassportQueueStatuses.query(event);\n\t\t\tbreak;\n\t\tcase \"export\":\n\t\t\toperation = () => api.event.passport.getPassportExportData.query(event);\n\t\t\tbreak;\n\t\tcase \"settings update\": {\n\t\t\tallowed.push(\"settings-json\");\n\t\t\tconst payload = parsePassportSettingsInput(\n\t\t\t\trequiredFlag(flags, \"settings-json\"),\n\t\t\t\teventId,\n\t\t\t);\n\t\t\toperation = () =>\n\t\t\t\tapi.event.passport.updatePassportSettings.mutate(payload);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"station upsert\": {\n\t\t\tallowed.push(\"station-json\");\n\t\t\tconst payload = parsePassportStationInput(\n\t\t\t\trequiredFlag(flags, \"station-json\"),\n\t\t\t\teventId,\n\t\t\t);\n\t\t\toperation = () =>\n\t\t\t\tapi.event.passport.upsertPassportStation.mutate(payload);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"station print-get\": {\n\t\t\tallowed.push(\"station-id\");\n\t\t\tconst payload = station();\n\t\t\toperation = () => api.event.passport.getStationPrintQr.query(payload);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"station print-issue\":\n\t\tcase \"station print-revoke\": {\n\t\t\tallowed.push(\"station-id\", \"expected-printed-qr-version\");\n\t\t\tconst payload = { ...station(), expectedPrintedQrVersion: version() };\n\t\t\tif (action === \"station print-revoke\") confirm();\n\t\t\toperation =\n\t\t\t\taction === \"station print-issue\"\n\t\t\t\t\t? () => api.event.passport.issueStationPrintQr.mutate(payload)\n\t\t\t\t\t: () => api.event.passport.revokeStationPrintQr.mutate(payload);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"station archive\": {\n\t\t\tallowed.push(\"station-id\");\n\t\t\tconfirm();\n\t\t\tconst payload = station();\n\t\t\toperation = () =>\n\t\t\t\tapi.event.passport.archivePassportStation.mutate(payload);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"station hidden\": {\n\t\t\tallowed.push(\"station-id\", \"hidden\");\n\t\t\tconst payload = {\n\t\t\t\t...station(),\n\t\t\t\thidden: boolean(requiredFlag(flags, \"hidden\"), \"--hidden\"),\n\t\t\t};\n\t\t\toperation = () =>\n\t\t\t\tapi.event.passport.setPassportStationHidden.mutate(payload);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"station queue-status\": {\n\t\t\tallowed.push(\"station-id\", \"status\");\n\t\t\tconst payload = {\n\t\t\t\t...station(),\n\t\t\t\tstatus: queueStatusFlag(requiredFlag(flags, \"status\")),\n\t\t\t};\n\t\t\toperation = () =>\n\t\t\t\tapi.event.passport.setStationQueueStatusAsStationStaff.mutate(payload);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"station start-qr\": {\n\t\t\tallowed.push(\"station-id\");\n\t\t\tconst payload = station();\n\t\t\toperation = () => api.event.passport.startStationQr.mutate(payload);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"station qr-status\": {\n\t\t\tallowed.push(\"session-id\");\n\t\t\tconst payload = { eventId, sessionId: requiredFlag(flags, \"session-id\") };\n\t\t\toperation = () => api.event.passport.getStationQrStatus.query(payload);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"collect\": {\n\t\t\tallowed.push(\n\t\t\t\t\"station-id\",\n\t\t\t\t\"profile-code\",\n\t\t\t\t\"points\",\n\t\t\t\t\"item\",\n\t\t\t\t\"site\",\n\t\t\t\t\"request-id\",\n\t\t\t);\n\t\t\tconst points = flag(flags, \"points\", false);\n\t\t\tconst item = flag(flags, \"item\", false);\n\t\t\tconst payload = {\n\t\t\t\t...station(),\n\t\t\t\tprofileCode: requiredFlag(flags, \"profile-code\"),\n\t\t\t\t...optionalEntry(\"site\", flag(flags, \"site\", false), (raw) =>\n\t\t\t\t\ttext(raw, \"--site\", 60),\n\t\t\t\t),\n\t\t\t\t...optionalEntry(\n\t\t\t\t\t\"requestId\",\n\t\t\t\t\tflag(flags, \"request-id\", false),\n\t\t\t\t\t(raw) => {\n\t\t\t\t\t\tconst parsed = passportRedemptionRequestIdSchema.safeParse(raw);\n\t\t\t\t\t\tif (!parsed.success)\n\t\t\t\t\t\t\tthrow new CliUsageError(\"--request-id must be a UUID.\");\n\t\t\t\t\t\treturn parsed.data;\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t\t...optionalEntry(\"points\", points, (raw) => integer(raw, \"--points\")),\n\t\t\t\t...optionalEntry(\"item\", item, (raw) => text(raw, \"--item\", 60)),\n\t\t\t};\n\t\t\toperation = () =>\n\t\t\t\tapi.event.passport.collectPassportStampByStaff.mutate(payload);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"claim\": {\n\t\t\tallowed.push(\"code\");\n\t\t\tconst payload = { eventId, code: requiredFlag(flags, \"code\") };\n\t\t\toperation = () => api.event.passport.claimPassportStamp.mutate(payload);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"stamp correct\": {\n\t\t\tallowed.push(\n\t\t\t\t\"station-id\",\n\t\t\t\t\"participant-id\",\n\t\t\t\t\"stamped\",\n\t\t\t\t\"reason\",\n\t\t\t\t\"points\",\n\t\t\t\t\"item\",\n\t\t\t\t\"collection-id\",\n\t\t\t\t\"site\",\n\t\t\t);\n\t\t\tconfirm();\n\t\t\tconst points = flag(flags, \"points\", false);\n\t\t\tconst item = flag(flags, \"item\", false);\n\t\t\tconst payload = {\n\t\t\t\t...station(),\n\t\t\t\tparticipantId: requiredFlag(flags, \"participant-id\"),\n\t\t\t\t...optionalEntry(\n\t\t\t\t\t\"collectionId\",\n\t\t\t\t\tflag(flags, \"collection-id\", false),\n\t\t\t\t\t(raw) => text(raw, \"--collection-id\", 200),\n\t\t\t\t),\n\t\t\t\t...optionalEntry(\"site\", flag(flags, \"site\", false), (raw) =>\n\t\t\t\t\ttext(raw, \"--site\", 60),\n\t\t\t\t),\n\t\t\t\tstamped: boolean(requiredFlag(flags, \"stamped\"), \"--stamped\"),\n\t\t\t\treason: requiredFlag(flags, \"reason\"),\n\t\t\t\t...optionalEntry(\"points\", points, (raw) => integer(raw, \"--points\")),\n\t\t\t\t...optionalEntry(\"item\", item, (raw) => text(raw, \"--item\", 60)),\n\t\t\t};\n\t\t\toperation = () => api.event.passport.correctPassportStamp.mutate(payload);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"participant detail\": {\n\t\t\tallowed.push(\"participant-id\");\n\t\t\tconst payload = {\n\t\t\t\teventId,\n\t\t\t\tparticipantId: requiredFlag(flags, \"participant-id\"),\n\t\t\t};\n\t\t\toperation = () =>\n\t\t\t\tapi.event.passport.getPassportParticipantDetail.query(payload);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"participant search\": {\n\t\t\tallowed.push(\"query\");\n\t\t\tconst payload = { eventId, query: flag(flags, \"query\", false) ?? \"\" };\n\t\t\toperation = () =>\n\t\t\t\tapi.event.passport.searchPassportParticipants.query(payload);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"prize upsert\": {\n\t\t\tallowed.push(\"prize-json\");\n\t\t\tconst value = json(requiredFlag(flags, \"prize-json\"), \"--prize-json\");\n\t\t\tkeys(\n\t\t\t\tvalue,\n\t\t\t\t[\n\t\t\t\t\t\"id\",\n\t\t\t\t\t\"name\",\n\t\t\t\t\t\"description\",\n\t\t\t\t\t\"imageKey\",\n\t\t\t\t\t\"stock\",\n\t\t\t\t\t\"stampCost\",\n\t\t\t\t\t\"order\",\n\t\t\t\t],\n\t\t\t\t\"Prize\",\n\t\t\t);\n\t\t\tconst payload = {\n\t\t\t\teventId,\n\t\t\t\t...optionalEntry(\"id\", value.id, (raw) => text(raw, \"id\", 200)),\n\t\t\t\tname: text(value.name, \"name\", 100),\n\t\t\t\tdescription: nullableText(value.description, \"description\", 1000),\n\t\t\t\t// Omitted keeps the stored photo; null clears it.\n\t\t\t\t...optionalEntry(\"imageKey\", value.imageKey, (raw) =>\n\t\t\t\t\tnullableText(raw, \"imageKey\", 2048),\n\t\t\t\t),\n\t\t\t\tstock: integer(value.stock, \"stock\"),\n\t\t\t\t...optionalEntry(\"stampCost\", value.stampCost, (raw) =>\n\t\t\t\t\tinteger(raw, \"stampCost\", 0, 100_000),\n\t\t\t\t),\n\t\t\t\torder: integer(value.order ?? 0, \"order\"),\n\t\t\t};\n\t\t\toperation = () => api.event.passport.upsertPassportPrize.mutate(payload);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"prize archive\": {\n\t\t\tallowed.push(\"prize-id\");\n\t\t\tconfirm();\n\t\t\tconst payload = { eventId, prizeId: requiredFlag(flags, \"prize-id\") };\n\t\t\toperation = () => api.event.passport.archivePassportPrize.mutate(payload);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"redemption create\": {\n\t\t\tallowed.push(\n\t\t\t\t\"prize-id\",\n\t\t\t\t\"participant-id\",\n\t\t\t\t\"quantity\",\n\t\t\t\t\"award-station-id\",\n\t\t\t\t\"bonus-stamps\",\n\t\t\t\t\"request-id\",\n\t\t\t);\n\t\t\tconst quantity = flag(flags, \"quantity\", false);\n\t\t\tconst awardStationId = flag(flags, \"award-station-id\", false);\n\t\t\tconst bonusStamps = flag(flags, \"bonus-stamps\", false);\n\t\t\tconst requestId = flag(flags, \"request-id\", false);\n\t\t\tconst payload = {\n\t\t\t\teventId,\n\t\t\t\t...optionalEntry(\"quantity\", quantity, (raw) =>\n\t\t\t\t\tinteger(raw, \"--quantity\", 1, 20),\n\t\t\t\t),\n\t\t\t\t...optionalEntry(\"bonusStamps\", bonusStamps, (raw) => {\n\t\t\t\t\tconst value = integer(raw, \"--bonus-stamps\", 0, 1000);\n\t\t\t\t\treturn redeemPassportPrizeSchema.shape.bonusStamps.parse(value);\n\t\t\t\t}),\n\t\t\t\t// A prize-desk station whose stamp is also awarded; omitted awards none.\n\t\t\t\t...optionalEntry(\"awardStationId\", awardStationId, (raw) =>\n\t\t\t\t\ttext(raw, \"--award-station-id\", 200),\n\t\t\t\t),\n\t\t\t\t// Reuse the same id to retry safely: a repeat returns the first redemption.\n\t\t\t\t...optionalEntry(\"requestId\", requestId, (raw) => {\n\t\t\t\t\tconst parsed = passportRedemptionRequestIdSchema.safeParse(raw);\n\t\t\t\t\tif (!parsed.success)\n\t\t\t\t\t\tthrow new CliUsageError(\"--request-id must be a UUID.\");\n\t\t\t\t\treturn parsed.data;\n\t\t\t\t}),\n\t\t\t\tprizeId: requiredFlag(flags, \"prize-id\"),\n\t\t\t\tparticipantId: requiredFlag(flags, \"participant-id\"),\n\t\t\t};\n\t\t\toperation = () => api.event.passport.redeemPassportPrize.mutate(payload);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"redemption reverse\": {\n\t\t\tallowed.push(\"redemption-id\", \"reason\");\n\t\t\tconfirm();\n\t\t\tconst payload = {\n\t\t\t\teventId,\n\t\t\t\tredemptionId: requiredFlag(flags, \"redemption-id\"),\n\t\t\t\treason: requiredFlag(flags, \"reason\"),\n\t\t\t};\n\t\t\toperation = () =>\n\t\t\t\tapi.event.passport.reversePassportRedemption.mutate(payload);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"tally record\": {\n\t\t\tallowed.push(\"station-id\", \"profile-code\", \"item\", \"quantity\");\n\t\t\tconst quantity = flag(flags, \"quantity\", false);\n\t\t\tconst payload = {\n\t\t\t\t...station(),\n\t\t\t\tprofileCode: requiredFlag(flags, \"profile-code\"),\n\t\t\t\titem: requiredFlag(flags, \"item\"),\n\t\t\t\t...optionalEntry(\"quantity\", quantity, (raw) =>\n\t\t\t\t\tinteger(raw, \"--quantity\", 1, 20),\n\t\t\t\t),\n\t\t\t};\n\t\t\toperation = () => api.event.passport.recordPassportTally.mutate(payload);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"tally reverse\": {\n\t\t\tallowed.push(\"tally-id\", \"reason\");\n\t\t\tconfirm();\n\t\t\tconst payload = {\n\t\t\t\teventId,\n\t\t\t\ttallyId: requiredFlag(flags, \"tally-id\"),\n\t\t\t\treason: requiredFlag(flags, \"reason\"),\n\t\t\t};\n\t\t\toperation = () => api.event.passport.reversePassportTally.mutate(payload);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"roster list\": {\n\t\t\tallowed.push(\"search\", \"limit\", \"cursor\");\n\t\t\tconst search = flag(flags, \"search\", false);\n\t\t\tconst limit = flag(flags, \"limit\", false);\n\t\t\tconst cursor = flag(flags, \"cursor\", false);\n\t\t\tconst payload = {\n\t\t\t\teventId,\n\t\t\t\t...optionalEntry(\"search\", search, (raw) => text(raw, \"--search\", 200)),\n\t\t\t\t...optionalEntry(\"limit\", limit, (raw) =>\n\t\t\t\t\tinteger(raw, \"--limit\", 1, PASSPORT_ROSTER_PAGE_MAX),\n\t\t\t\t),\n\t\t\t\t...optionalEntry(\"cursor\", cursor, (raw) =>\n\t\t\t\t\ttext(raw, \"--cursor\", 8192),\n\t\t\t\t),\n\t\t\t};\n\t\t\toperation = () => api.event.passport.getPassportRoster.query(payload);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"roster counts\": {\n\t\t\tallowed.push(\"search\");\n\t\t\tconst search = flag(flags, \"search\", false);\n\t\t\tconst payload = {\n\t\t\t\teventId,\n\t\t\t\t...optionalEntry(\"search\", search, (raw) => text(raw, \"--search\", 200)),\n\t\t\t};\n\t\t\toperation = () =>\n\t\t\t\tapi.event.passport.getPassportRosterCounts.query(payload);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"roster upsert\": {\n\t\t\tallowed.push(\"entry-json\");\n\t\t\tconst payload = parsePassportRosterEntryInput(\n\t\t\t\trequiredFlag(flags, \"entry-json\"),\n\t\t\t\teventId,\n\t\t\t);\n\t\t\toperation = () =>\n\t\t\t\tapi.event.passport.upsertPassportRosterEntry.mutate(payload);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"roster remove\": {\n\t\t\tallowed.push(\"entry-id\");\n\t\t\tconfirm();\n\t\t\tconst payload = { eventId, entryId: requiredFlag(flags, \"entry-id\") };\n\t\t\toperation = () =>\n\t\t\t\tapi.event.passport.deletePassportRosterEntry.mutate(payload);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"roster purge\":\n\t\t\tconfirm();\n\t\t\toperation = () => api.event.passport.purgePassportRoster.mutate(event);\n\t\t\tbreak;\n\t\tcase \"roster import\": {\n\t\t\tallowed.push(\n\t\t\t\t\"file\",\n\t\t\t\t\"staff-id-column\",\n\t\t\t\t\"last-name-column\",\n\t\t\t\t\"full-name-column\",\n\t\t\t\t\"display-name-column\",\n\t\t\t\t\"surname-position\",\n\t\t\t);\n\t\t\tconst path = requiredFlag(flags, \"file\");\n\t\t\toperation = async () => {\n\t\t\t\tconst { loginMethods } =\n\t\t\t\t\tawait api.event.passport.getPassportLoginOptions.query(event);\n\t\t\t\treturn api.event.passport.importPassportRoster.mutate({\n\t\t\t\t\teventId,\n\t\t\t\t\trows: await readRosterRows(\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\tflags,\n\t\t\t\t\t\tloginMethods.staffIdRequiresLastName,\n\t\t\t\t\t),\n\t\t\t\t});\n\t\t\t};\n\t\t\tbreak;\n\t\t}\n\t\tcase \"tally summary\":\n\t\t\toperation = () => api.event.passport.getPassportTallySummary.query(event);\n\t\t\tbreak;\n\t\tcase \"tally list\":\n\t\t\tallowed.push(\"station-id\");\n\t\t\toperation = () =>\n\t\t\t\tapi.event.passport.getPassportStationTallies.query(station());\n\t\t\tbreak;\n\t\tdefault: {\n\t\t\tconst mediaOperation =\n\t\t\t\t(await createStationAccessOperation(action, {\n\t\t\t\t\teventId,\n\t\t\t\t\tflags,\n\t\t\t\t\tallowed,\n\t\t\t\t\tstation,\n\t\t\t\t\tconfirm,\n\t\t\t\t})) ??\n\t\t\t\tcreatePassportMediaOperation(action, { eventId, flags, allowed });\n\t\t\tif (!mediaOperation)\n\t\t\t\tthrow new CliUsageError(\n\t\t\t\t\t\"Unknown passport command. Run et --help for supported commands.\",\n\t\t\t\t);\n\t\t\toperation = mediaOperation;\n\t\t}\n\t}\n\tconst unknown = [...flags.keys()].filter(\n\t\t(key) => key !== \"api-url\" && !allowed.includes(key),\n\t);\n\tif (unknown.length)\n\t\tthrow new CliUsageError(\n\t\t\t`Unknown option(s): ${unknown.map((key) => `--${key}`).join(\", \")}.`,\n\t\t);\n\tawait input.authenticate();\n\twriteSuccess(input.runtime, await operation());\n};\n", "import JSZip from \"jszip\";\nimport Papa from \"papaparse\";\n\n/**\n * Reads one sheet (the first by default; `sheetName` picks another) of a CSV\n * or XLSX file into rows of cell text (header row first). Shared by the web\n * importer and the CLI so both see the same table. Legacy `.xls` is not\n * supported.\n *\n * Reading is bounded to MAX_ROWS physical rows and MAX_COLUMNS columns. Data\n * past either limit is an error, never silently dropped, because a roster\n * import replaces the whole roster with what was read. Blank (for example\n * formatted but empty) cells past the limits are ignored.\n */\n\nconst MAX_ROWS = 50_000;\nconst MAX_COLUMNS = 200;\n\nconst isFilled = (value: string | undefined) => Boolean(value?.trim());\n\nconst rowLimitError = () =>\n\tnew Error(\n\t\t`The file has data below row ${MAX_ROWS.toLocaleString(\"en-US\")}. Remove blank rows or split the file, then try again.`,\n\t);\n\nconst columnLimitError = () =>\n\tnew Error(\n\t\t`The file has data beyond column ${MAX_COLUMNS}. Delete the extra columns, then try again.`,\n\t);\n\n/** Drops blank cells past the column limit; data there is an error. */\nconst clampColumns = (cells: string[]) => {\n\tif (cells.length <= MAX_COLUMNS) return cells;\n\tif (cells.slice(MAX_COLUMNS).some(isFilled)) throw columnLimitError();\n\treturn cells.slice(0, MAX_COLUMNS);\n};\n\nconst isZip = (bytes: Uint8Array) =>\n\tbytes[0] === 0x50 && bytes[1] === 0x4b && bytes[2] === 0x03;\n\nconst decodeXml = (value: string) =>\n\tvalue\n\t\t.replace(/_x([0-9A-Fa-f]{4})_/g, (_, hex: string) =>\n\t\t\tString.fromCharCode(Number.parseInt(hex, 16)),\n\t\t)\n\t\t.replace(/&#x([0-9A-Fa-f]+);/g, (_, hex: string) =>\n\t\t\tString.fromCodePoint(Number.parseInt(hex, 16)),\n\t\t)\n\t\t.replace(/&#(\\d+);/g, (_, digits: string) =>\n\t\t\tString.fromCodePoint(Number.parseInt(digits, 10)),\n\t\t)\n\t\t.replace(/&lt;/g, \"<\")\n\t\t.replace(/&gt;/g, \">\")\n\t\t.replace(/&quot;/g, '\"')\n\t\t.replace(/&apos;/g, \"'\")\n\t\t.replace(/&amp;/g, \"&\");\n\n/** Text of every `<t>` run, ignoring phonetic hints. */\nconst textRuns = (xml: string) =>\n\t[\n\t\t...xml\n\t\t\t.replace(/<rPh\\b[\\s\\S]*?<\\/rPh>/g, \"\")\n\t\t\t.matchAll(/<t\\b[^>]*>([\\s\\S]*?)<\\/t>/g),\n\t]\n\t\t.map((match) => decodeXml(match[1] ?? \"\"))\n\t\t.join(\"\");\n\nconst attribute = (tag: string, name: string) =>\n\tnew RegExp(`\\\\s${name}=\"([^\"]*)\"`).exec(tag)?.[1];\n\nconst columnIndex = (reference: string) => {\n\tconst letters = /^[A-Z]+/.exec(reference)?.[0] ?? \"\";\n\tlet index = 0;\n\tfor (const letter of letters) index = index * 26 + letter.charCodeAt(0) - 64;\n\treturn index - 1;\n};\n\ninterface WorkbookSheet {\n\tname: string;\n\t/** Path of the sheet's XML inside the archive, when the workbook names one. */\n\tpath: string | undefined;\n}\n\nconst sheetPathFromTarget = (target: string) =>\n\ttarget.startsWith(\"/\") ? target.slice(1) : `xl/${target}`;\n\n/** Every sheet of the workbook, in tab order, with its XML path. */\nconst readWorkbookSheets = async (zip: JSZip): Promise<WorkbookSheet[]> => {\n\tconst workbook = await zip.file(\"xl/workbook.xml\")?.async(\"string\");\n\tif (!workbook) return [];\n\tconst rels = await zip.file(\"xl/_rels/workbook.xml.rels\")?.async(\"string\");\n\tconst relationships = rels\n\t\t? [...rels.matchAll(/<Relationship\\b[^>]*>/g)].map((match) => match[0])\n\t\t: [];\n\treturn [...workbook.matchAll(/<sheet\\b[^>]*>/g)].map((match) => {\n\t\tconst relationId = attribute(match[0], \"r:id\");\n\t\tconst relationship = relationships.find(\n\t\t\t(tag) => attribute(tag, \"Id\") === relationId,\n\t\t);\n\t\tconst target = relationship ? attribute(relationship, \"Target\") : undefined;\n\t\treturn {\n\t\t\tname: decodeXml(attribute(match[0], \"name\") ?? \"\"),\n\t\t\tpath: target ? sheetPathFromTarget(target) : undefined,\n\t\t};\n\t});\n};\n\nconst DEFAULT_SHEET_PATH = \"xl/worksheets/sheet1.xml\";\n\nconst unknownSheetError = (\n\tsheetName: string,\n\tsheets: readonly WorkbookSheet[],\n) =>\n\tnew Error(\n\t\t`The workbook has no sheet named \"${sheetName}\". Sheets: ${sheets.map((sheet) => `\"${sheet.name}\"`).join(\", \") || \"none\"}.`,\n\t);\n\n/**\n * The sheet to read: the one named `sheetName` (exact name, else ignoring case\n * and surrounding spaces), or the first sheet when no name is given.\n */\nconst resolveSheetPath = (\n\tsheets: readonly WorkbookSheet[],\n\tsheetName: string | undefined,\n) => {\n\tif (sheetName === undefined) return sheets[0]?.path ?? DEFAULT_SHEET_PATH;\n\tconst wanted = sheetName.trim().toLowerCase();\n\tconst sheet =\n\t\tsheets.find((candidate) => candidate.name === sheetName) ??\n\t\tsheets.find((candidate) => candidate.name.trim().toLowerCase() === wanted);\n\tif (!sheet) throw unknownSheetError(sheetName, sheets);\n\tif (!sheet.path)\n\t\tthrow new Error(`The sheet \"${sheet.name}\" could not be read.`);\n\treturn sheet.path;\n};\n\nconst cellValue = (cellXml: string, sharedStrings: readonly string[]) => {\n\tconst open = /^<c\\b[^>]*>/.exec(cellXml)?.[0] ?? \"\";\n\tconst type = attribute(open, \"t\");\n\tif (type === \"inlineStr\") return textRuns(cellXml);\n\tconst raw = /<v>([\\s\\S]*?)<\\/v>/.exec(cellXml)?.[1];\n\tif (raw === undefined) return \"\";\n\tif (type === \"s\") return sharedStrings[Number(raw)] ?? \"\";\n\tif (type === \"b\") return raw === \"1\" ? \"TRUE\" : \"FALSE\";\n\treturn decodeXml(raw);\n};\n\nconst readSharedStrings = async (zip: JSZip) => {\n\tconst xml = await zip.file(\"xl/sharedStrings.xml\")?.async(\"string\");\n\treturn xml\n\t\t? [...xml.matchAll(/<si\\b[^>]*>([\\s\\S]*?)<\\/si>/g)].map((match) =>\n\t\t\t\ttextRuns(match[1] ?? \"\"),\n\t\t\t)\n\t\t: [];\n};\n\n/** Cells of one `<row>`, placed by their column reference. */\nconst readRowCells = (rowXml: string, sharedStrings: readonly string[]) => {\n\tconst cells: string[] = [];\n\tfor (const cellMatch of rowXml.matchAll(\n\t\t/<c\\b[^>]*?(?:\\/>|>[\\s\\S]*?<\\/c>)/g,\n\t)) {\n\t\tconst reference = attribute(cellMatch[0], \"r\");\n\t\tconst column = reference ? columnIndex(reference) : cells.length;\n\t\tconst value = cellValue(cellMatch[0], sharedStrings);\n\t\tif (column < 0 || column >= MAX_COLUMNS) {\n\t\t\tif (isFilled(value)) throw columnLimitError();\n\t\t\tcontinue;\n\t\t}\n\t\twhile (cells.length < column) cells.push(\"\");\n\t\tcells[column] = value;\n\t}\n\treturn cells;\n};\n\nconst readXlsx = async (bytes: Uint8Array, sheetName: string | undefined) => {\n\tconst zip = await JSZip.loadAsync(bytes);\n\tconst sharedStrings = await readSharedStrings(zip);\n\tconst sheetPath = resolveSheetPath(await readWorkbookSheets(zip), sheetName);\n\tconst sheet = await zip.file(sheetPath)?.async(\"string\");\n\tif (!sheet) throw new Error(\"The workbook has no readable sheet.\");\n\tconst table: string[][] = [];\n\t// Empty rows are self-closing (`<row r=\"4\"/>`) and must not swallow the next row.\n\tfor (const rowMatch of sheet.matchAll(\n\t\t/<row\\b([^>]*?)(?:\\/>|>([\\s\\S]*?)<\\/row>)/g,\n\t)) {\n\t\tconst rowNumber = Number(attribute(` ${rowMatch[1] ?? \"\"}`, \"r\"));\n\t\tconst index = Number.isInteger(rowNumber) ? rowNumber - 1 : table.length;\n\t\tconst cells = readRowCells(rowMatch[2] ?? \"\", sharedStrings);\n\t\t// Check before padding so a far-away row number never allocates a huge table.\n\t\tif (index >= MAX_ROWS) {\n\t\t\tif (cells.some(isFilled)) throw rowLimitError();\n\t\t\tcontinue;\n\t\t}\n\t\twhile (table.length < index) table.push([]);\n\t\ttable[index] = cells;\n\t}\n\treturn table;\n};\n\nconst readCsv = (bytes: Uint8Array) => {\n\tconst text = new TextDecoder(\"utf-8\").decode(bytes).replace(/^\\uFEFF/, \"\");\n\tconst parsed = Papa.parse<string[]>(text, { skipEmptyLines: false });\n\t// A stray or unclosed quote merges the rows after it into one cell.\n\tconst badQuote = parsed.errors.find((error) => error.type === \"Quotes\");\n\tif (badQuote) {\n\t\tconst near =\n\t\t\tbadQuote.row === undefined ? \"\" : ` near row ${badQuote.row + 1}`;\n\t\tthrow new Error(\n\t\t\t`The CSV has a misplaced or unclosed quote${near}. Fix it, then try again.`,\n\t\t);\n\t}\n\tif (parsed.data.slice(MAX_ROWS).some((row) => row.some(isFilled)))\n\t\tthrow rowLimitError();\n\treturn parsed.data.slice(0, MAX_ROWS).map(clampColumns);\n};\n\n/** Pads rows to the header width and drops trailing empty rows. */\nconst squareTable = (table: string[][]) => {\n\twhile (\n\t\ttable.length > 0 &&\n\t\t(table.at(-1) ?? []).every((value) => !value?.trim())\n\t)\n\t\ttable.pop();\n\tconst width = Math.max(0, ...table.map((row) => row.length));\n\treturn table.map((row) =>\n\t\tArray.from({ length: width }, (_, index) => row[index] ?? \"\"),\n\t);\n};\n\nconst toBytes = (data: ArrayBuffer | Uint8Array) =>\n\tdata instanceof Uint8Array ? data : new Uint8Array(data);\n\nconst isXlsx = (fileName: string, bytes: Uint8Array) =>\n\tfileName.toLowerCase().endsWith(\".xlsx\") || isZip(bytes);\n\nconst assertNotLegacyXls = (fileName: string) => {\n\tif (fileName.toLowerCase().endsWith(\".xls\"))\n\t\tthrow new Error(\"Save the file as .xlsx or .csv and try again.\");\n};\n\n/**\n * Sheet names of an XLSX workbook in tab order, so a caller can offer a\n * picker. A CSV has no sheets and returns an empty list.\n */\nexport const listSpreadsheetSheets = async (\n\tfileName: string,\n\tdata: ArrayBuffer | Uint8Array,\n): Promise<string[]> => {\n\tassertNotLegacyXls(fileName);\n\tconst bytes = toBytes(data);\n\tif (!isXlsx(fileName, bytes)) return [];\n\tconst zip = await JSZip.loadAsync(bytes);\n\treturn (await readWorkbookSheets(zip)).map((sheet) => sheet.name);\n};\n\nexport interface ReadSpreadsheetTableOptions {\n\t/** XLSX only: the sheet to read. Defaults to the first sheet. */\n\tsheetName?: string;\n}\n\nexport const readSpreadsheetTable = async (\n\tfileName: string,\n\tdata: ArrayBuffer | Uint8Array,\n\toptions: ReadSpreadsheetTableOptions = {},\n): Promise<string[][]> => {\n\tassertNotLegacyXls(fileName);\n\tconst bytes = toBytes(data);\n\tconst xlsx = isXlsx(fileName, bytes);\n\tif (!xlsx && options.sheetName !== undefined)\n\t\tthrow new Error(\n\t\t\t\"A CSV file has no sheets. Remove the sheet name or use an .xlsx file.\",\n\t\t);\n\tconst table = xlsx\n\t\t? await readXlsx(bytes, options.sheetName)\n\t\t: readCsv(bytes);\n\tconst squared = squareTable(table);\n\tif (squared.length === 0) throw new Error(\"The file is empty.\");\n\treturn squared;\n};\n", "import { z } from \"zod\";\n\nconst pointsSchema = z.number().int().min(0).max(2_147_483_647);\nconst printVersionSchema = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);\nexport const PASSPORT_STAMP_VALUE_MAX = 1000;\nexport const PASSPORT_BONUS_STAMPS_MAX = 1000;\nexport const passportBonusStampsSchema = z\n\t.number()\n\t.int()\n\t.min(0)\n\t.max(PASSPORT_BONUS_STAMPS_MAX);\nexport const PASSPORT_PRIZE_STAMP_COST_MAX = 100_000;\nexport const PASSPORT_REDEMPTION_QUANTITY_MAX = 20;\nexport const PASSPORT_TALLY_ITEMS_MAX = 30;\nexport const PASSPORT_TALLY_ITEM_NAME_MAX = 60;\nexport const PASSPORT_TALLY_QUANTITY_MAX = 20;\nexport const PASSPORT_MENU_STOCK_MAX = 2_147_483_647;\n/** Food/drink stamp stations: each stamp uses one unit of the chosen item. */\nexport const passportMenuItemsSchema = z\n\t.array(\n\t\tz.object({\n\t\t\tname: z.string().trim().min(1).max(PASSPORT_TALLY_ITEM_NAME_MAX),\n\t\t\tstock: z.number().int().min(0).max(PASSPORT_MENU_STOCK_MAX).nullable(),\n\t\t\tsiteStocks: z\n\t\t\t\t.array(\n\t\t\t\t\tz\n\t\t\t\t\t\t.object({\n\t\t\t\t\t\t\tsite: z.string().trim().min(1).max(60),\n\t\t\t\t\t\t\tstock: z\n\t\t\t\t\t\t\t\t.number()\n\t\t\t\t\t\t\t\t.int()\n\t\t\t\t\t\t\t\t.min(0)\n\t\t\t\t\t\t\t\t.max(PASSPORT_MENU_STOCK_MAX)\n\t\t\t\t\t\t\t\t.nullable(),\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.strict(),\n\t\t\t\t)\n\t\t\t\t.max(30)\n\t\t\t\t.optional(),\n\t\t}),\n\t)\n\t.min(1)\n\t.max(PASSPORT_TALLY_ITEMS_MAX)\n\t.superRefine((items, context) => {\n\t\tconst names = new Set<string>();\n\t\titems.forEach((item, index) => {\n\t\t\tconst name = item.name.toLocaleLowerCase();\n\t\t\tif (names.has(name))\n\t\t\t\tcontext.addIssue({\n\t\t\t\t\tcode: \"custom\",\n\t\t\t\t\tpath: [index, \"name\"],\n\t\t\t\t\tmessage: \"Menu item names must be unique.\",\n\t\t\t\t});\n\t\t\tnames.add(name);\n\t\t\tconst sites = (item.siteStocks ?? []).map((row) =>\n\t\t\t\trow.site.toLowerCase(),\n\t\t\t);\n\t\t\tconst expected = (items[0]?.siteStocks ?? [])\n\t\t\t\t.map((row) => row.site)\n\t\t\t\t.sort();\n\t\t\tif (\n\t\t\t\tnew Set(sites).size !== sites.length ||\n\t\t\t\tJSON.stringify(\n\t\t\t\t\t(item.siteStocks ?? []).map((row) => row.site).sort(),\n\t\t\t\t) !== JSON.stringify(expected)\n\t\t\t)\n\t\t\t\tcontext.addIssue({\n\t\t\t\t\tcode: \"custom\",\n\t\t\t\t\tpath: [index, \"siteStocks\"],\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t\"Every menu item must use the same site names and casing; site names must be unique ignoring case.\",\n\t\t\t\t});\n\t\t});\n\t});\nconst validateMenuCollection = (\n\tconfig: {\n\t\tcollectionMode: string;\n\t\tmenuItems?: z.output<typeof passportMenuItemsSchema>;\n\t\tprizeDeskAward?: boolean;\n\t\tcategory?: string;\n\t\tcollectionLimit?: \"ONCE\" | \"UNLIMITED\";\n\t},\n\tcontext: z.RefinementCtx,\n) => {\n\tif (\n\t\tconfig.collectionLimit !== undefined &&\n\t\t(!config.menuItems?.length ||\n\t\t\tconfig.collectionMode !== \"STAFF_SCAN\" ||\n\t\t\t![\"FOOD\", \"DRINK\"].includes(config.category ?? \"GAME\"))\n\t)\n\t\tcontext.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tpath: [\"collectionLimit\"],\n\t\t\tmessage:\n\t\t\t\t\"Collection limits require a FOOD or DRINK staff-scan menu station.\",\n\t\t});\n\tif (\n\t\tconfig.menuItems &&\n\t\t(config.collectionMode !== \"STAFF_SCAN\" || config.prizeDeskAward)\n\t)\n\t\tcontext.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tpath: [\"menuItems\"],\n\t\t\tmessage:\n\t\t\t\t\"Menu items require staff-scan collection without prize-desk awards.\",\n\t\t});\n};\n\nconst stampValueSchema = z.number().int().min(0).max(PASSPORT_STAMP_VALUE_MAX);\n\n/** Guest-facing grouping for a station. Unset reads as GAME. */\nexport const PASSPORT_STATION_CATEGORIES = [\n\t\"GAME\",\n\t\"FOOD\",\n\t\"DRINK\",\n\t\"BINGO\",\n] as const;\nexport const passportStationCategorySchema = z.enum(\n\tPASSPORT_STATION_CATEGORIES,\n);\nexport type PassportStationCategory = z.infer<\n\ttypeof passportStationCategorySchema\n>;\n\n/** Longest custom category name, in either language. */\nexport const PASSPORT_CATEGORY_LABEL_MAX = 40;\n\n/** The languages a category name can be written in. */\nexport const PASSPORT_CATEGORY_LABEL_LOCALES = [\"en\", \"zh-CN\"] as const;\nexport type PassportCategoryLabelLocale =\n\t(typeof PASSPORT_CATEGORY_LABEL_LOCALES)[number];\n\n/** An event's own names for station categories. Unset entries use the built-in wording. */\nexport type PassportCategoryLabels = Partial<\n\tRecord<\n\t\tPassportStationCategory,\n\t\tPartial<Record<PassportCategoryLabelLocale, string>>\n\t>\n>;\n\n/** One custom category name: trimmed, 1 to 40 characters. */\nconst passportCategoryLabelTextSchema = z\n\t.string()\n\t.trim()\n\t.min(1)\n\t.max(PASSPORT_CATEGORY_LABEL_MAX);\n\n/**\n * Keeps the usable names in `value` and drops everything else: unknown\n * categories or languages, non-text, blank or over-long names, and categories\n * left with no name. Returns undefined when nothing is left. Never throws, so\n * a hand-edited row cannot take the whole passport config down.\n */\nexport const sanitizePassportCategoryLabels = (\n\tvalue: unknown,\n): PassportCategoryLabels | undefined => {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value))\n\t\treturn undefined;\n\tconst labels: PassportCategoryLabels = {};\n\tfor (const category of PASSPORT_STATION_CATEGORIES) {\n\t\tconst entry: unknown = Reflect.get(value, category);\n\t\tif (typeof entry !== \"object\" || entry === null) continue;\n\t\tconst names: Partial<Record<PassportCategoryLabelLocale, string>> = {};\n\t\tfor (const locale of PASSPORT_CATEGORY_LABEL_LOCALES) {\n\t\t\tconst parsed = passportCategoryLabelTextSchema.safeParse(\n\t\t\t\tReflect.get(entry, locale),\n\t\t\t);\n\t\t\tif (parsed.success) names[locale] = parsed.data;\n\t\t}\n\t\tif (Object.keys(names).length > 0) labels[category] = names;\n\t}\n\treturn Object.keys(labels).length > 0 ? labels : undefined;\n};\n\n/**\n * The event's custom name for `category` in `locale`, or undefined when it has\n * none, so the caller keeps its own built-in wording (which differs by\n * surface: a heading says \"Food\", a card eyebrow says \"Food stall\"). Pass\n * \"en\" for English-only screens (admin, station crew); a Chinese guest only\n * ever gets a Chinese custom name, never the English one.\n */\nexport const passportCustomCategoryLabel = (\n\tlabels: PassportCategoryLabels | null | undefined,\n\tcategory: PassportStationCategory,\n\tlocale: PassportCategoryLabelLocale = \"en\",\n): string | undefined => labels?.[category]?.[locale]?.trim() || undefined;\n\n/** Trimmed item names, unique ignoring case, for a STAFF_TALLY station. */\nexport const passportTallyItemsSchema = z\n\t.array(z.string().trim().min(1).max(PASSPORT_TALLY_ITEM_NAME_MAX))\n\t.min(1)\n\t.max(PASSPORT_TALLY_ITEMS_MAX)\n\t.superRefine((items, context) => {\n\t\tconst seen = new Set<string>();\n\t\titems.forEach((item, index) => {\n\t\t\tconst key = item.toLocaleLowerCase();\n\t\t\tif (seen.has(key))\n\t\t\t\tcontext.addIssue({\n\t\t\t\t\tcode: \"custom\",\n\t\t\t\t\tpath: [index],\n\t\t\t\t\tmessage: `\"${item}\" is listed more than once.`,\n\t\t\t\t});\n\t\t\tseen.add(key);\n\t\t});\n\t});\n\nexport const PASSPORT_STATION_INFO_SUBTITLE_MAX = 80;\nexport const PASSPORT_STATION_INFO_STEPS_MAX = 8;\nexport const PASSPORT_STATION_INFO_STEP_MAX = 160;\nexport const PASSPORT_STATION_INFO_MENU_MAX = 15;\nexport const PASSPORT_STATION_INFO_MENU_NAME_MAX = 80;\nexport const PASSPORT_STATION_INFO_MENU_DETAIL_MAX = 200;\nexport const PASSPORT_STATION_INFO_NOTE_MAX = 240;\n\n/** Trimmed text where an empty string reads as absent. */\nconst optionalInfoText = (maximum: number) =>\n\tz\n\t\t.string()\n\t\t.trim()\n\t\t.max(maximum)\n\t\t.optional()\n\t\t.transform((value) => value || undefined);\n\nexport type PassportStationMenuItem = {\n\tname: string;\n\tdetail?: string;\n\t/** Allergens, shown as \"Contains: ...\". */\n\tcontains?: string;\n};\n\n/** Guest-facing station information shown in the passport station drawer. */\nexport type PassportStationInfo = {\n\tsubtitle?: string;\n\t/** \"How to play\" steps, usually for games. */\n\tsteps?: string[];\n\t/** Menu items, usually for food and drink stations. */\n\tmenu?: PassportStationMenuItem[];\n\tnote?: string;\n};\n\nconst passportStationInfoStepsSchema = z\n\t.array(z.string().trim().max(PASSPORT_STATION_INFO_STEP_MAX))\n\t.transform((steps) => steps.filter((step) => step !== \"\"))\n\t.pipe(z.array(z.string()).max(PASSPORT_STATION_INFO_STEPS_MAX))\n\t.transform((steps) => (steps.length > 0 ? steps : undefined));\n\nconst passportStationInfoMenuSchema = z\n\t.array(\n\t\tz.object({\n\t\t\tname: z.string().trim().max(PASSPORT_STATION_INFO_MENU_NAME_MAX),\n\t\t\tdetail: optionalInfoText(PASSPORT_STATION_INFO_MENU_DETAIL_MAX),\n\t\t\tcontains: optionalInfoText(PASSPORT_STATION_INFO_MENU_DETAIL_MAX),\n\t\t}),\n\t)\n\t// Fully blank rows are dropped; a row with detail but no name fails below.\n\t.transform((rows): PassportStationMenuItem[] =>\n\t\trows\n\t\t\t.filter((row) => row.name !== \"\" || row.detail || row.contains)\n\t\t\t.map(({ name, detail, contains }) => ({\n\t\t\t\tname,\n\t\t\t\t...(detail ? { detail } : {}),\n\t\t\t\t...(contains ? { contains } : {}),\n\t\t\t})),\n\t)\n\t.pipe(\n\t\tz\n\t\t\t.array(\n\t\t\t\tz.object({\n\t\t\t\t\tname: z.string().min(1, \"Menu items need a name.\"),\n\t\t\t\t\tdetail: z.string().optional(),\n\t\t\t\t\tcontains: z.string().optional(),\n\t\t\t\t}),\n\t\t\t)\n\t\t\t.max(PASSPORT_STATION_INFO_MENU_MAX),\n\t)\n\t.transform((rows) => (rows.length > 0 ? rows : undefined));\n\n/**\n * Station info. Empty strings, blank list rows and empty lists normalise to\n * absent, and an info object with nothing left normalises to undefined.\n */\nexport const passportStationInfoSchema = z\n\t.object({\n\t\tsubtitle: optionalInfoText(PASSPORT_STATION_INFO_SUBTITLE_MAX),\n\t\tsteps: passportStationInfoStepsSchema.optional(),\n\t\tmenu: passportStationInfoMenuSchema.optional(),\n\t\tnote: optionalInfoText(PASSPORT_STATION_INFO_NOTE_MAX),\n\t})\n\t.transform((info): PassportStationInfo | undefined => {\n\t\tconst normalised: PassportStationInfo = {\n\t\t\t...(info.subtitle ? { subtitle: info.subtitle } : {}),\n\t\t\t...(info.steps ? { steps: info.steps } : {}),\n\t\t\t...(info.menu ? { menu: info.menu } : {}),\n\t\t\t...(info.note ? { note: info.note } : {}),\n\t\t};\n\t\treturn Object.keys(normalised).length > 0 ? normalised : undefined;\n\t});\n\n/**\n * Station info as an upsert input: omitted keeps the stored info, null (or an\n * object that normalises to nothing) clears it.\n */\nexport const passportStationInfoInputSchema = z.union([\n\tz.null(),\n\tpassportStationInfoSchema.transform((info) => info ?? null),\n]);\n\n/** Parsed station info from a stored config, or null. Never throws. */\nexport const readPassportStationInfo = (\n\tconfig: { info?: unknown } | null | undefined,\n): PassportStationInfo | null => {\n\tconst parsed = passportStationInfoSchema.safeParse(config?.info);\n\treturn parsed.success ? (parsed.data ?? null) : null;\n};\n\nexport const passportLoginMethodsSchema = z\n\t.object({\n\t\temailOtp: z.boolean(),\n\t\tgoogle: z.boolean(),\n\t\tguest: z.boolean(),\n\t\t/** Staff ID against the event roster. Absent reads as false. */\n\t\tstaffId: z.boolean().default(false),\n\t\t/** Staff ID sign-in also checks the last name. Absent reads as true. */\n\t\tstaffIdRequiresLastName: z.boolean().default(true),\n\t})\n\t.strict()\n\t.refine((methods) => methods.emailOtp || methods.google || methods.staffId, {\n\t\tmessage:\n\t\t\t\"Keep email OTP, Google or roster sign-in available for passport recovery.\",\n\t});\n\n/** The crew-set queue waits, shortest first. */\nexport const PASSPORT_QUEUE_STATUSES = [\n\t\"UNDER_10_MIN\",\n\t\"UNDER_30_MIN\",\n\t\"OVER_30_MIN\",\n] as const;\n\nexport type PassportQueueStatus = (typeof PASSPORT_QUEUE_STATUSES)[number];\n\nexport const passportQueueStatusSchema = z.enum(PASSPORT_QUEUE_STATUSES);\n\n/** Minutes before a crew-set queue wait reads as not updated recently. */\nexport const PASSPORT_QUEUE_STATUS_STALE_MINUTES_DEFAULT = 10;\nexport const PASSPORT_QUEUE_STATUS_STALE_MINUTES_MIN = 1;\nexport const PASSPORT_QUEUE_STATUS_STALE_MINUTES_MAX = 240;\n\n/** What the roster identifier is called when the event has not named it. */\nexport const PASSPORT_STAFF_ID_LABEL_DEFAULT = \"Employee Number\";\n\n/** Longest custom name for the roster identifier. */\nexport const PASSPORT_STAFF_ID_LABEL_MAX = 40;\n\n/** A custom name for the roster identifier, trimmed and non-empty. */\nexport const passportStaffIdLabelSchema = z\n\t.string()\n\t.trim()\n\t.min(1)\n\t.max(PASSPORT_STAFF_ID_LABEL_MAX);\n\nexport const passportConfigSchema = z.object({\n\tversion: z.literal(1),\n\tloginMethods: passportLoginMethodsSchema,\n\t/** Guests may scan station QR codes themselves. Absent reads as true. */\n\tguestScan: z.boolean().optional(),\n\t/** The guest passport offers Simplified Chinese. Absent reads as false. */\n\tsimplifiedChinese: z.boolean().optional(),\n\t/**\n\t * What the roster identifier is called (\"Staff ID\", \"Employee Number\").\n\t * Absent reads as `PASSPORT_STAFF_ID_LABEL_DEFAULT`. A malformed value never\n\t * invalidates the config; it just reads as absent.\n\t */\n\tstaffIdLabel: passportStaffIdLabelSchema.optional().catch(undefined),\n\t/**\n\t * The event's own names for station categories. Usable names are kept and\n\t * anything malformed is dropped, so it never invalidates the config.\n\t */\n\tcategoryLabels: z\n\t\t.unknown()\n\t\t.transform(sanitizePassportCategoryLabels)\n\t\t.optional(),\n\t/** Station crew set a queue wait guests see. Absent reads as false. */\n\tqueueStatus: z.boolean().optional().catch(undefined),\n\t/**\n\t * Minutes before a crew-set queue wait reads as not updated recently.\n\t * Absent (or malformed) reads as `PASSPORT_QUEUE_STATUS_STALE_MINUTES_DEFAULT`.\n\t */\n\tqueueStatusStaleMinutes: z\n\t\t.number()\n\t\t.int()\n\t\t.min(PASSPORT_QUEUE_STATUS_STALE_MINUTES_MIN)\n\t\t.max(PASSPORT_QUEUE_STATUS_STALE_MINUTES_MAX)\n\t\t.optional()\n\t\t.catch(undefined),\n});\n\n/** Whether guests may scan station QR codes. Absent reads as true. */\nexport const passportGuestScanEnabled = (\n\tconfig: { guestScan?: boolean } | null | undefined,\n) => config?.guestScan ?? true;\n\n/** Whether the guest passport offers Simplified Chinese. Absent reads as false. */\nexport const passportSimplifiedChineseEnabled = (\n\tconfig: { simplifiedChinese?: boolean } | null | undefined,\n) => config?.simplifiedChinese ?? false;\n\n/**\n * What the event calls the roster identifier, in English: the organiser's\n * label, else \"Employee Number\". The Chinese passport keeps 员工编号.\n */\nexport const passportStaffIdLabel = (\n\tconfig: { staffIdLabel?: string | null } | null | undefined,\n) => config?.staffIdLabel?.trim() || PASSPORT_STAFF_ID_LABEL_DEFAULT;\n\n/** Whether station crew set queue waits that guests see. Absent reads as false. */\nexport const passportQueueStatusEnabled = (\n\tconfig: { queueStatus?: boolean } | null | undefined,\n) => config?.queueStatus ?? false;\n\n/** Minutes before a queue wait reads as not updated recently. Absent reads as 10. */\nexport const passportQueueStatusStaleMinutes = (\n\tconfig: { queueStatusStaleMinutes?: number } | null | undefined,\n) =>\n\tconfig?.queueStatusStaleMinutes ??\n\tPASSPORT_QUEUE_STATUS_STALE_MINUTES_DEFAULT;\n\n/**\n * Whether a queue wait set at `updatedAt` is too old to trust at `now`. A wait\n * exactly `staleMinutes` old is still fresh; one millisecond later it is stale.\n */\nexport const isPassportQueueStatusStale = (\n\tupdatedAt: Date,\n\tnow: Date,\n\tstaleMinutes: number,\n) => now.getTime() - updatedAt.getTime() > staleMinutes * 60_000;\n\n/**\n * What a retry of a redemption that was since reversed is refused with\n * (CONFLICT). The prize desk and the organiser workspace match it to discard\n * their stored request id, so the next submit hands over a new redemption.\n */\nexport const PASSPORT_REDEMPTION_REVERSED_MESSAGE =\n\t\"This redemption was reversed. Submit it again to hand over a new one.\";\n\n/** Whether a failed redeem is the refusal of a retry of a reversed redemption. */\nexport const isReversedRedemptionReplay = (cause: unknown) =>\n\tcause instanceof Error &&\n\tcause.message === PASSPORT_REDEMPTION_REVERSED_MESSAGE;\n\n/** Shown when crew set a queue wait while the event has queue status off. */\nexport const PASSPORT_QUEUE_STATUS_OFF_MESSAGE =\n\t\"Queue status is turned off for this event.\";\n\n/** Shown when a guest tries to scan a station while guest scanning is off. */\nexport const PASSPORT_GUEST_SCAN_OFF_MESSAGE =\n\t\"Station scanning is turned off for this event. Show your QR to the station crew instead.\";\n\n/** Collection modes whose station stamp crew can award at the prize desk. */\nexport const PRIZE_DESK_AWARD_MODES: readonly string[] = [\n\t\"SELF_SCAN\",\n\t\"STAFF_SCAN\",\n];\n\nexport const passportStationConfigSchema = z\n\t.object({\n\t\tversion: z.literal(1),\n\t\tcollectionMode: z.enum([\n\t\t\t\"SELF_SCAN\",\n\t\t\t\"STAFF_SCAN\",\n\t\t\t\"STAFF_SCORE\",\n\t\t\t\"STAFF_TALLY\",\n\t\t]),\n\t\tmaxPoints: pointsSchema,\n\t\tprintedQrVersion: printVersionSchema,\n\t\tprintedQrEnabled: z.boolean(),\n\t\tstampValue: stampValueSchema.optional(),\n\t\tcategory: passportStationCategorySchema.optional(),\n\t\ttallyItems: passportTallyItemsSchema.optional(),\n\t\ttallyEarnsStamp: z.boolean().optional(),\n\t\tmenuItems: passportMenuItemsSchema.optional(),\n\t\tshowHowToCollect: z.boolean().optional(),\n\t\tshowMyQr: z.boolean().optional(),\n\t\tcollectionLimit: z.enum([\"ONCE\", \"UNLIMITED\"]).optional(),\n\t\tprizeDeskAward: z.boolean().optional(),\n\t\t// Malformed info never invalidates the station; it just reads as absent.\n\t\tinfo: passportStationInfoSchema.optional().catch(undefined),\n\t})\n\t.superRefine((config, context) => {\n\t\tvalidateMenuCollection(config, context);\n\n\t\tconst tally = config.collectionMode === \"STAFF_TALLY\";\n\t\tif (tally && !config.tallyItems) {\n\t\t\tcontext.addIssue({\n\t\t\t\tcode: \"custom\",\n\t\t\t\tpath: [\"tallyItems\"],\n\t\t\t\tmessage: \"Tally stations need at least one item.\",\n\t\t\t});\n\t\t}\n\t\tif (\n\t\t\t!tally &&\n\t\t\t(config.tallyItems !== undefined || config.tallyEarnsStamp !== undefined)\n\t\t) {\n\t\t\tcontext.addIssue({\n\t\t\t\tcode: \"custom\",\n\t\t\t\tpath: [\"tallyItems\"],\n\t\t\t\tmessage: \"Only tally stations can list items.\",\n\t\t\t});\n\t\t}\n\t\tif (config.prizeDeskAward === true) {\n\t\t\tif (!PRIZE_DESK_AWARD_MODES.includes(config.collectionMode)) {\n\t\t\t\tcontext.addIssue({\n\t\t\t\t\tcode: \"custom\",\n\t\t\t\t\tpath: [\"prizeDeskAward\"],\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t\"Only self-scan and staff-scan stations can be awarded at the prize desk.\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (config.category === \"BINGO\") {\n\t\t\t\tcontext.addIssue({\n\t\t\t\t\tcode: \"custom\",\n\t\t\t\t\tpath: [\"prizeDeskAward\"],\n\t\t\t\t\tmessage: \"The Bingo station cannot be awarded at the prize desk.\",\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tif (config.collectionMode !== \"STAFF_SCORE\" && config.maxPoints !== 0) {\n\t\t\tcontext.addIssue({\n\t\t\t\tcode: \"custom\",\n\t\t\t\tpath: [\"maxPoints\"],\n\t\t\t\tmessage: \"Only scored stations can award points.\",\n\t\t\t});\n\t\t}\n\t\tif (config.collectionMode !== \"SELF_SCAN\" && config.printedQrEnabled) {\n\t\t\tcontext.addIssue({\n\t\t\t\tcode: \"custom\",\n\t\t\t\tpath: [\"printedQrEnabled\"],\n\t\t\t\tmessage: \"Only self-scan stations can issue printed QR codes.\",\n\t\t\t});\n\t\t}\n\t});\n\nconst DEFAULT_PASSPORT_CONFIG: z.infer<typeof passportConfigSchema> = {\n\tversion: 1,\n\tloginMethods: {\n\t\temailOtp: true,\n\t\tgoogle: false,\n\t\tguest: false,\n\t\tstaffId: false,\n\t\tstaffIdRequiresLastName: true,\n\t},\n};\n\nexport const readPassportConfig = (value: unknown) =>\n\tpassportConfigSchema.parse(value ?? DEFAULT_PASSPORT_CONFIG);\n\n/**\n * Like `readPassportConfig`, but a malformed stored config reads as the\n * defaults (guest scanning on) instead of throwing. For guest claims and\n * settings saves, which must not fail on a hand-edited row.\n */\nexport const readPassportConfigOrDefault = (value: unknown) => {\n\tconst parsed = passportConfigSchema.safeParse(\n\t\tvalue ?? DEFAULT_PASSPORT_CONFIG,\n\t);\n\treturn parsed.success ? parsed.data : DEFAULT_PASSPORT_CONFIG;\n};\n\nexport const readPassportStationConfig = (value: unknown) =>\n\tvalue == null ? null : passportStationConfigSchema.parse(value);\n\nexport const passportStationCollectionSchema = z.discriminatedUnion(\n\t\"collectionMode\",\n\t[\n\t\tz\n\t\t\t.object({\n\t\t\t\tshowHowToCollect: z.boolean().optional(),\n\t\t\t\tshowMyQr: z.boolean().optional(),\n\t\t\t\tcollectionMode: z.literal(\"SELF_SCAN\"),\n\t\t\t\tstampValue: stampValueSchema.optional(),\n\t\t\t\tcategory: passportStationCategorySchema.optional(),\n\t\t\t\tprizeDeskAward: z.boolean().optional(),\n\t\t\t\tinfo: passportStationInfoInputSchema.optional(),\n\t\t\t})\n\t\t\t.strict(),\n\t\tz\n\t\t\t.object({\n\t\t\t\tshowHowToCollect: z.boolean().optional(),\n\t\t\t\tshowMyQr: z.boolean().optional(),\n\t\t\t\tcollectionMode: z.literal(\"STAFF_SCAN\"),\n\t\t\t\tmenuItems: passportMenuItemsSchema.nullable().optional(),\n\t\t\t\tcollectionLimit: z.enum([\"ONCE\", \"UNLIMITED\"]).optional(),\n\t\t\t\tstampValue: stampValueSchema.optional(),\n\t\t\t\tcategory: passportStationCategorySchema.optional(),\n\t\t\t\tprizeDeskAward: z.boolean().optional(),\n\t\t\t\tinfo: passportStationInfoInputSchema.optional(),\n\t\t\t})\n\t\t\t.strict(),\n\t\tz\n\t\t\t.object({\n\t\t\t\tshowHowToCollect: z.boolean().optional(),\n\t\t\t\tshowMyQr: z.boolean().optional(),\n\t\t\t\tcollectionMode: z.literal(\"STAFF_SCORE\"),\n\t\t\t\tmaxPoints: pointsSchema,\n\t\t\t\tstampValue: stampValueSchema.optional(),\n\t\t\t\tcategory: passportStationCategorySchema.optional(),\n\t\t\t\tinfo: passportStationInfoInputSchema.optional(),\n\t\t\t})\n\t\t\t.strict(),\n\t\tz\n\t\t\t.object({\n\t\t\t\tshowHowToCollect: z.boolean().optional(),\n\t\t\t\tshowMyQr: z.boolean().optional(),\n\t\t\t\tcollectionMode: z.literal(\"STAFF_TALLY\"),\n\t\t\t\ttallyItems: passportTallyItemsSchema,\n\t\t\t\ttallyEarnsStamp: z.boolean().default(false),\n\t\t\t\tstampValue: stampValueSchema.optional(),\n\t\t\t\tcategory: passportStationCategorySchema.optional(),\n\t\t\t\tinfo: passportStationInfoInputSchema.optional(),\n\t\t\t})\n\t\t\t.strict(),\n\t],\n);\n\nexport const passportEventIdSchema = z.object({ eventId: z.string().min(1) });\n\nexport const passportStationIdSchema = passportEventIdSchema.extend({\n\tstationId: z.string().min(1),\n});\nexport const passportQrInputSchema = passportEventIdSchema.extend({\n\tcode: z.string().min(1).max(2048),\n});\nexport const passportPrintQrMutationSchema = passportStationIdSchema.extend({\n\texpectedPrintedQrVersion: printVersionSchema,\n});\nexport const collectPassportStampByStaffSchema = passportStationIdSchema.extend(\n\t{\n\t\tprofileCode: z.string().min(1).max(2048),\n\t\tsite: z.string().trim().min(1).max(60).optional(),\n\t\trequestId: z.uuid().optional(),\n\t\tpoints: pointsSchema.optional(),\n\t\titem: z.string().trim().min(1).max(PASSPORT_TALLY_ITEM_NAME_MAX).optional(),\n\t},\n);\nexport const recordPassportTallySchema = passportStationIdSchema.extend({\n\tprofileCode: z.string().min(1).max(2048),\n\titem: z.string().trim().min(1).max(PASSPORT_TALLY_ITEM_NAME_MAX),\n\tquantity: z.number().int().min(1).max(PASSPORT_TALLY_QUANTITY_MAX).default(1),\n});\nexport const reversePassportTallySchema = passportEventIdSchema.extend({\n\ttallyId: z.string().min(1),\n\treason: z.string().trim().min(1).max(200),\n});\nexport const correctPassportStampSchema = passportStationIdSchema.extend({\n\tparticipantId: z.string().min(1),\n\tcollectionId: z.string().min(1).optional(),\n\tsite: z.string().trim().min(1).max(60).optional(),\n\tstamped: z.boolean(),\n\treason: z.string().trim().min(1).max(500),\n\tpoints: pointsSchema.optional(),\n\titem: z.string().trim().min(1).max(PASSPORT_TALLY_ITEM_NAME_MAX).optional(),\n});\n\nexport const beginPassportAccountLinkSchema = z.discriminatedUnion(\"method\", [\n\tpassportEventIdSchema\n\t\t.extend({\n\t\t\tmethod: z.literal(\"EMAIL_OTP\"),\n\t\t\temail: z.string().trim().toLowerCase().pipe(z.email()),\n\t\t})\n\t\t.strict(),\n\tpassportEventIdSchema.extend({ method: z.literal(\"GOOGLE\") }).strict(),\n]);\n\nexport const passportAccountLinkIntentSchema = passportEventIdSchema.extend({\n\tintent: z.string().regex(/^epl1\\.[A-Za-z0-9_-]{43}$/),\n});\n\nexport const requestPassportAccountLinkOtpSchema =\n\tpassportAccountLinkIntentSchema.extend({\n\t\temail: z.string().trim().toLowerCase().pipe(z.email()),\n\t});\n\nexport const joinPassportSchema = passportEventIdSchema.extend({\n\tname: z.string().trim().min(1).max(100),\n});\n\nconst passportCategoryLabelInputSchema = z\n\t.string()\n\t.trim()\n\t.max(PASSPORT_CATEGORY_LABEL_MAX);\n\nconst passportCategoryLabelEntryInputSchema = z.strictObject({\n\ten: passportCategoryLabelInputSchema.optional(),\n\t\"zh-CN\": passportCategoryLabelInputSchema.optional(),\n});\n\n/** Names as typed in settings: blank is allowed and means no custom name. */\nexport const passportCategoryLabelsInputSchema = z\n\t.strictObject({\n\t\tGAME: passportCategoryLabelEntryInputSchema.optional(),\n\t\tFOOD: passportCategoryLabelEntryInputSchema.optional(),\n\t\tDRINK: passportCategoryLabelEntryInputSchema.optional(),\n\t\tBINGO: passportCategoryLabelEntryInputSchema.optional(),\n\t})\n\t.transform((labels) => sanitizePassportCategoryLabels(labels) ?? {});\n\nexport const passportSettingsSchema = passportEventIdSchema.extend({\n\tluckyDrawStampThreshold: z.number().int().positive().nullable(),\n\tprizeStampThreshold: z.number().int().positive().nullable(),\n\t/** Units per participant across all prizes. 0 means no cap. */\n\tmaxRedemptionsPerParticipant: z.number().int().min(0).max(2_147_483_647),\n\tlinkedDrawEventId: z.string().min(1).nullable(),\n\tloginMethods: passportLoginMethodsSchema.optional(),\n\t/** Guests may scan station QR codes. Omitted keeps the stored setting. */\n\tguestScan: z.boolean().optional(),\n\t/** The guest passport offers Simplified Chinese. Omitted keeps the stored setting. */\n\tsimplifiedChinese: z.boolean().optional(),\n\t/**\n\t * What the roster identifier is called. Omitted keeps the stored label;\n\t * null or blank resets it to \"Employee Number\".\n\t */\n\tstaffIdLabel: z\n\t\t.union([\n\t\t\tz.null(),\n\t\t\tz\n\t\t\t\t.string()\n\t\t\t\t.trim()\n\t\t\t\t.max(PASSPORT_STAFF_ID_LABEL_MAX)\n\t\t\t\t.transform((label) => (label === \"\" ? null : label)),\n\t\t])\n\t\t.optional(),\n\t/**\n\t * The event's own names for station categories, per language. Omitted keeps\n\t * the stored names; an object replaces them all (blank names mean the\n\t * built-in wording); null clears them. Names are trimmed, up to 40 characters.\n\t */\n\tcategoryLabels: z\n\t\t.union([z.null(), passportCategoryLabelsInputSchema])\n\t\t.optional(),\n\t/** Station crew set queue waits guests see. Omitted keeps the stored setting. */\n\tqueueStatus: z.boolean().optional(),\n\t/** Minutes before a queue wait reads as stale. Omitted keeps; null resets to 10. */\n\tqueueStatusStaleMinutes: z\n\t\t.number()\n\t\t.int()\n\t\t.min(PASSPORT_QUEUE_STATUS_STALE_MINUTES_MIN)\n\t\t.max(PASSPORT_QUEUE_STATUS_STALE_MINUTES_MAX)\n\t\t.nullable()\n\t\t.optional(),\n});\n\nexport type PassportSettingsInput = z.infer<typeof passportSettingsSchema>;\n\n/** Crew set or clear (null) their station's queue wait. */\nexport const setPassportStationQueueStatusSchema = passportEventIdSchema.extend(\n\t{\n\t\tstationId: z.string().min(1),\n\t\tstatus: passportQueueStatusSchema.nullable(),\n\t},\n);\n\nexport type SetPassportStationQueueStatusInput = z.infer<\n\ttypeof setPassportStationQueueStatusSchema\n>;\n\n/** Renames the passport's bingo game (its Bingo station). Same limit as station names. */\nexport const renamePassportBingoSchema = passportEventIdSchema.extend({\n\tname: z.string().trim().min(1).max(100),\n});\n\nexport const passportStationSchema = passportEventIdSchema.extend({\n\tid: z.string().optional(),\n\tname: z.string().trim().min(1).max(100),\n\tdescription: z.string().trim().max(1000).nullable(),\n\tlocation: z.string().trim().max(200).nullable(),\n\t/** Street or site address. Omitted keeps the stored value; null clears it. */\n\taddress: z.string().trim().max(300).nullable().optional(),\n\t/** Cover art key. Omitted keeps the stored image; null clears it. */\n\timageKey: z.string().nullable().optional(),\n\torder: z.number().int().min(0),\n\topensAt: z.date().nullable(),\n\tclosesAt: z.date().nullable(),\n\tcollection: passportStationCollectionSchema.optional(),\n});\n\nexport const passportPrizeSchema = passportEventIdSchema.extend({\n\tid: z.string().optional(),\n\tname: z.string().trim().min(1).max(100),\n\tdescription: z.string().trim().max(1000).nullable(),\n\t/** Prize photo key. Omitted keeps the stored photo; null clears it. */\n\timageKey: z.string().max(2048).nullable().optional(),\n\tstock: z.number().int().min(0),\n\t/** Omitted on update keeps the stored cost; omitted on create means 0. */\n\tstampCost: z\n\t\t.number()\n\t\t.int()\n\t\t.min(0)\n\t\t.max(PASSPORT_PRIZE_STAMP_COST_MAX)\n\t\t.optional(),\n\torder: z.number().int().min(0),\n});\n\n/**\n * Generated once per redemption attempt and reused when it is retried, so a\n * repeat after a lost response returns the first redemption instead of\n * redeeming or awarding the station stamp again.\n */\nexport const passportRedemptionRequestIdSchema = z.uuid();\n\nexport const redeemPassportPrizeSchema = passportEventIdSchema.extend({\n\tparticipantId: z.string().min(1),\n\tprizeId: z.string().min(1),\n\tquantity: z\n\t\t.number()\n\t\t.int()\n\t\t.min(1)\n\t\t.max(PASSPORT_REDEMPTION_QUANTITY_MAX)\n\t\t.default(1),\n\t/**\n\t * A station that opted in to prize-desk awards whose stamp the guest also\n\t * receives with this redemption. Omitted awards no stamp.\n\t */\n\tawardStationId: z.string().min(1).optional(),\n\t/** Manual bonus for the whole handover, removed on reversal. */\n\tbonusStamps: passportBonusStampsSchema.default(0),\n\trequestId: passportRedemptionRequestIdSchema.optional(),\n});\n\n/** Station category, falling back to GAME for legacy and unset configs. */\nexport const passportStationCategory = (\n\tconfig: { category?: PassportStationCategory } | null,\n): PassportStationCategory => config?.category ?? \"GAME\";\n\n/**\n * Default name of the passport's bingo game. Organisers rename the game by\n * renaming its Bingo station; it is still stored as Human Bingo.\n */\nexport const PASSPORT_BINGO_DEFAULT_NAME = \"Human Bingo\";\n\n/** The bingo game's display name: the Bingo station's name, or the default. */\nexport const passportBingoName = (stationName: string | null | undefined) =>\n\tstationName?.trim() || PASSPORT_BINGO_DEFAULT_NAME;\n\n/**\n * Whether crew can award this station's stamp at the prize desk. Absent reads\n * as false. Hidden stations may be opted in; archived ones never qualify (the\n * caller filters those out).\n */\nexport const passportStationPrizeDeskAward = (\n\tconfig: { prizeDeskAward?: boolean } | null,\n) => config?.prizeDeskAward ?? false;\n\n/** Station stamp value, falling back to 1 for legacy and unset configs. */\nexport const passportStationStampValue = (\n\tconfig: { stampValue?: number } | null,\n) => config?.stampValue ?? 1;\n", "import { z } from \"zod\";\nimport {\n\tPASSPORT_STAFF_ID_LABEL_DEFAULT,\n\tpassportEventIdSchema,\n} from \"./passport-input.schema\";\n\nexport const PASSPORT_ROSTER_STAFF_ID_MAX = 64;\nexport const PASSPORT_ROSTER_NAME_MAX = 100;\nexport const PASSPORT_ROSTER_IMPORT_MAX = 20_000;\nexport const PASSPORT_ROSTER_PAGE_MAX = 100;\n\n/**\n * Comparison key for a Staff ID or last name: case-insensitive, ignoring\n * whitespace, punctuation and accents. \"O'Brien-Lee\" and \"obrien lee\" match.\n */\nexport const normalizePassportRosterKey = (value: string) =>\n\tvalue\n\t\t.normalize(\"NFKD\")\n\t\t.replace(/\\p{M}/gu, \"\")\n\t\t.toLocaleLowerCase(\"en\")\n\t\t.replace(/[^\\p{L}\\p{N}]/gu, \"\");\n\n/**\n * Passport name for a roster entry with no display or last name. It is shown on\n * Lucky Draw screens and a Staff ID can be the only sign-in secret, so at most\n * the last third of the key sign-in actually compares (three characters at\n * most) is revealed. Punctuation and spaces in the ID do not count.\n */\nexport const passportStaffFallbackName = (staffId: string) => {\n\t// Spread by code point so a character outside the BMP is never split in two.\n\tconst key = [...normalizePassportRosterKey(staffId)];\n\tconst visible = Math.min(3, Math.floor(key.length / 3));\n\treturn visible > 0\n\t\t? `Staff ••••${key.slice(-visible).join(\"\").toLocaleUpperCase(\"en\")}`\n\t\t: \"Staff member\";\n};\n\nconst rosterStaffIdSchema = z\n\t.string()\n\t.trim()\n\t.min(1, \"Enter an ID.\")\n\t.max(PASSPORT_ROSTER_STAFF_ID_MAX)\n\t.refine((value) => normalizePassportRosterKey(value) !== \"\", {\n\t\tmessage: \"The ID needs at least one letter or digit.\",\n\t});\nconst rosterLastNameSchema = z\n\t.string()\n\t.trim()\n\t.min(1, \"Enter a last name.\")\n\t.max(PASSPORT_ROSTER_NAME_MAX)\n\t.refine((value) => normalizePassportRosterKey(value) !== \"\", {\n\t\tmessage: \"Last name needs at least one letter or digit.\",\n\t});\n\n/** Blank means no last name. Whether one is needed depends on the event's settings. */\nconst rosterOptionalLastNameSchema = z\n\t.string()\n\t.trim()\n\t.max(PASSPORT_ROSTER_NAME_MAX)\n\t.nullable()\n\t.transform((value) => value || null)\n\t.refine(\n\t\t(value) => value === null || normalizePassportRosterKey(value) !== \"\",\n\t\t{ message: \"Last name needs at least one letter or digit.\" },\n\t);\n\n/** The event's settings decide whether `lastName` is required and checked. */\nexport const passportStaffIdSignInSchema = passportEventIdSchema\n\t.extend({\n\t\tstaffId: rosterStaffIdSchema,\n\t\tlastName: rosterLastNameSchema.optional(),\n\t})\n\t.strict();\n\nexport const passportRosterEntrySchema = passportEventIdSchema\n\t.extend({\n\t\tid: z.string().min(1).optional(),\n\t\tstaffId: rosterStaffIdSchema,\n\t\tlastName: rosterOptionalLastNameSchema,\n\t\tdisplayName: z\n\t\t\t.string()\n\t\t\t.trim()\n\t\t\t.max(PASSPORT_ROSTER_NAME_MAX)\n\t\t\t.nullable()\n\t\t\t.transform((value) => value || null),\n\t})\n\t.strict();\n\nexport const passportRosterEntryIdSchema = passportEventIdSchema\n\t.extend({ entryId: z.string().min(1) })\n\t.strict();\n\nexport const passportRosterListSchema = passportEventIdSchema\n\t.extend({\n\t\tsearch: z.string().trim().max(200).optional(),\n\t\tlimit: z.number().int().min(1).max(PASSPORT_ROSTER_PAGE_MAX).default(25),\n\t\tcursor: z.string().min(1).max(8192).nullish(),\n\t\t// tRPC infinite queries always send the fetch direction; this list only pages forward.\n\t\tdirection: z.literal(\"forward\").optional(),\n\t})\n\t.strict();\n\nexport const passportRosterCountsSchema = passportEventIdSchema\n\t.extend({ search: z.string().trim().max(200).optional() })\n\t.strict();\n\n/** One mapped spreadsheet row. `row` is the 1-based row number in the file. */\nexport const passportRosterImportRowSchema = z\n\t.object({\n\t\trow: z.number().int().min(1),\n\t\tstaffId: z.string().max(1000),\n\t\tlastName: z.string().max(1000),\n\t\tdisplayName: z.string().max(1000).nullable(),\n\t})\n\t.strict();\nexport type PassportRosterImportRow = z.infer<\n\ttypeof passportRosterImportRowSchema\n>;\n\nexport const importPassportRosterSchema = passportEventIdSchema\n\t.extend({\n\t\trows: z\n\t\t\t.array(passportRosterImportRowSchema)\n\t\t\t.max(\n\t\t\t\tPASSPORT_ROSTER_IMPORT_MAX,\n\t\t\t\t`A roster can have at most ${PASSPORT_ROSTER_IMPORT_MAX} rows.`,\n\t\t\t),\n\t})\n\t.strict();\n\nexport const PASSPORT_ROSTER_REJECT_REASONS = [\n\t\"MISSING_STAFF_ID\",\n\t\"MISSING_LAST_NAME\",\n\t\"DUPLICATE_STAFF_ID\",\n\t\"TOO_LONG\",\n] as const;\nexport type PassportRosterRejectReason =\n\t(typeof PASSPORT_ROSTER_REJECT_REASONS)[number];\n\n/** Why a row was rejected, naming the identifier as the event does. */\nexport const passportRosterRejectReasonLabels = (\n\tstaffIdLabel: string,\n): Record<PassportRosterRejectReason, string> => ({\n\tMISSING_STAFF_ID: `The ${staffIdLabel} is blank`,\n\tMISSING_LAST_NAME: \"Last name is blank\",\n\tDUPLICATE_STAFF_ID: `The ${staffIdLabel} appears earlier in the file`,\n\tTOO_LONG: `The ${staffIdLabel} is over ${PASSPORT_ROSTER_STAFF_ID_MAX} characters or a name is over ${PASSPORT_ROSTER_NAME_MAX}`,\n});\n\n/** The reasons worded with the default identifier label. */\nexport const passportRosterRejectReasonLabel = passportRosterRejectReasonLabels(\n\tPASSPORT_STAFF_ID_LABEL_DEFAULT,\n);\n\nexport interface PreparedPassportRosterEntry {\n\tstaffId: string;\n\tstaffIdKey: string;\n\tlastName: string | null;\n\tlastNameKey: string | null;\n\tdisplayName: string | null;\n}\n\nexport interface PassportRosterRejectedRow {\n\trow: number;\n\tstaffId: string;\n\treason: PassportRosterRejectReason;\n}\n\nconst rejectReason = (\n\tstaffId: string,\n\tlastName: string,\n\tdisplayName: string | null,\n\trequireLastName: boolean,\n): PassportRosterRejectReason | null => {\n\tif (normalizePassportRosterKey(staffId) === \"\") return \"MISSING_STAFF_ID\";\n\tif (requireLastName && normalizePassportRosterKey(lastName) === \"\")\n\t\treturn \"MISSING_LAST_NAME\";\n\tif (\n\t\tstaffId.length > PASSPORT_ROSTER_STAFF_ID_MAX ||\n\t\tlastName.length > PASSPORT_ROSTER_NAME_MAX ||\n\t\t(displayName?.length ?? 0) > PASSPORT_ROSTER_NAME_MAX\n\t)\n\t\treturn \"TOO_LONG\";\n\treturn null;\n};\n\n/**\n * Validates mapped rows into roster entries. Blank or over-long rows are\n * rejected; a Staff ID repeated later in the file keeps its first row. A blank\n * last name is only rejected when the event requires one.\n */\nexport const preparePassportRosterImport = (\n\trows: readonly PassportRosterImportRow[],\n\t{ requireLastName }: { requireLastName: boolean },\n) => {\n\tconst entries: PreparedPassportRosterEntry[] = [];\n\tconst rejected: PassportRosterRejectedRow[] = [];\n\tconst seen = new Set<string>();\n\tfor (const row of rows) {\n\t\tconst staffId = row.staffId.trim();\n\t\tconst lastName = row.lastName.trim();\n\t\tconst displayName = row.displayName?.trim() || null;\n\t\tconst reason = rejectReason(\n\t\t\tstaffId,\n\t\t\tlastName,\n\t\t\tdisplayName,\n\t\t\trequireLastName,\n\t\t);\n\t\tif (reason) {\n\t\t\trejected.push({ row: row.row, staffId, reason });\n\t\t\tcontinue;\n\t\t}\n\t\tconst staffIdKey = normalizePassportRosterKey(staffId);\n\t\tif (seen.has(staffIdKey)) {\n\t\t\trejected.push({ row: row.row, staffId, reason: \"DUPLICATE_STAFF_ID\" });\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(staffIdKey);\n\t\tconst lastNameKey = normalizePassportRosterKey(lastName) || null;\n\t\tentries.push({\n\t\t\tstaffId,\n\t\t\tstaffIdKey,\n\t\t\tlastName: lastNameKey ? lastName : null,\n\t\t\tlastNameKey,\n\t\t\tdisplayName,\n\t\t});\n\t}\n\treturn { entries, rejected };\n};\n\nexport const PASSPORT_ROSTER_SURNAME_POSITIONS = [\"last\", \"first\"] as const;\nexport type PassportRosterSurnamePosition =\n\t(typeof PASSPORT_ROSTER_SURNAME_POSITIONS)[number];\n\n/** Zero-based column indexes. Map `lastName`, or `fullName` to derive it. */\nexport interface PassportRosterColumnMapping {\n\tstaffId: number;\n\tlastName: number | null;\n\tfullName: number | null;\n\t/** Defaults to the full-name column when unset. */\n\tdisplayName: number | null;\n\t/** Which word of the full name is the last name. */\n\tsurnamePosition: PassportRosterSurnamePosition;\n}\n\nconst cell = (row: readonly string[], index: number | null) =>\n\tindex === null ? \"\" : (row[index] ?? \"\").trim();\n\nconst surnameOf = (\n\tfullName: string,\n\tposition: PassportRosterSurnamePosition,\n) => {\n\tconst words = fullName.split(/\\s+/).filter(Boolean);\n\treturn (position === \"first\" ? words[0] : words.at(-1)) ?? \"\";\n};\n\n/** Throws a readable error when the mapping cannot produce a required last name. */\nexport const assertPassportRosterMapping = (\n\tmapping: PassportRosterColumnMapping,\n\tcolumnCount: number,\n\trequireLastName: boolean,\n) => {\n\tconst columns = [\n\t\tmapping.staffId,\n\t\tmapping.lastName,\n\t\tmapping.fullName,\n\t\tmapping.displayName,\n\t];\n\tif (\n\t\tcolumns.some(\n\t\t\t(index) =>\n\t\t\t\tindex !== null &&\n\t\t\t\t(!Number.isInteger(index) || index < 0 || index >= columnCount),\n\t\t)\n\t)\n\t\tthrow new Error(\"A mapped column is not in the file.\");\n\tif (requireLastName && mapping.lastName === null && mapping.fullName === null)\n\t\tthrow new Error(\"Map a Last Name column or a Full Name column.\");\n};\n\n/**\n * Maps a parsed table (header row first) to import rows. Fully empty lines\n * are skipped; everything else goes to the server, which reports rejects.\n */\nexport const mapPassportRosterTable = (\n\ttable: readonly (readonly string[])[],\n\tmapping: PassportRosterColumnMapping,\n\t{ requireLastName }: { requireLastName: boolean },\n): PassportRosterImportRow[] => {\n\tassertPassportRosterMapping(mapping, table[0]?.length ?? 0, requireLastName);\n\tconst rows: PassportRosterImportRow[] = [];\n\ttable.slice(1).forEach((row, index) => {\n\t\tif (row.every((value) => value.trim() === \"\")) return;\n\t\tconst fullName = cell(row, mapping.fullName);\n\t\tconst lastName =\n\t\t\tmapping.lastName === null\n\t\t\t\t? surnameOf(fullName, mapping.surnamePosition)\n\t\t\t\t: cell(row, mapping.lastName);\n\t\tconst displayName =\n\t\t\tcell(row, mapping.displayName ?? mapping.fullName) || null;\n\t\trows.push({\n\t\t\trow: index + 2,\n\t\t\tstaffId: cell(row, mapping.staffId),\n\t\t\tlastName,\n\t\t\tdisplayName,\n\t\t});\n\t});\n\t// Refuse rather than import a prefix: an import replaces the whole roster.\n\tif (rows.length > PASSPORT_ROSTER_IMPORT_MAX) {\n\t\tthrow new Error(\n\t\t\t`This file has ${rows.length.toLocaleString(\"en-US\")} rows with data. A roster can have at most ${PASSPORT_ROSTER_IMPORT_MAX.toLocaleString(\"en-US\")}. Split the file or remove rows you do not need.`,\n\t\t);\n\t}\n\treturn rows;\n};\n\nconst headerPatterns = {\n\tstaffId:\n\t\t/^(staff|employee|emp|personnel|badge|worker)[\\s_-]*(id|no|number|#|code)?$|^(staff|employee)$|^id$/,\n\tlastName: /^(last[\\s_-]*name|surname|family[\\s_-]*name|lname)$/,\n\tfullName: /^(full[\\s_-]*name|name|staff[\\s_-]*name|employee[\\s_-]*name)$/,\n\tdisplayName: /^(display[\\s_-]*name|preferred[\\s_-]*name|nickname)$/,\n} as const;\n\n/** Best-effort column guess from header labels. */\nexport const guessPassportRosterMapping = (\n\theaders: readonly string[],\n): PassportRosterColumnMapping => {\n\tconst find = (pattern: RegExp) => {\n\t\tconst index = headers.findIndex((header) =>\n\t\t\tpattern.test(header.trim().toLowerCase()),\n\t\t);\n\t\treturn index === -1 ? null : index;\n\t};\n\treturn {\n\t\tstaffId: find(headerPatterns.staffId) ?? 0,\n\t\tlastName: find(headerPatterns.lastName),\n\t\tfullName: find(headerPatterns.fullName),\n\t\tdisplayName: find(headerPatterns.displayName),\n\t\tsurnamePosition: \"last\",\n\t};\n};\n", "import { z } from \"zod\";\nimport {\n\tpassportBonusStampsSchema,\n\tpassportEventIdSchema,\n\tpassportRedemptionRequestIdSchema,\n\tpassportStationIdSchema,\n} from \"./passport-input.schema\";\nimport { PASSPORT_ROSTER_STAFF_ID_MAX } from \"./passport-roster.schema\";\n\nexport const PASSPORT_STATION_PASSWORD_MIN = 6;\nexport const PASSPORT_STATION_PASSWORD_MAX = 128;\nexport const PASSPORT_STATION_RECIPIENTS_PAGE_MAX = 100;\n\n/** Shared station password. Not trimmed: spaces are part of a password, but edge spaces are almost always a paste slip. */\nexport const stationStaffPasswordSchema = z\n\t.string()\n\t.min(\n\t\tPASSPORT_STATION_PASSWORD_MIN,\n\t\t`Use at least ${PASSPORT_STATION_PASSWORD_MIN} characters.`,\n\t)\n\t.max(\n\t\tPASSPORT_STATION_PASSWORD_MAX,\n\t\t`Use at most ${PASSPORT_STATION_PASSWORD_MAX} characters.`,\n\t)\n\t.refine((value) => value === value.trim(), {\n\t\tmessage: \"Remove the spaces at the start or end of the password.\",\n\t});\n\nexport const signInToStationStaffSchema = passportEventIdSchema\n\t.extend({ password: z.string().min(1).max(PASSPORT_STATION_PASSWORD_MAX) })\n\t.strict();\n\nexport const setPassportStationPasswordSchema = passportEventIdSchema\n\t.extend({ password: stationStaffPasswordSchema })\n\t.strict();\n\nconst participantCodeSchema = z.string().min(1).max(2048);\n\n/**\n * The participant station staff are about to stamp: the QR from their My QR,\n * or, when it cannot be scanned, the Staff ID shown under their name.\n */\nexport const stationStaffParticipantSchema = z.union([\n\tpassportStationIdSchema.extend({\n\t\tprofileCode: participantCodeSchema,\n\t\tsite: z.string().trim().min(1).max(60).optional(),\n\t}),\n\tpassportStationIdSchema.extend({\n\t\tstaffId: z.string().trim().min(1).max(PASSPORT_ROSTER_STAFF_ID_MAX),\n\t\tsite: z.string().trim().min(1).max(60).optional(),\n\t}),\n]);\n\n/**\n * A guest at the prize desk: the QR from their My QR, or the Staff ID shown\n * under their name when it cannot be scanned.\n */\nexport const stationPrizeClaimParticipantSchema = z.union([\n\tpassportEventIdSchema.extend({ profileCode: participantCodeSchema }),\n\tpassportEventIdSchema.extend({\n\t\tstaffId: z.string().trim().min(1).max(PASSPORT_ROSTER_STAFF_ID_MAX),\n\t}),\n]);\n\n/** Station crew hand over one prize; the code is the fresh one from the claim preview. */\nexport const redeemPrizeAsStationStaffSchema = passportEventIdSchema\n\t.extend({\n\t\tprofileCode: participantCodeSchema,\n\t\tprizeId: z.string().min(1),\n\t\t/** A prize-desk station whose stamp the crew also award; omitted awards none. */\n\t\tawardStationId: z.string().min(1).optional(),\n\t\tbonusStamps: passportBonusStampsSchema.default(0),\n\t\t/** One per desk submission, reused when it is retried. */\n\t\trequestId: passportRedemptionRequestIdSchema.optional(),\n\t})\n\t.strict();\n\nconst stationStampRecipientFiltersSchema = z\n\t.object({ search: z.string().trim().max(200).optional() })\n\t.strict();\n\n/** Strict cursor page input. `backward` needs a cursor. */\nexport const passportStationStampRecipientsSchema = passportStationIdSchema\n\t.extend({\n\t\tfilters: stationStampRecipientFiltersSchema.default({}),\n\t\tlimit: z\n\t\t\t.number()\n\t\t\t.int()\n\t\t\t.min(1)\n\t\t\t.max(PASSPORT_STATION_RECIPIENTS_PAGE_MAX)\n\t\t\t.default(25),\n\t\tcursor: z.string().min(1).max(8192).nullish(),\n\t\tdirection: z.enum([\"forward\", \"backward\"]).default(\"forward\"),\n\t})\n\t.strict()\n\t.refine((input) => input.direction === \"forward\" || Boolean(input.cursor), {\n\t\tmessage: \"A backward page needs a cursor.\",\n\t\tpath: [\"cursor\"],\n\t});\n\n/** Counts take only the filters: no cursor, limit or direction. */\nexport const passportStationStampRecipientCountsSchema = passportStationIdSchema\n\t.extend({ filters: stationStampRecipientFiltersSchema.default({}) })\n\t.strict();\n", "import { readFile } from \"node:fs/promises\";\nimport { basename } from \"node:path\";\nimport {\n\ttype EventPassportUploadKind,\n\tgetEventPassportUploadBaseFolder,\n\tMAX_EVENT_IMAGE_UPLOAD_BYTES,\n} from \"@go-labs/event-tech-utils/lib/event-s3-upload\";\nimport { resolvePassportSkinSettingsFromAppearance } from \"@go-labs/event-tech-utils/lib/passport-skin\";\nimport {\n\tDEFAULT_EVENT_APPEARANCE,\n\tDEFAULT_PASSPORT_SKIN,\n\ttype EventAppearance,\n\teventAppearanceSchema,\n\ttype PassportSkinSettings,\n\tpassportSkinSchema,\n} from \"@go-labs/event-tech-validators/event-appearance.schema\";\nimport { api } from \"@go-labs-sg/event-tech/api-client\";\nimport { CliUsageError } from \"@go-labs-sg/event-tech/runtime\";\n\ntype Flags = ReadonlyMap<string, string | true>;\n\nconst IMAGE_CONTENT_TYPES = [\n\t\"image/jpeg\",\n\t\"image/png\",\n\t\"image/webp\",\n\t\"image/gif\",\n] as const;\n\nconst PASSPORT_SKIN_UPLOAD_KINDS = [\"hero\", \"logo\"] as const;\n\nconst requiredValue = (flags: Flags, name: string) => {\n\tconst value = flags.get(name);\n\tif (typeof value !== \"string\" || value === \"\")\n\t\tthrow new CliUsageError(`--${name} is required and needs a value.`);\n\treturn value;\n};\n\nconst nonnegativeInteger = (value: string, name: string) => {\n\tconst parsed = Number(value);\n\tif (!/^\\d+$/.test(value) || !Number.isSafeInteger(parsed))\n\t\tthrow new CliUsageError(`--${name} must be a non-negative whole number.`);\n\treturn parsed;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst parseJsonRecord = (raw: string, name: string) => {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch {\n\t\tthrow new CliUsageError(`--${name} must be valid JSON.`);\n\t}\n\tif (!isRecord(parsed))\n\t\tthrow new CliUsageError(`--${name} must be a JSON object.`);\n\treturn parsed;\n};\n\n/**\n * Applies a merge patch to the stored skin. `null` clears the hero or logo, an\n * object merges into the stored value, and omitted keys stay as they are.\n */\nconst mergeSkinPatch = (\n\tcurrent: PassportSkinSettings,\n\tpatch: Record<string, unknown>,\n): PassportSkinSettings => {\n\tconst allowed = [\"heroImage\", \"logo\", \"colors\", \"emphasis\"];\n\tif (Object.keys(patch).some((key) => !allowed.includes(key)))\n\t\tthrow new CliUsageError(\n\t\t\t`--skin-json supports only: ${allowed.join(\", \")}.`,\n\t\t);\n\tconst merged = {\n\t\theroImage:\n\t\t\tpatch.heroImage === undefined\n\t\t\t\t? current.heroImage\n\t\t\t\t: isRecord(patch.heroImage)\n\t\t\t\t\t? { ...current.heroImage, ...patch.heroImage }\n\t\t\t\t\t: patch.heroImage,\n\t\tlogo:\n\t\t\tpatch.logo === undefined\n\t\t\t\t? current.logo\n\t\t\t\t: isRecord(patch.logo)\n\t\t\t\t\t? { ...current.logo, ...patch.logo }\n\t\t\t\t\t: patch.logo,\n\t\tcolors: isRecord(patch.colors)\n\t\t\t? { ...current.colors, ...patch.colors }\n\t\t\t: (patch.colors ?? current.colors),\n\t\temphasis: patch.emphasis ?? current.emphasis,\n\t};\n\tconst parsed = passportSkinSchema.safeParse(merged);\n\tif (!parsed.success)\n\t\tthrow new CliUsageError(\n\t\t\t`Invalid passport skin: ${parsed.error.issues\n\t\t\t\t.map((issue) => `${issue.path.join(\".\") || \"skin\"}: ${issue.message}`)\n\t\t\t\t.join(\"; \")}`,\n\t\t);\n\treturn parsed.data;\n};\n\nconst readCanonicalAppearance = async (eventId: string) => {\n\tconst projection = await api.event.getEventAppearance.query({ eventId });\n\tconst appearance = eventAppearanceSchema.parse(\n\t\tprojection.appearance ?? DEFAULT_EVENT_APPEARANCE,\n\t);\n\treturn { projection, appearance };\n};\n\nconst getPassportSkin = async (eventId: string) => {\n\tconst { projection, appearance } = await readCanonicalAppearance(eventId);\n\treturn {\n\t\tappearanceVersion: projection.appearanceVersion,\n\t\thasCustomAppearance: projection.hasCustomAppearance,\n\t\tpassport: resolvePassportSkinSettingsFromAppearance(appearance),\n\t\tpassportHeroImageUrl: projection.passportHeroImageUrl,\n\t\tpassportLogoUrl: projection.passportLogoUrl,\n\t};\n};\n\nconst saveSkin = async (\n\teventId: string,\n\tappearanceVersion: number,\n\tbuildSkin: (current: PassportSkinSettings) => PassportSkinSettings,\n) => {\n\tconst { projection, appearance } = await readCanonicalAppearance(eventId);\n\tif (projection.appearanceVersion !== appearanceVersion)\n\t\tthrow new CliUsageError(\n\t\t\t`The appearance is at version ${projection.appearanceVersion}, not ${appearanceVersion}. Read it with \\`et passport skin get\\` and retry.`,\n\t\t);\n\tconst next: EventAppearance = {\n\t\t...appearance,\n\t\tpassport: buildSkin(resolvePassportSkinSettingsFromAppearance(appearance)),\n\t};\n\treturn api.event.updateEventAppearance.mutate({\n\t\teventId,\n\t\tappearance: next,\n\t\tappearanceVersion,\n\t});\n};\n\nconst isUploadKind = <Kind extends EventPassportUploadKind>(\n\tkinds: readonly Kind[],\n\tvalue: string,\n): value is Kind => kinds.some((kind) => kind === value);\n\nconst uploadPassportImage = async (\n\teventId: string,\n\tkind: EventPassportUploadKind,\n\tflags: Flags,\n) => {\n\tconst filePath = requiredValue(flags, \"file\");\n\tconst contentType = requiredValue(flags, \"content-type\");\n\tif (!IMAGE_CONTENT_TYPES.some((allowed) => allowed === contentType))\n\t\tthrow new CliUsageError(\n\t\t\t`--content-type must be one of: ${IMAGE_CONTENT_TYPES.join(\", \")}.`,\n\t\t);\n\tconst file = await readFile(filePath);\n\tif (file.byteLength > MAX_EVENT_IMAGE_UPLOAD_BYTES)\n\t\tthrow new CliUsageError(\"The image must be 25 MB or smaller.\");\n\tconst signed = await api.attachment.getPresignedUrlToUpload.mutate({\n\t\tfolder: getEventPassportUploadBaseFolder(kind),\n\t\tfileName: basename(filePath),\n\t\tcontentType,\n\t\tsize: file.byteLength,\n\t\teventId,\n\t});\n\tconst uploadResponse = await fetch(signed.uploadUrl, {\n\t\tmethod: \"PUT\",\n\t\theaders: { \"content-type\": contentType },\n\t\tbody: file,\n\t});\n\tif (!uploadResponse.ok)\n\t\tthrow new Error(\n\t\t\t`Passport image upload failed with HTTP ${uploadResponse.status}.`,\n\t\t);\n\treturn signed;\n};\n\n/** Passport skin commands: `skin get|set|clear|upload`. */\nconst createSkinOperation = (\n\tsubcommand: string,\n\t{ eventId, flags, allowed }: MediaContext,\n): (() => Promise<unknown>) | null => {\n\tswitch (subcommand) {\n\t\tcase \"get\":\n\t\t\treturn () => getPassportSkin(eventId);\n\t\tcase \"set\": {\n\t\t\tallowed.push(\"appearance-version\", \"skin-json\");\n\t\t\tconst version = nonnegativeInteger(\n\t\t\t\trequiredValue(flags, \"appearance-version\"),\n\t\t\t\t\"appearance-version\",\n\t\t\t);\n\t\t\tconst patch = parseJsonRecord(\n\t\t\t\trequiredValue(flags, \"skin-json\"),\n\t\t\t\t\"skin-json\",\n\t\t\t);\n\t\t\treturn () =>\n\t\t\t\tsaveSkin(eventId, version, (current) => mergeSkinPatch(current, patch));\n\t\t}\n\t\tcase \"clear\": {\n\t\t\tallowed.push(\"appearance-version\");\n\t\t\tconst version = nonnegativeInteger(\n\t\t\t\trequiredValue(flags, \"appearance-version\"),\n\t\t\t\t\"appearance-version\",\n\t\t\t);\n\t\t\treturn () => saveSkin(eventId, version, () => DEFAULT_PASSPORT_SKIN);\n\t\t}\n\t\tcase \"upload\": {\n\t\t\tallowed.push(\"kind\", \"file\", \"content-type\");\n\t\t\tconst kind = requiredValue(flags, \"kind\");\n\t\t\tif (!isUploadKind(PASSPORT_SKIN_UPLOAD_KINDS, kind))\n\t\t\t\tthrow new CliUsageError(\n\t\t\t\t\t`--kind must be one of: ${PASSPORT_SKIN_UPLOAD_KINDS.join(\", \")}.`,\n\t\t\t\t);\n\t\t\treturn () => uploadPassportImage(eventId, kind, flags);\n\t\t}\n\t\tdefault:\n\t\t\treturn null;\n\t}\n};\n\nconst setStationImage = async (\n\teventId: string,\n\tstationId: string,\n\timageKey: (() => Promise<string>) | null,\n) => {\n\tconst overview = await api.event.passport.getPassportOverview.query({\n\t\teventId,\n\t});\n\tconst station = overview.stations.find((item) => item.id === stationId);\n\tif (!station) throw new CliUsageError(\"Station not found for this event.\");\n\t// Omitting `collection` keeps the station's current mode and settings.\n\treturn api.event.passport.upsertPassportStation.mutate({\n\t\teventId,\n\t\tid: station.id,\n\t\tname: station.name,\n\t\tdescription: station.description,\n\t\tlocation: station.location,\n\t\timageKey: imageKey ? await imageKey() : null,\n\t\torder: station.order,\n\t\topensAt: station.opensAt,\n\t\tclosesAt: station.closesAt,\n\t});\n};\n\nconst setPrizeImage = async (\n\teventId: string,\n\tprizeId: string,\n\timageKey: (() => Promise<string>) | null,\n) => {\n\tconst overview = await api.event.passport.getPassportOverview.query({\n\t\teventId,\n\t});\n\tconst prize = overview.prizes.find((item) => item.id === prizeId);\n\tif (!prize) throw new CliUsageError(\"Prize not found for this event.\");\n\t// Name, description, stock, stamp cost and order are sent back unchanged.\n\treturn api.event.passport.upsertPassportPrize.mutate({\n\t\teventId,\n\t\tid: prize.id,\n\t\tname: prize.name,\n\t\tdescription: prize.description,\n\t\timageKey: imageKey ? await imageKey() : null,\n\t\tstock: prize.stock,\n\t\tstampCost: prize.stampCost,\n\t\torder: prize.order,\n\t});\n};\n\n/** Station and prize image commands: `station|prize image-set|image-clear`. */\nconst createImageOperation = (\n\tresource: \"station\" | \"prize\",\n\tsubcommand: string,\n\t{ eventId, flags, allowed }: MediaContext,\n): (() => Promise<unknown>) | null => {\n\tif (subcommand !== \"image-set\" && subcommand !== \"image-clear\") return null;\n\tconst idFlag = `${resource}-id`;\n\tallowed.push(idFlag);\n\tconst id = requiredValue(flags, idFlag);\n\tconst save = (imageKey: (() => Promise<string>) | null) =>\n\t\tresource === \"station\"\n\t\t\t? setStationImage(eventId, id, imageKey)\n\t\t\t: setPrizeImage(eventId, id, imageKey);\n\tif (subcommand === \"image-clear\") return () => save(null);\n\tallowed.push(\"file\", \"content-type\");\n\trequiredValue(flags, \"file\");\n\trequiredValue(flags, \"content-type\");\n\treturn () =>\n\t\tsave(async () => {\n\t\t\tconst signed = await uploadPassportImage(\n\t\t\t\teventId,\n\t\t\t\tresource === \"station\" ? \"stations\" : \"prizes\",\n\t\t\t\tflags,\n\t\t\t);\n\t\t\treturn signed.key;\n\t\t});\n};\n\ninterface MediaContext {\n\teventId: string;\n\tflags: Flags;\n\t/** Flags the command accepts; extended here so unknown flags are rejected. */\n\tallowed: string[];\n}\n\n/**\n * Resolves `passport skin ...` and `passport station|prize image-set|image-clear`.\n * Returns null for any other action so the caller reports an unknown command.\n */\nexport const createPassportMediaOperation = (\n\taction: string,\n\tcontext: MediaContext,\n): (() => Promise<unknown>) | null => {\n\tconst [first, second] = action.split(\" \");\n\tif (first === \"skin\" && second) return createSkinOperation(second, context);\n\tif ((first === \"station\" || first === \"prize\") && second)\n\t\treturn createImageOperation(first, second, context);\n\treturn null;\n};\n", "import { randomUUID } from \"node:crypto\";\n\nexport const MAX_EVENT_IMAGE_UPLOAD_BYTES = 25 * 1024 * 1024;\nexport const MAX_EVENT_VIDEO_UPLOAD_BYTES = 200 * 1024 * 1024;\nexport const MAX_HUMAN_BINGO_MEDIA_UPLOAD_BYTES = 1024 * 1024 * 1024;\nexport const MAX_EVENT_UPLOAD_BYTES = MAX_EVENT_VIDEO_UPLOAD_BYTES;\n\nconst SAFE_IMAGE_CONTENT_TYPES = [\n\t\"image/jpeg\",\n\t\"image/png\",\n\t\"image/webp\",\n\t\"image/gif\",\n] as const;\n\nconst VIDEO_CONTENT_TYPES = [\n\t\"video/mp4\",\n\t\"video/quicktime\",\n\t\"video/webm\",\n\t\"video/ogg\",\n] as const;\n\nconst EVENT_APPEARANCE_IMAGE_CONTENT_TYPES = [\n\t\"image/jpeg\",\n\t\"image/png\",\n\t\"image/webp\",\n\t\"image/gif\",\n] as const;\nconst EVENT_APPEARANCE_VIDEO_CONTENT_TYPES = [\n\t\"video/mp4\",\n\t\"video/webm\",\n] as const;\n\nexport const SAFE_EVENT_IMAGE_CONTENT_TYPES = [\n\t...SAFE_IMAGE_CONTENT_TYPES,\n] as const;\nexport const SAFE_EVENT_VIDEO_CONTENT_TYPES = [...VIDEO_CONTENT_TYPES] as const;\nexport const SAFE_EVENT_UPLOAD_CONTENT_TYPES = [\n\t...SAFE_IMAGE_CONTENT_TYPES,\n\t...VIDEO_CONTENT_TYPES,\n] as const;\n\nconst IMAGE_EXTENSIONS = [\"jpg\", \"jpeg\", \"png\", \"webp\", \"gif\"] as const;\nconst VIDEO_EXTENSIONS = [\"mp4\", \"mov\", \"webm\", \"ogg\"] as const;\n\nconst contentTypeByExtension = {\n\tjpg: \"image/jpeg\",\n\tjpeg: \"image/jpeg\",\n\tpng: \"image/png\",\n\twebp: \"image/webp\",\n\tgif: \"image/gif\",\n\tmp4: \"video/mp4\",\n\tmov: \"video/quicktime\",\n\twebm: \"video/webm\",\n\togg: \"video/ogg\",\n} as const;\n\nconst PUBLIC_UPLOAD_FOLDERS = [\n\t\"photo-wall/user-uploads\",\n\t\"signature-wall/user-uploads\",\n\t\"story-collection/user-uploads\",\n\t\"post-it-note/user-uploads\",\n] as const;\n\nconst AUTHENTICATED_UPLOAD_FOLDERS = [\n\t\"organization-images\",\n\t\"team-images\",\n\t\"default/backgrounds\",\n\t\"human-bingo/backgrounds\",\n\t\"human-bingo/mobile-backgrounds\",\n\t\"human-bingo/bingo-cell-images\",\n\t\"photo-wall/backgrounds\",\n\t\"signature-wall/backgrounds\",\n\t\"signature-wall/animation-videos\",\n\t\"story-collection/backgrounds\",\n\t\"rating-system/backgrounds\",\n\t\"rating-system/mobile-backgrounds\",\n\t\"rating-system/subjects\",\n\t\"lucky-draw/backgrounds\",\n\t\"post-it-note/backgrounds\",\n\t\"event-appearance/images\",\n\t\"event-appearance/videos\",\n\t\"event-passport/hero\",\n\t\"event-passport/logo\",\n\t\"event-passport/stations\",\n\t\"event-passport/prizes\",\n\t\"staff-redemption/backgrounds\",\n] as const;\n\nconst PARTICIPANT_AUTHENTICATED_UPLOAD_FOLDERS = [\n\t\"human-bingo/user-uploads\",\n] as const;\n\nconst EVENT_BACKGROUND_FOLDERS = [\n\t\"human-bingo/backgrounds\",\n\t\"human-bingo/mobile-backgrounds\",\n\t\"human-bingo/bingo-cell-images\",\n\t\"rating-system/backgrounds\",\n\t\"lucky-draw/backgrounds\",\n\t\"post-it-note/backgrounds\",\n\t\"event-appearance/images\",\n\t\"event-appearance/videos\",\n\t\"event-passport/hero\",\n\t\"event-passport/logo\",\n\t\"event-passport/stations\",\n\t\"event-passport/prizes\",\n] as const;\n\nconst MEDIA_USER_UPLOAD_FOLDERS = [\"human-bingo/user-uploads\"] as const;\n\nconst USER_UPLOAD_FOLDER_SUFFIX = \"/user-uploads\";\n\nconst hasControlCharacter = (value: string) =>\n\tArray.from(value).some((character) => {\n\t\tconst codePoint = character.codePointAt(0) ?? 0;\n\t\treturn codePoint <= 31 || codePoint === 127;\n\t});\n\nexport type EventUploadFolder =\n\t| (typeof PUBLIC_UPLOAD_FOLDERS)[number]\n\t| (typeof AUTHENTICATED_UPLOAD_FOLDERS)[number]\n\t| (typeof PARTICIPANT_AUTHENTICATED_UPLOAD_FOLDERS)[number];\n\nconst normalizeFolder = (folder: string) => {\n\tconst normalizedFolder = folder.replace(/^\\/+|\\/+$/g, \"\");\n\tif (\n\t\t!normalizedFolder ||\n\t\tnormalizedFolder.includes(\"..\") ||\n\t\tnormalizedFolder.includes(\"\\\\\") ||\n\t\thasControlCharacter(normalizedFolder)\n\t) {\n\t\tthrow new Error(\"Upload folder is not allowed\");\n\t}\n\treturn normalizedFolder;\n};\n\nexport const sanitizeUploadExtension = (fileName: string): string => {\n\tconst base = fileName.split(/[/\\\\]/).pop() ?? \"file\";\n\tconst lastDot = base.lastIndexOf(\".\");\n\tif (lastDot <= 0 || lastDot === base.length - 1) return \"bin\";\n\tconst ext = base\n\t\t.slice(lastDot + 1)\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9]/g, \"\");\n\treturn ext.slice(0, 10) || \"bin\";\n};\n\nconst isSignatureWallAnimationFolder = (folder: string) =>\n\tnormalizeFolder(folder) === \"signature-wall/animation-videos\";\n\nexport const isEventAppearanceImageFolder = (folder: string) => {\n\tconst normalized = normalizeFolder(folder);\n\treturn (\n\t\tnormalized === \"event-appearance/images\" ||\n\t\tnormalized.startsWith(\"event-appearance/images/\")\n\t);\n};\n\nexport const isEventAppearanceVideoFolder = (folder: string) => {\n\tconst normalized = normalizeFolder(folder);\n\treturn (\n\t\tnormalized === \"event-appearance/videos\" ||\n\t\tnormalized.startsWith(\"event-appearance/videos/\")\n\t);\n};\n\nexport const isEventAppearanceUploadFolder = (folder: string) =>\n\tisEventAppearanceImageFolder(folder) || isEventAppearanceVideoFolder(folder);\n\nexport const EVENT_PASSPORT_UPLOAD_KINDS = [\n\t\"hero\",\n\t\"logo\",\n\t\"stations\",\n\t\"prizes\",\n] as const;\nexport type EventPassportUploadKind =\n\t(typeof EVENT_PASSPORT_UPLOAD_KINDS)[number];\n\n/** Base folder (without event scope) for an Event Passport image kind. */\nexport const getEventPassportUploadBaseFolder = (\n\tkind: EventPassportUploadKind,\n) => `event-passport/${kind}` as const;\n\n/** The Event Passport kind a base or event-scoped folder belongs to, if any. */\nexport const getEventPassportUploadKind = (\n\tfolder: string,\n): EventPassportUploadKind | null => {\n\tconst normalized = normalizeFolder(folder);\n\treturn (\n\t\tEVENT_PASSPORT_UPLOAD_KINDS.find((kind) => {\n\t\t\tconst base = getEventPassportUploadBaseFolder(kind);\n\t\t\treturn normalized === base || normalized.startsWith(`${base}/`);\n\t\t}) ?? null\n\t);\n};\n\nexport const isEventPassportUploadFolder = (folder: string) =>\n\tgetEventPassportUploadKind(folder) !== null;\n\nconst isMediaUserUploadFolder = (folder: string) => {\n\tconst normalized = normalizeFolder(folder);\n\treturn MEDIA_USER_UPLOAD_FOLDERS.some(\n\t\t(allowedFolder) =>\n\t\t\tnormalized === allowedFolder ||\n\t\t\tnormalized.startsWith(`${allowedFolder}/`),\n\t);\n};\n\nexport const getAllowedEventUploadContentTypes = (folder: string) =>\n\tisEventAppearanceVideoFolder(folder)\n\t\t? EVENT_APPEARANCE_VIDEO_CONTENT_TYPES\n\t\t: isEventAppearanceImageFolder(folder)\n\t\t\t? EVENT_APPEARANCE_IMAGE_CONTENT_TYPES\n\t\t\t: isSignatureWallAnimationFolder(folder)\n\t\t\t\t? SAFE_EVENT_VIDEO_CONTENT_TYPES\n\t\t\t\t: isMediaUserUploadFolder(folder)\n\t\t\t\t\t? SAFE_EVENT_UPLOAD_CONTENT_TYPES\n\t\t\t\t\t: SAFE_EVENT_IMAGE_CONTENT_TYPES;\n\nconst getMaxEventUploadSize = (folder: string, normalizedType: string) => {\n\tif (folder === \"human-bingo/user-uploads\") {\n\t\treturn MAX_HUMAN_BINGO_MEDIA_UPLOAD_BYTES;\n\t}\n\treturn normalizedType.startsWith(\"video/\")\n\t\t? MAX_EVENT_VIDEO_UPLOAD_BYTES\n\t\t: MAX_EVENT_IMAGE_UPLOAD_BYTES;\n};\n\nconst getAllowedEventUploadExtensions = (folder: string): readonly string[] => {\n\tif (isEventAppearanceVideoFolder(folder)) return [\"mp4\", \"webm\"];\n\tif (isEventAppearanceImageFolder(folder)) return IMAGE_EXTENSIONS;\n\tif (isSignatureWallAnimationFolder(folder)) return VIDEO_EXTENSIONS;\n\tif (isMediaUserUploadFolder(folder)) {\n\t\treturn [...IMAGE_EXTENSIONS, ...VIDEO_EXTENSIONS];\n\t}\n\treturn IMAGE_EXTENSIONS;\n};\n\nexport const assertAllowedEventUploadContent = ({\n\tfolder,\n\tfileName,\n\tcontentType,\n\tsize,\n}: {\n\tfolder: string;\n\tfileName: string;\n\tcontentType: string;\n\tsize: number;\n}) => {\n\tif (size <= 0) {\n\t\tthrow new Error(\"Upload size is not allowed\");\n\t}\n\n\tconst normalizedType = contentType.split(\";\")[0]?.trim().toLowerCase() ?? \"\";\n\tconst allowedTypes = getAllowedEventUploadContentTypes(folder);\n\tif (!allowedTypes.some((allowedType) => allowedType === normalizedType)) {\n\t\tthrow new Error(\"Upload content type is not allowed\");\n\t}\n\n\tconst maxSize = getMaxEventUploadSize(folder, normalizedType);\n\tif (size > maxSize) {\n\t\tthrow new Error(\"Upload size is not allowed\");\n\t}\n\n\tconst extension = sanitizeUploadExtension(fileName);\n\tconst allowedExtensions = getAllowedEventUploadExtensions(folder);\n\tif (\n\t\t!allowedExtensions.some(\n\t\t\t(allowedExtension) => allowedExtension === extension,\n\t\t)\n\t) {\n\t\tthrow new Error(\"Upload file extension is not allowed\");\n\t}\n\n\tconst expectedContentType =\n\t\tcontentTypeByExtension[extension as keyof typeof contentTypeByExtension];\n\tif (expectedContentType !== normalizedType) {\n\t\tthrow new Error(\"Upload file extension does not match content type\");\n\t}\n};\n\nexport const isSafeEventProxyImageContentType = (contentType: string) => {\n\tconst normalizedType = contentType.split(\";\")[0]?.trim().toLowerCase() ?? \"\";\n\treturn SAFE_IMAGE_CONTENT_TYPES.some(\n\t\t(allowedType) => allowedType === normalizedType,\n\t);\n};\n\nexport const isSafeEventProxyMediaContentType = (contentType: string) => {\n\tconst normalizedType = contentType.split(\";\")[0]?.trim().toLowerCase() ?? \"\";\n\treturn SAFE_EVENT_UPLOAD_CONTENT_TYPES.some(\n\t\t(allowedType) => allowedType === normalizedType,\n\t);\n};\n\nexport const isAuthenticatedUploadFolder = (folder: string) => {\n\tconst normalized = normalizeFolder(folder);\n\treturn AUTHENTICATED_UPLOAD_FOLDERS.some(\n\t\t(allowedFolder) =>\n\t\t\tnormalized === allowedFolder ||\n\t\t\tnormalized.startsWith(`${allowedFolder}/`),\n\t);\n};\n\nexport const isAllowedEventUploadFolder = (folder: string) => {\n\tconst normalized = normalizeFolder(folder);\n\tif (isAuthenticatedUploadFolder(normalized)) return true;\n\tif (\n\t\tPARTICIPANT_AUTHENTICATED_UPLOAD_FOLDERS.some(\n\t\t\t(allowedFolder) =>\n\t\t\t\tnormalized === allowedFolder ||\n\t\t\t\tnormalized.startsWith(`${allowedFolder}/`),\n\t\t)\n\t) {\n\t\treturn true;\n\t}\n\n\tif (\n\t\tPUBLIC_UPLOAD_FOLDERS.some(\n\t\t\t(allowedFolder) =>\n\t\t\t\tnormalized === allowedFolder ||\n\t\t\t\tnormalized.startsWith(`${allowedFolder}/`),\n\t\t)\n\t) {\n\t\treturn true;\n\t}\n\n\treturn false;\n};\n\nexport const isPublicUserUploadFolder = (folder: string) => {\n\tconst normalized = normalizeFolder(folder);\n\treturn PUBLIC_UPLOAD_FOLDERS.some(\n\t\t(allowedFolder) => normalized === allowedFolder,\n\t);\n};\n\nexport const isParticipantAuthenticatedUploadFolder = (folder: string) => {\n\tconst normalized = normalizeFolder(folder);\n\treturn PARTICIPANT_AUTHENTICATED_UPLOAD_FOLDERS.some(\n\t\t(allowedFolder) =>\n\t\t\tnormalized === allowedFolder ||\n\t\t\tnormalized.startsWith(`${allowedFolder}/`),\n\t);\n};\n\nexport const buildEventAppearanceUploadFolder = ({\n\teventId,\n\tmediaType,\n}: {\n\teventId: string;\n\tmediaType: \"image\" | \"video\";\n}) => {\n\tif (\n\t\t!eventId ||\n\t\teventId !== eventId.trim() ||\n\t\thasControlCharacter(eventId) ||\n\t\teventId.includes(\"/\") ||\n\t\teventId.includes(\"\\\\\") ||\n\t\teventId.includes(\"..\")\n\t) {\n\t\tthrow new Error(\"Event upload scope is not allowed\");\n\t}\n\treturn `event-appearance/${mediaType === \"image\" ? \"images\" : \"videos\"}/${eventId}`;\n};\n\nexport const assertAllowedEventAppearanceKey = ({\n\teventId,\n\tkey,\n\tmediaType,\n}: {\n\teventId: string;\n\tkey: string;\n\tmediaType: \"image\" | \"video\";\n}) => {\n\tconst expectedFolder = buildEventAppearanceUploadFolder({\n\t\teventId,\n\t\tmediaType,\n\t});\n\tif (!key.startsWith(`${expectedFolder}/`)) {\n\t\tthrow new Error(\"Appearance media key does not match event upload scope\");\n\t}\n\tconst fileName = key.slice(expectedFolder.length + 1);\n\t// Only the exact UUID filename issued by the upload endpoint is attachable.\n\tif (\n\t\t!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\\.[a-z0-9]+$/.test(\n\t\t\tfileName,\n\t\t)\n\t) {\n\t\tthrow new Error(\"Appearance media key is not allowed\");\n\t}\n\tconst extension = fileName.split(\".\")[1];\n\tconst allowedExtensions =\n\t\tmediaType === \"image\" ? IMAGE_EXTENSIONS : ([\"mp4\", \"webm\"] as const);\n\tif (!allowedExtensions.some((allowed) => allowed === extension)) {\n\t\tthrow new Error(\"Appearance media file type is not allowed\");\n\t}\n\treturn key;\n};\n\nconst assertSafeEventScope = (eventId: string) => {\n\tif (\n\t\t!eventId ||\n\t\teventId !== eventId.trim() ||\n\t\thasControlCharacter(eventId) ||\n\t\teventId.includes(\"/\") ||\n\t\teventId.includes(\"\\\\\") ||\n\t\teventId.includes(\"..\")\n\t) {\n\t\tthrow new Error(\"Event upload scope is not allowed\");\n\t}\n};\n\n/** `event-passport/<kind>/<eventId>`: the only folder a presigned passport upload may use. */\nexport const buildEventPassportUploadFolder = ({\n\teventId,\n\tkind,\n}: {\n\teventId: string;\n\tkind: EventPassportUploadKind;\n}) => {\n\tassertSafeEventScope(eventId);\n\treturn `${getEventPassportUploadBaseFolder(kind)}/${eventId}`;\n};\n\n/**\n * A newly attached passport image key must be an exact UUID filename issued by\n * the upload endpoint, inside this event's folder for that kind.\n */\nexport const assertAllowedEventPassportKey = ({\n\teventId,\n\tkey,\n\tkind,\n}: {\n\teventId: string;\n\tkey: string;\n\tkind: EventPassportUploadKind;\n}) => {\n\tconst expectedFolder = buildEventPassportUploadFolder({ eventId, kind });\n\tif (!key.startsWith(`${expectedFolder}/`)) {\n\t\tthrow new Error(\"Passport image key does not match event upload scope\");\n\t}\n\tconst fileName = key.slice(expectedFolder.length + 1);\n\tif (\n\t\t!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\\.[a-z0-9]+$/.test(\n\t\t\tfileName,\n\t\t)\n\t) {\n\t\tthrow new Error(\"Passport image key is not allowed\");\n\t}\n\tconst extension = fileName.split(\".\")[1];\n\tif (!IMAGE_EXTENSIONS.some((allowed) => allowed === extension)) {\n\t\tthrow new Error(\"Passport image file type is not allowed\");\n\t}\n\treturn key;\n};\n\nexport const buildEventUploadKey = ({\n\tfolder,\n\tfileName,\n}: {\n\tfolder: string;\n\tfileName: string;\n}) => {\n\tconst normalizedFolder = normalizeFolder(folder);\n\tif (!isAllowedEventUploadFolder(normalizedFolder)) {\n\t\tthrow new Error(\"Upload folder is not allowed\");\n\t}\n\n\tconst ext = sanitizeUploadExtension(fileName);\n\treturn `${normalizedFolder}/${randomUUID()}.${ext}`;\n};\n\nexport const buildEventScopedPublicUploadFolder = ({\n\tfolder,\n\teventId,\n}: {\n\tfolder: string;\n\teventId: string;\n}) => {\n\tconst normalizedFolder = normalizeFolder(folder);\n\tconst normalizedEventId = eventId.trim();\n\tif (!normalizedEventId || hasControlCharacter(normalizedEventId)) {\n\t\tthrow new Error(\"Event upload scope is not allowed\");\n\t}\n\tif (\n\t\t!isPublicUserUploadFolder(normalizedFolder) &&\n\t\t!isParticipantAuthenticatedUploadFolder(normalizedFolder)\n\t) {\n\t\tthrow new Error(\"Public upload folder is not event-scoped\");\n\t}\n\n\treturn `${normalizedFolder}/${normalizedEventId}`;\n};\n\nexport const buildHumanBingoParticipantUploadFolder = ({\n\teventId,\n\tparticipantId,\n}: {\n\teventId: string;\n\tparticipantId: string;\n}) => {\n\tconst normalizedParticipantId = participantId.trim();\n\tif (\n\t\t!normalizedParticipantId ||\n\t\thasControlCharacter(normalizedParticipantId) ||\n\t\tnormalizedParticipantId.includes(\"/\") ||\n\t\tnormalizedParticipantId.includes(\"..\")\n\t) {\n\t\tthrow new Error(\"Participant upload scope is not allowed\");\n\t}\n\n\treturn `${buildEventScopedPublicUploadFolder({\n\t\teventId,\n\t\tfolder: \"human-bingo/user-uploads\",\n\t})}/${normalizedParticipantId}`;\n};\n\ntype PublicEventSubmissionMediaType = \"image\" | \"video\" | \"imageOrVideo\";\n\nconst assertAllowedSubmissionExtension = (\n\tkey: string,\n\tmediaType: PublicEventSubmissionMediaType,\n) => {\n\tconst extension = sanitizeUploadExtension(key);\n\tconst allowedExtensions =\n\t\tmediaType === \"video\"\n\t\t\t? VIDEO_EXTENSIONS\n\t\t\t: mediaType === \"imageOrVideo\"\n\t\t\t\t? [...IMAGE_EXTENSIONS, ...VIDEO_EXTENSIONS]\n\t\t\t\t: IMAGE_EXTENSIONS;\n\n\tif (\n\t\t!allowedExtensions.some(\n\t\t\t(allowedExtension) => allowedExtension === extension,\n\t\t)\n\t) {\n\t\tthrow new Error(\"Submitted file type is not allowed\");\n\t}\n};\n\nexport const assertAllowedPublicEventSubmissionKey = ({\n\tkey,\n\teventId,\n\tfolder,\n\tmediaType = \"image\",\n}: {\n\tkey: string;\n\teventId: string;\n\tfolder: string;\n\tmediaType?: PublicEventSubmissionMediaType;\n}) => {\n\tconst normalizedKey = key.replace(/^\\/+/, \"\");\n\tconst expectedFolder = buildEventScopedPublicUploadFolder({\n\t\tfolder,\n\t\teventId,\n\t});\n\tif (!normalizedKey.startsWith(`${expectedFolder}/`)) {\n\t\tthrow new Error(\"Submitted file key does not match event upload scope\");\n\t}\n\n\tassertAllowedSubmissionExtension(normalizedKey, mediaType);\n\n\treturn assertAllowedS3ObjectKey(normalizedKey);\n};\n\nexport const assertAllowedPhotoWallSubmissionKey = ({\n\tkey,\n\teventId,\n}: {\n\tkey: string;\n\teventId: string;\n}) => {\n\tconst normalizedKey = assertAllowedPublicEventSubmissionKey({\n\t\tkey,\n\t\teventId,\n\t\tfolder: \"photo-wall/user-uploads\",\n\t});\n\tconst expectedFolder = buildEventScopedPublicUploadFolder({\n\t\tfolder: \"photo-wall/user-uploads\",\n\t\teventId,\n\t});\n\tconst fileName = normalizedKey.slice(expectedFolder.length + 1);\n\tif (\n\t\t!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\\.(?:jpg|jpeg|png|webp|gif)$/.test(\n\t\t\tfileName,\n\t\t)\n\t) {\n\t\tthrow new Error(\"Photo Wall submission key is not allowed\");\n\t}\n\treturn normalizedKey;\n};\n\nexport const assertAllowedHumanBingoSubmissionKey = ({\n\tkey,\n\teventId,\n\tmediaType = \"image\",\n\tparticipantId,\n}: {\n\tkey: string;\n\teventId: string;\n\tmediaType?: PublicEventSubmissionMediaType;\n\tparticipantId?: string;\n}) => {\n\tconst normalizedKey = assertAllowedPublicEventSubmissionKey({\n\t\tkey,\n\t\teventId,\n\t\tfolder: \"human-bingo/user-uploads\",\n\t\tmediaType,\n\t});\n\n\tif (participantId) {\n\t\tconst participantFolder = buildHumanBingoParticipantUploadFolder({\n\t\t\teventId,\n\t\t\tparticipantId,\n\t\t});\n\t\tif (!normalizedKey.startsWith(`${participantFolder}/`)) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Submitted file key does not match participant upload scope\",\n\t\t\t);\n\t\t}\n\t}\n\n\treturn normalizedKey;\n};\n\nexport const assertAllowedS3ObjectKey = (key: string) => {\n\tconst normalizedKey = key.replace(/^\\/+/, \"\");\n\tif (!normalizedKey || normalizedKey.includes(\"..\")) {\n\t\tthrow new Error(\"Invalid S3 object key\");\n\t}\n\n\tif (normalizedKey.startsWith(\"organization-images/\")) {\n\t\treturn normalizedKey;\n\t}\n\n\tconst folder = normalizedKey.split(\"/\").slice(0, -1).join(\"/\");\n\tif (!isAllowedEventUploadFolder(folder)) {\n\t\tthrow new Error(\"S3 object key prefix is not allowed\");\n\t}\n\n\treturn normalizedKey;\n};\n\nexport const isUserUploadImageKey = (key: string) =>\n\tkey.includes(USER_UPLOAD_FOLDER_SUFFIX);\n\nexport const isPublicBackgroundImageKey = (key: string) =>\n\tEVENT_BACKGROUND_FOLDERS.some((folder) => key.startsWith(`${folder}/`));\n\nexport const getImageProxyCacheControl = (key: string) => {\n\tif (isUserUploadImageKey(key)) {\n\t\treturn \"private, no-store\";\n\t}\n\n\tif (isPublicBackgroundImageKey(key)) {\n\t\treturn \"public, max-age=86400, immutable\";\n\t}\n\n\treturn \"private, max-age=3600\";\n};\n", "import type { Event } from \"@go-labs/event-tech-db\";\nimport { EventType } from \"@go-labs/event-tech-db/enums\";\n\nexport const EVENT_TECH_EVENT_TYPES = Object.values(EventType);\nexport type EventTechEventType = EventType;\nexport type EventAppearance = NonNullable<Event[\"appearance\"]>;\nexport type EventTheme = EventAppearance[\"theme\"];\nexport type EventThemeFontFamily = EventTheme[\"fontFamily\"];\nexport const EVENT_THEME_FONT_FAMILIES = [\n\t\"SYSTEM\",\n\t\"JAKARTA\",\n\t\"SERIF\",\n] as const satisfies readonly EventThemeFontFamily[];\n\nexport interface EventAppearanceProjection {\n\teventId: string;\n\teventName: string;\n\teventType: EventTechEventType;\n\tappearance: EventAppearance;\n\tappearanceVersion: number;\n\thasCustomAppearance: boolean;\n\tguestBackgroundUrl: string | null;\n\tdisplayBackgroundUrl: string | null;\n\t/** Presigned-proxy URL of the Event Passport hero image, when one is set. */\n\tpassportHeroImageUrl: string | null;\n\t/** Presigned-proxy URL of the Event Passport logo, when one is set. */\n\tpassportLogoUrl: string | null;\n}\n\nexport const DEFAULT_EVENT_APPEARANCE: EventAppearance = {\n\tversion: 1,\n\ttheme: {\n\t\taccentColor: \"#f84404\",\n\t\tbackgroundColor: \"#f6f7f9\",\n\t\ttextColor: \"#20242a\",\n\t\tfontFamily: \"SYSTEM\",\n\t},\n\tguestBackground: { key: null, type: \"none\" },\n\tdisplayBackground: { key: null, type: \"none\" },\n\tphotoWall: {\n\t\tdurationSeconds: 18,\n\t\tmaxVisible: 4,\n\t\tmotion: \"gentle\",\n\t\tshowEventName: true,\n\t\tshowQrCode: true,\n\t\tqrCodeLabel: \"Scan to share\",\n\t},\n};\n\nconst HEX_COLOR_PATTERN = /^#[0-9a-f]{6}$/i;\nconst DEFAULT_FONT_STACKS: Record<EventThemeFontFamily, string> = {\n\tJAKARTA:\n\t\t'var(--font-plus-jakarta-sans, \"Plus Jakarta Sans\"), ui-sans-serif, system-ui, sans-serif',\n\tSERIF: 'Georgia, Cambria, \"Times New Roman\", Times, serif',\n\tSYSTEM: \"ui-sans-serif, system-ui, sans-serif\",\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === \"object\" && value !== null && !Array.isArray(value);\n\nexport const isEventThemeHexColor = (value: string) =>\n\tHEX_COLOR_PATTERN.test(value);\n\nexport const isEventThemeFontFamily = (\n\tvalue: string,\n): value is EventThemeFontFamily =>\n\t(EVENT_THEME_FONT_FAMILIES as readonly string[]).includes(value);\n\nconst getValidColor = (value: unknown, fallback: string) =>\n\ttypeof value === \"string\" && isEventThemeHexColor(value)\n\t\t? value.toLowerCase()\n\t\t: fallback;\n\nconst getValidTheme = (value: unknown, fallback: EventTheme): EventTheme => {\n\tif (!isRecord(value)) return fallback;\n\tconst fontFamily =\n\t\ttypeof value.fontFamily === \"string\" &&\n\t\tisEventThemeFontFamily(value.fontFamily)\n\t\t\t? value.fontFamily\n\t\t\t: fallback.fontFamily;\n\treturn {\n\t\taccentColor: getValidColor(value.accentColor, fallback.accentColor),\n\t\tbackgroundColor: getValidColor(\n\t\t\tvalue.backgroundColor,\n\t\t\tfallback.backgroundColor,\n\t\t),\n\t\tfontFamily,\n\t\ttextColor: getValidColor(value.textColor, fallback.textColor),\n\t};\n};\n\nexport const resolveEventTheme = ({\n\tappearance,\n\tfallback,\n\thasCustomAppearance = true,\n}: {\n\tappearance: unknown;\n\tfallback?: EventTheme | null;\n\thasCustomAppearance?: boolean;\n}): EventTheme | null => {\n\tif (!hasCustomAppearance || !isRecord(appearance)) return fallback ?? null;\n\treturn getValidTheme(\n\t\tappearance.theme,\n\t\tfallback ?? DEFAULT_EVENT_APPEARANCE.theme,\n\t);\n};\n\nconst toLinearRgbChannel = (channel: number) => {\n\tconst normalized = channel / 255;\n\treturn normalized <= 0.04045\n\t\t? normalized / 12.92\n\t\t: ((normalized + 0.055) / 1.055) ** 2.4;\n};\n\nexport const getEventThemeLuminance = (color: string) => {\n\tconst red = Number.parseInt(color.slice(1, 3), 16);\n\tconst green = Number.parseInt(color.slice(3, 5), 16);\n\tconst blue = Number.parseInt(color.slice(5, 7), 16);\n\treturn (\n\t\t0.2126 * toLinearRgbChannel(red) +\n\t\t0.7152 * toLinearRgbChannel(green) +\n\t\t0.0722 * toLinearRgbChannel(blue)\n\t);\n};\n\nexport const getEventThemeContrastRatio = (\n\tforeground: string,\n\tbackground: string,\n) => {\n\tif (!isEventThemeHexColor(foreground) || !isEventThemeHexColor(background)) {\n\t\treturn 0;\n\t}\n\tconst foregroundLuminance = getEventThemeLuminance(foreground);\n\tconst backgroundLuminance = getEventThemeLuminance(background);\n\treturn (\n\t\t(Math.max(foregroundLuminance, backgroundLuminance) + 0.05) /\n\t\t(Math.min(foregroundLuminance, backgroundLuminance) + 0.05)\n\t);\n};\n\nexport const mixEventThemeColors = (\n\tforeground: string,\n\tbackground: string,\n\tamount: number,\n) => {\n\tconst channel = (color: string, start: number) =>\n\t\tNumber.parseInt(color.slice(start, start + 2), 16);\n\tconst toHex = (value: number) =>\n\t\tMath.round(value).toString(16).padStart(2, \"0\");\n\treturn `#${[1, 3, 5]\n\t\t.map((start) =>\n\t\t\ttoHex(\n\t\t\t\tchannel(background, start) +\n\t\t\t\t\t(channel(foreground, start) - channel(background, start)) * amount,\n\t\t\t),\n\t\t)\n\t\t.join(\"\")}`;\n};\n\nexport const getEventThemeSurfaceColor = (backgroundColor: string) => {\n\tconst background = isEventThemeHexColor(backgroundColor)\n\t\t? backgroundColor.toLowerCase()\n\t\t: DEFAULT_EVENT_APPEARANCE.theme.backgroundColor;\n\tconst surface =\n\t\tgetEventThemeLuminance(background) >= 0.5\n\t\t\t? \"#ffffff\"\n\t\t\t: mixEventThemeColors(\"#ffffff\", background, 0.08);\n\tconst readableForeground = [\"#000000\", \"#ffffff\"].find(\n\t\t(candidate) =>\n\t\t\tgetEventThemeContrastRatio(candidate, background) >= 4.5 &&\n\t\t\tgetEventThemeContrastRatio(candidate, surface) >= 4.5,\n\t);\n\treturn readableForeground ? surface : background;\n};\n\nexport const getReadableEventThemeTextColor = (\n\ttextColor: string,\n\tbackgroundColor: string,\n) => {\n\tconst candidates = [textColor, \"#20242a\", \"#000000\", \"#ffffff\"].filter(\n\t\t(candidate) => isEventThemeHexColor(candidate),\n\t);\n\tconst surface = getEventThemeSurfaceColor(backgroundColor);\n\treturn (\n\t\tcandidates.find(\n\t\t\t(candidate) =>\n\t\t\t\tgetEventThemeContrastRatio(candidate, backgroundColor) >= 4.5 &&\n\t\t\t\tgetEventThemeContrastRatio(candidate, surface) >= 4.5,\n\t\t) ?? \"#ffffff\"\n\t);\n};\n\nexport const getEventThemeAccentForeground = (accentColor: string) => {\n\tconst accent = isEventThemeHexColor(accentColor)\n\t\t? accentColor\n\t\t: DEFAULT_EVENT_APPEARANCE.theme.accentColor;\n\tconst darkContrast = getEventThemeContrastRatio(\"#171717\", accent);\n\tconst lightContrast = getEventThemeContrastRatio(\"#ffffff\", accent);\n\treturn darkContrast >= lightContrast ? \"#171717\" : \"#ffffff\";\n};\n\nexport interface EventThemeTokens {\n\t\"--accent\": string;\n\t\"--accent-foreground\": string;\n\t\"--background\": string;\n\t\"--border\": string;\n\t\"--card\": string;\n\t\"--card-foreground\": string;\n\t\"--chart-1\": string;\n\t\"--destructive\": string;\n\t\"--destructive-foreground\": string;\n\t\"--font-sans\": string;\n\t\"--foreground\": string;\n\t\"--input\": string;\n\t\"--muted\": string;\n\t\"--muted-foreground\": string;\n\t\"--popover\": string;\n\t\"--popover-foreground\": string;\n\t\"--primary\": string;\n\t\"--primary-foreground\": string;\n\t\"--ring\": string;\n\t\"--secondary\": string;\n\t\"--secondary-foreground\": string;\n\tcolor: string;\n\tcolorScheme: \"dark\" | \"light\";\n\tfontFamily: string;\n}\n\nexport const getEventThemeTokens = (theme: EventTheme): EventThemeTokens => {\n\tconst normalizedTheme = getValidTheme(theme, DEFAULT_EVENT_APPEARANCE.theme);\n\tconst { accentColor, backgroundColor } = normalizedTheme;\n\tconst surfaceColor = getEventThemeSurfaceColor(backgroundColor);\n\tconst textColor = getReadableEventThemeTextColor(\n\t\tnormalizedTheme.textColor,\n\t\tbackgroundColor,\n\t);\n\tconst mutedColor =\n\t\tgetEventThemeContrastRatio(\n\t\t\tmixEventThemeColors(textColor, surfaceColor, 0.8),\n\t\t\tsurfaceColor,\n\t\t) >= 4.5\n\t\t\t? mixEventThemeColors(textColor, surfaceColor, 0.8)\n\t\t\t: textColor;\n\tconst mutedSurface = mixEventThemeColors(textColor, surfaceColor, 0.06);\n\tconst colorScheme =\n\t\tgetEventThemeLuminance(backgroundColor) < 0.5 ? \"dark\" : \"light\";\n\treturn {\n\t\t\"--accent\": mixEventThemeColors(accentColor, surfaceColor, 0.08),\n\t\t\"--accent-foreground\": textColor,\n\t\t\"--background\": backgroundColor,\n\t\t\"--border\": mixEventThemeColors(textColor, surfaceColor, 0.18),\n\t\t\"--card\": surfaceColor,\n\t\t\"--card-foreground\": textColor,\n\t\t\"--chart-1\": accentColor,\n\t\t\"--destructive\": colorScheme === \"dark\" ? \"#fda29b\" : \"#b42318\",\n\t\t\"--destructive-foreground\": colorScheme === \"dark\" ? \"#171717\" : \"#ffffff\",\n\t\t\"--font-sans\": DEFAULT_FONT_STACKS[normalizedTheme.fontFamily],\n\t\t\"--foreground\": textColor,\n\t\t\"--input\": mixEventThemeColors(textColor, surfaceColor, 0.3),\n\t\t\"--muted\": mutedSurface,\n\t\t\"--muted-foreground\": mutedColor,\n\t\t\"--popover\": surfaceColor,\n\t\t\"--popover-foreground\": textColor,\n\t\t\"--primary\": accentColor,\n\t\t\"--primary-foreground\": getEventThemeAccentForeground(accentColor),\n\t\t\"--ring\": accentColor,\n\t\t\"--secondary\": mutedSurface,\n\t\t\"--secondary-foreground\": textColor,\n\t\tcolor: textColor,\n\t\tcolorScheme,\n\t\tfontFamily: DEFAULT_FONT_STACKS[normalizedTheme.fontFamily],\n\t};\n};\n\nexport const getEventThemeMedia = ({\n\tappearance,\n\tdisplayBackgroundUrl,\n\tguestBackgroundUrl,\n\thasCustomAppearance,\n}: {\n\tappearance: unknown;\n\tdisplayBackgroundUrl?: string | null;\n\tguestBackgroundUrl?: string | null;\n\thasCustomAppearance?: boolean;\n}) => {\n\tif (!hasCustomAppearance || !isRecord(appearance)) {\n\t\treturn { display: null, guest: null };\n\t}\n\tconst guestBackground = isRecord(appearance.guestBackground)\n\t\t? appearance.guestBackground\n\t\t: null;\n\tconst displayBackground = isRecord(appearance.displayBackground)\n\t\t? appearance.displayBackground\n\t\t: null;\n\tconst displayMediaType = displayBackground?.type;\n\treturn {\n\t\tdisplay:\n\t\t\t(displayMediaType === \"image\" || displayMediaType === \"video\") &&\n\t\t\tdisplayBackgroundUrl\n\t\t\t\t? { src: displayBackgroundUrl, type: displayMediaType }\n\t\t\t\t: null,\n\t\tguest:\n\t\t\tguestBackground?.type === \"image\" && guestBackgroundUrl\n\t\t\t\t? { src: guestBackgroundUrl, type: \"image\" as const }\n\t\t\t\t: null,\n\t};\n};\n", "import {\n\tDEFAULT_EVENT_APPEARANCE,\n\ttype EventTheme,\n\tgetEventThemeContrastRatio,\n\tgetEventThemeLuminance,\n\tgetEventThemeSurfaceColor,\n\tgetReadableEventThemeTextColor,\n\tisEventThemeHexColor,\n\tmixEventThemeColors,\n\tresolveEventTheme,\n} from \"./event-theme\";\n\n/**\n * Event Passport skin.\n *\n * Every event renders the Go Labs default (the Event Tech default theme). An\n * organiser may optionally skin one event through the optional `passport`\n * block of `Event.appearance`: a key visual, a logo, a graphics-only colour,\n * a dark block colour and an emphasis mode. All colours the UI paints are\n * derived here so text on every pairing stays at WCAG AA.\n */\n\nexport type PassportSkinEmphasis = \"accent\" | \"ink\";\n\nexport interface PassportSkinSettings {\n\theroImage: { key: string; focalX: number; focalY: number } | null;\n\tlogo: { key: string } | null;\n\tcolors: { graphic: string | null; dark: string | null };\n\temphasis: PassportSkinEmphasis;\n}\n\nexport const DEFAULT_PASSPORT_SKIN_SETTINGS: PassportSkinSettings = {\n\theroImage: null,\n\tlogo: null,\n\tcolors: { graphic: null, dark: null },\n\temphasis: \"accent\",\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst toKey = (value: unknown) =>\n\ttypeof value === \"string\" && value.trim().length > 0 ? value.trim() : null;\n\nconst toPercent = (value: unknown) =>\n\ttypeof value === \"number\" && Number.isFinite(value)\n\t\t? Math.min(100, Math.max(0, value))\n\t\t: 50;\n\nconst toHex = (value: unknown) =>\n\ttypeof value === \"string\" && isEventThemeHexColor(value)\n\t\t? value.toLowerCase()\n\t\t: null;\n\nconst readHeroImage = (value: unknown): PassportSkinSettings[\"heroImage\"] => {\n\tif (!isRecord(value)) return null;\n\tconst key = toKey(value.key);\n\tif (!key) return null;\n\treturn {\n\t\tkey,\n\t\tfocalX: toPercent(value.focalX),\n\t\tfocalY: toPercent(value.focalY),\n\t};\n};\n\nconst readLogo = (value: unknown): PassportSkinSettings[\"logo\"] => {\n\tif (!isRecord(value)) return null;\n\tconst key = toKey(value.key);\n\treturn key ? { key } : null;\n};\n\n/** Reads a stored `appearance.passport` value; unknown shapes fall back to defaults. */\nexport const resolvePassportSkinSettings = (\n\tvalue: unknown,\n): PassportSkinSettings => {\n\tif (!isRecord(value)) return DEFAULT_PASSPORT_SKIN_SETTINGS;\n\tconst colors = isRecord(value.colors) ? value.colors : {};\n\treturn {\n\t\theroImage: readHeroImage(value.heroImage),\n\t\tlogo: readLogo(value.logo),\n\t\tcolors: { graphic: toHex(colors.graphic), dark: toHex(colors.dark) },\n\t\temphasis: value.emphasis === \"ink\" ? \"ink\" : \"accent\",\n\t};\n};\n\n/** Reads `passport` off a stored appearance of unknown shape. */\nexport const resolvePassportSkinSettingsFromAppearance = (\n\tappearance: unknown,\n): PassportSkinSettings =>\n\tresolvePassportSkinSettings(\n\t\tisRecord(appearance) ? appearance.passport : undefined,\n\t);\n\n/** Object keys the skin references, for media validation and cleanup. */\nexport const getPassportSkinMediaKeys = (settings: PassportSkinSettings) => ({\n\thero: settings.heroImage?.key ?? null,\n\tlogo: settings.logo?.key ?? null,\n});\n\nexport const PASSPORT_TOKEN_NAMES = [\n\t\"ground\",\n\t\"ink\",\n\t\"inkStrong\",\n\t\"accent\",\n\t\"dark\",\n\t\"onDark\",\n\t\"onDarkTitle\",\n\t\"onDarkSmall\",\n\t\"soft\",\n\t\"card\",\n\t\"muted\",\n\t\"primary\",\n\t\"onPrimary\",\n\t\"accentText\",\n\t\"bubble\",\n\t\"bubbleInk\",\n\t\"check\",\n\t\"checkInk\",\n\t\"railCap\",\n\t\"stampGround\",\n\t\"stampStatus\",\n\t\"stampDisc\",\n\t\"stampDiscInk\",\n\t\"stampBtn\",\n\t\"stampBtnInk\",\n\t\"stampLink\",\n\t\"chipQr\",\n\t\"chipQrInk\",\n\t\"chipScan\",\n\t\"chipScanInk\",\n\t\"slotEmpty\",\n\t\"scrim\",\n\t\"danger\",\n\t\"onDanger\",\n\t\"dangerSoft\",\n] as const;\n\nexport type PassportTokenName = (typeof PASSPORT_TOKEN_NAMES)[number];\nexport type PassportTokens = Record<PassportTokenName, string>;\nexport type PassportCssVariables = Record<`--pp-${string}`, string>;\n\nconst WHITE = \"#ffffff\";\nconst BLACK = \"#000000\";\nconst NEAR_BLACK = \"#111316\";\nconst FALLBACK_DARK = \"#20242a\";\nconst AA = 4.5;\n\nconst contrast = getEventThemeContrastRatio;\n\nconst meetsAll = (color: string, against: readonly string[], minimum: number) =>\n\tagainst.every((other) => contrast(color, other) >= minimum);\n\n/** First candidate meeting `minimum` on `background`, else the highest-contrast one. */\nconst pickText = (\n\tbackground: string,\n\tcandidates: readonly string[],\n\tminimum = AA,\n) => {\n\tconst readable = candidates.find(\n\t\t(candidate) => contrast(candidate, background) >= minimum,\n\t);\n\tif (readable) return readable;\n\treturn [...candidates].sort(\n\t\t(a, b) => contrast(b, background) - contrast(a, background),\n\t)[0] as string;\n};\n\n/** Moves `color` toward `target` in 2% steps until it meets `minimum` on every ground. */\nconst shiftUntil = (\n\tcolor: string,\n\ttarget: string,\n\tgrounds: readonly string[],\n\tminimum: number,\n) => {\n\tfor (let amount = 0; amount <= 1; amount += 0.02) {\n\t\tconst candidate =\n\t\t\tamount === 0 ? color : mixEventThemeColors(target, color, amount);\n\t\tif (meetsAll(candidate, grounds, minimum)) return candidate;\n\t}\n\treturn target;\n};\n\nconst isLight = (color: string) => getEventThemeLuminance(color) >= 0.5;\n\nconst resolveDark = (settings: PassportSkinSettings, ink: string) => {\n\tconst preferred = settings.colors.dark ?? ink;\n\tif (contrast(WHITE, preferred) >= AA) return preferred;\n\treturn FALLBACK_DARK;\n};\n\nconst resolveOnDark = (dark: string) => {\n\tfor (let amount = 0.7; amount < 1; amount += 0.02) {\n\t\tconst candidate = mixEventThemeColors(WHITE, dark, amount);\n\t\tif (contrast(candidate, dark) >= 7) return candidate;\n\t}\n\treturn WHITE;\n};\n\nconst resolveMuted = (ink: string, grounds: readonly string[]) => {\n\tfor (let amount = 0.6; amount < 1; amount += 0.02) {\n\t\tconst candidate = mixEventThemeColors(ink, grounds[0] as string, amount);\n\t\tif (meetsAll(candidate, grounds, AA)) return candidate;\n\t}\n\treturn ink;\n};\n\nconst toRgba = (color: string, alpha: number) => {\n\tconst channel = (start: number) =>\n\t\tNumber.parseInt(color.slice(start, start + 2), 16);\n\treturn `rgba(${channel(1)}, ${channel(3)}, ${channel(5)}, ${alpha})`;\n};\n\ninterface TokenBase {\n\tground: string;\n\tcard: string;\n\tink: string;\n\taccent: string;\n\tdark: string;\n\tgraphic: string | null;\n\tinkEmphasis: boolean;\n}\n\nconst getTokenBase = (\n\tsettings: PassportSkinSettings,\n\ttheme: EventTheme,\n): TokenBase => {\n\tconst ground = theme.backgroundColor;\n\tconst ink = getReadableEventThemeTextColor(theme.textColor, ground);\n\treturn {\n\t\tground,\n\t\tcard: getEventThemeSurfaceColor(ground),\n\t\tink,\n\t\taccent: theme.accentColor,\n\t\tdark: resolveDark(settings, ink),\n\t\tgraphic: settings.colors.graphic,\n\t\tinkEmphasis: settings.emphasis === \"ink\" && contrast(WHITE, ink) >= AA,\n\t};\n};\n\nconst getDarkBlockTokens = ({ accent, card, dark }: TokenBase) => {\n\tconst onDarkSmall = shiftUntil(accent, WHITE, [dark], AA);\n\treturn {\n\t\tdark,\n\t\tonDark: resolveOnDark(dark),\n\t\tonDarkTitle: contrast(accent, dark) >= 3 ? accent : onDarkSmall,\n\t\tonDarkSmall,\n\t\tscrim: toRgba(dark, 0.56),\n\t\tonDarkStrong: contrast(card, dark) >= 7 ? card : WHITE,\n\t};\n};\n\nconst getActionTokens = (base: TokenBase) => {\n\tconst { accent, card, ground, ink, inkEmphasis } = base;\n\tconst bubble = mixEventThemeColors(accent, card, 0.15);\n\tconst primary = inkEmphasis ? ink : shiftUntil(accent, BLACK, [WHITE], AA);\n\tconst accentTextTarget = isLight(ground) ? BLACK : WHITE;\n\tconst accentText = inkEmphasis\n\t\t? ink\n\t\t: shiftUntil(accent, accentTextTarget, [ground, card, bubble], AA);\n\treturn {\n\t\tbubble,\n\t\tprimary,\n\t\taccentText,\n\t\tsoft: inkEmphasis ? card : bubble,\n\t\tbubbleInk: contrast(accentText, bubble) >= AA ? accentText : ink,\n\t};\n};\n\nconst getGraphicTokens = (\n\t{ accent, graphic }: TokenBase,\n\tinkStrong: string,\n) => {\n\tconst graphicInk = graphic\n\t\t? pickText(graphic, [WHITE, NEAR_BLACK, BLACK], 3)\n\t\t: inkStrong;\n\tconst stampDisc = graphic ?? inkStrong;\n\treturn {\n\t\tcheck: graphic ?? accent,\n\t\tcheckInk: graphicInk,\n\t\trailCap: graphic ?? \"transparent\",\n\t\tstampDisc,\n\t\tstampDiscInk: graphic\n\t\t\t? graphicInk\n\t\t\t: pickText(stampDisc, [WHITE, NEAR_BLACK]),\n\t};\n};\n\n/**\n * Derives every colour the Event Passport paints. Pairings that carry text are\n * checked against WCAG AA (4.5:1; display sizes use 3:1 where noted); the\n * graphic colour is only ever used for non-text shapes.\n */\nexport const getPassportTokens = ({\n\tsettings,\n\ttheme,\n}: {\n\tsettings: PassportSkinSettings;\n\ttheme: EventTheme;\n}): PassportTokens => {\n\tconst base = getTokenBase(settings, theme);\n\tconst { accent, card, dark, ground, ink } = base;\n\tconst darkBlock = getDarkBlockTokens(base);\n\tconst actions = getActionTokens(base);\n\tconst inkStrong = pickText(accent, [ink, NEAR_BLACK, BLACK, WHITE]);\n\tconst slotEmpty = mixEventThemeColors(ink, ground, 0.06);\n\t// A primary that disappears into the dark block falls back to the accent.\n\tconst stampOnPrimary = contrast(actions.primary, dark) >= 2;\n\treturn {\n\t\tground,\n\t\tink,\n\t\tinkStrong,\n\t\taccent,\n\t\tdark,\n\t\tonDark: darkBlock.onDark,\n\t\tonDarkTitle: darkBlock.onDarkTitle,\n\t\tonDarkSmall: darkBlock.onDarkSmall,\n\t\tsoft: actions.soft,\n\t\tcard,\n\t\tmuted: resolveMuted(ink, [ground, card, slotEmpty, actions.bubble]),\n\t\tprimary: actions.primary,\n\t\tonPrimary: WHITE,\n\t\taccentText: actions.accentText,\n\t\tbubble: actions.bubble,\n\t\tbubbleInk: actions.bubbleInk,\n\t\t...getGraphicTokens(base, inkStrong),\n\t\tstampGround: dark,\n\t\tstampStatus: darkBlock.onDarkStrong,\n\t\tstampBtn: stampOnPrimary ? actions.primary : accent,\n\t\tstampBtnInk: stampOnPrimary ? WHITE : inkStrong,\n\t\tstampLink: darkBlock.onDarkStrong,\n\t\tchipQr: accent,\n\t\tchipQrInk: inkStrong,\n\t\tchipScan: dark,\n\t\tchipScanInk: pickText(dark, [WHITE]),\n\t\tslotEmpty,\n\t\tscrim: darkBlock.scrim,\n\t\tdanger: \"#c81e1e\",\n\t\tonDanger: WHITE,\n\t\tdangerSoft: \"#fdecea\",\n\t};\n};\n\nconst toKebab = (name: string) =>\n\tname.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n\n/** `{ inkStrong }` becomes `{ \"--pp-ink-strong\": ... }` for a style attribute. */\nexport const getPassportCssVariables = (\n\ttokens: PassportTokens,\n): PassportCssVariables => {\n\tconst variables: PassportCssVariables = {};\n\tfor (const name of PASSPORT_TOKEN_NAMES) {\n\t\tvariables[`--pp-${toKebab(name)}`] = tokens[name];\n\t}\n\treturn variables;\n};\n\nexport interface PassportSkin {\n\t/** True when the organiser configured any passport skin value. */\n\tisSkinned: boolean;\n\ttheme: EventTheme;\n\tsettings: PassportSkinSettings;\n\thero: {\n\t\turl: string;\n\t\tfocalX: number;\n\t\tfocalY: number;\n\t\t/** Ready for CSS `object-position` / `background-position`. */\n\t\tobjectPosition: string;\n\t} | null;\n\tlogo: { url: string } | null;\n\ttokens: PassportTokens;\n\tcssVariables: PassportCssVariables;\n}\n\nconst hasSkinValue = (settings: PassportSkinSettings) =>\n\tsettings.heroImage !== null ||\n\tsettings.logo !== null ||\n\tsettings.colors.graphic !== null ||\n\tsettings.colors.dark !== null ||\n\tsettings.emphasis !== \"accent\";\n\n/**\n * Resolves what the participant app paints for an event. Pass the fields of\n * `EventAppearanceProjection`; events without custom appearance (or without a\n * passport block) resolve to the Go Labs default.\n */\nexport const getPassportSkin = ({\n\tappearance,\n\thasCustomAppearance,\n\theroImageUrl,\n\tlogoUrl,\n}: {\n\tappearance: unknown;\n\thasCustomAppearance: boolean;\n\theroImageUrl?: string | null;\n\tlogoUrl?: string | null;\n}): PassportSkin => {\n\tconst theme =\n\t\tresolveEventTheme({\n\t\t\tappearance,\n\t\t\thasCustomAppearance,\n\t\t\tfallback: DEFAULT_EVENT_APPEARANCE.theme,\n\t\t}) ?? DEFAULT_EVENT_APPEARANCE.theme;\n\tconst settings = hasCustomAppearance\n\t\t? resolvePassportSkinSettingsFromAppearance(appearance)\n\t\t: DEFAULT_PASSPORT_SKIN_SETTINGS;\n\tconst tokens = getPassportTokens({ settings, theme });\n\tconst hero =\n\t\tsettings.heroImage && heroImageUrl\n\t\t\t? {\n\t\t\t\t\turl: heroImageUrl,\n\t\t\t\t\tfocalX: settings.heroImage.focalX,\n\t\t\t\t\tfocalY: settings.heroImage.focalY,\n\t\t\t\t\tobjectPosition: `${settings.heroImage.focalX}% ${settings.heroImage.focalY}%`,\n\t\t\t\t}\n\t\t\t: null;\n\treturn {\n\t\tisSkinned: hasSkinValue(settings),\n\t\ttheme,\n\t\tsettings,\n\t\thero,\n\t\tlogo: settings.logo && logoUrl ? { url: logoUrl } : null,\n\t\ttokens,\n\t\tcssVariables: getPassportCssVariables(tokens),\n\t};\n};\n", "import { z } from \"zod\";\n\nexport const photoWallScreenSchema = z.object({\n\twidth: z.number().int().min(240).max(16_384),\n\theight: z.number().int().min(240).max(16_384),\n});\n\nexport const getPhotoWallScreenCapacity = (width: number, height: number) => {\n\tconst ratio = width / height;\n\n\tif (ratio >= 3)\n\t\treturn Math.min(Math.max(Math.floor(ratio * 1.25) * 2, 2), 16);\n\tif (ratio >= 1) return 8;\n\treturn 4;\n};\n", "import { z } from \"zod\";\n\nexport const photoWallSubmissionSettingsSchema = z.object({\n\tmode: z.enum([\"photo-only\", \"comment-only\", \"photo-and-comment\"]),\n\tphotoRequired: z.boolean(),\n\tcommentRequired: z.boolean(),\n});\n\nexport type PhotoWallSubmissionSettings = z.infer<\n\ttypeof photoWallSubmissionSettingsSchema\n>;\n\nexport const DEFAULT_PHOTO_WALL_SUBMISSION_SETTINGS = {\n\tmode: \"photo-and-comment\",\n\tphotoRequired: true,\n\tcommentRequired: false,\n} as const satisfies PhotoWallSubmissionSettings;\n\nexport interface PhotoWallSubmissionRequirements {\n\tshowPhoto: boolean;\n\tshowComment: boolean;\n\tphotoRequired: boolean;\n\tcommentRequired: boolean;\n}\n\nexport const getPhotoWallSubmissionRequirements = (\n\tsettings: PhotoWallSubmissionSettings,\n): PhotoWallSubmissionRequirements => ({\n\tshowPhoto: settings.mode !== \"comment-only\",\n\tshowComment: settings.mode !== \"photo-only\",\n\tphotoRequired:\n\t\tsettings.mode === \"photo-only\" ||\n\t\t(settings.mode === \"photo-and-comment\" && settings.photoRequired),\n\tcommentRequired:\n\t\tsettings.mode === \"comment-only\" ||\n\t\t(settings.mode === \"photo-and-comment\" && settings.commentRequired),\n});\n", "import { z } from \"zod\";\nimport { photoWallScreenSchema } from \"./photo-wall-screen.schema\";\nimport {\n\tDEFAULT_PHOTO_WALL_SUBMISSION_SETTINGS,\n\tphotoWallSubmissionSettingsSchema,\n} from \"./photo-wall-submission-settings.schema\";\n\nconst hexColorSchema = z\n\t.string()\n\t.trim()\n\t.regex(/^#[0-9a-f]{6}$/i, \"Color must be a six-digit hex color\")\n\t.transform((value) => value.toLowerCase());\n\nconst getRelativeLuminance = (color: string): number => {\n\tconst toLinear = (channel: number) => {\n\t\tconst normalized = channel / 255;\n\t\treturn normalized <= 0.04045\n\t\t\t? normalized / 12.92\n\t\t\t: ((normalized + 0.055) / 1.055) ** 2.4;\n\t};\n\tconst red = toLinear(Number.parseInt(color.slice(1, 3), 16));\n\tconst green = toLinear(Number.parseInt(color.slice(3, 5), 16));\n\tconst blue = toLinear(Number.parseInt(color.slice(5, 7), 16));\n\treturn 0.2126 * red + 0.7152 * green + 0.0722 * blue;\n};\n\nconst hasReadableTextContrast = (\n\ttextColor: string,\n\tbackgroundColor: string,\n) => {\n\tconst textLuminance = getRelativeLuminance(textColor);\n\tconst backgroundLuminance = getRelativeLuminance(backgroundColor);\n\treturn (\n\t\t(Math.max(textLuminance, backgroundLuminance) + 0.05) /\n\t\t\t(Math.min(textLuminance, backgroundLuminance) + 0.05) >=\n\t\t4.5\n\t);\n};\n\nexport const eventThemeSchema = z\n\t.object({\n\t\taccentColor: hexColorSchema,\n\t\tbackgroundColor: hexColorSchema,\n\t\ttextColor: hexColorSchema,\n\t\tfontFamily: z.enum([\"SYSTEM\", \"JAKARTA\", \"SERIF\"]),\n\t})\n\t.superRefine((theme, context) => {\n\t\tif (!hasReadableTextContrast(theme.textColor, theme.backgroundColor)) {\n\t\t\tcontext.addIssue({\n\t\t\t\tcode: \"custom\",\n\t\t\t\tmessage:\n\t\t\t\t\t\"Text color must have at least 4.5:1 contrast on the background color\",\n\t\t\t\tpath: [\"textColor\"],\n\t\t\t});\n\t\t}\n\t});\n\nconst appearanceMediaSchema = z.discriminatedUnion(\"type\", [\n\tz.object({ type: z.literal(\"none\"), key: z.null() }),\n\tz.object({ type: z.literal(\"image\"), key: z.string().min(1).max(1024) }),\n]);\n\nconst displayMediaSchema = z.discriminatedUnion(\"type\", [\n\tz.object({ type: z.literal(\"none\"), key: z.null() }),\n\tz.object({ type: z.literal(\"image\"), key: z.string().min(1).max(1024) }),\n\tz.object({ type: z.literal(\"video\"), key: z.string().min(1).max(1024) }),\n]);\n\nconst passportImageKeySchema = z.string().trim().min(1).max(1024);\nconst passportFocalSchema = z.number().min(0).max(100);\n\n/**\n * Optional Event Passport skin. Every field is optional with a default, so a\n * stored appearance without `passport` (or with a partial block) resolves to\n * the Go Labs default look.\n */\nexport const passportSkinSchema = z.object({\n\theroImage: z\n\t\t.object({\n\t\t\tkey: passportImageKeySchema,\n\t\t\tfocalX: passportFocalSchema.default(50),\n\t\t\tfocalY: passportFocalSchema.default(50),\n\t\t})\n\t\t.nullable()\n\t\t.default(null),\n\tlogo: z.object({ key: passportImageKeySchema }).nullable().default(null),\n\tcolors: z\n\t\t.object({\n\t\t\tgraphic: hexColorSchema.nullable().default(null),\n\t\t\tdark: hexColorSchema\n\t\t\t\t.nullable()\n\t\t\t\t.default(null)\n\t\t\t\t.refine(\n\t\t\t\t\t(color) =>\n\t\t\t\t\t\tcolor === null || hasReadableTextContrast(\"#ffffff\", color),\n\t\t\t\t\t\"Dark colour must have at least 4.5:1 contrast with white text\",\n\t\t\t\t),\n\t\t})\n\t\t.default({ graphic: null, dark: null }),\n\temphasis: z.enum([\"accent\", \"ink\"]).default(\"accent\"),\n});\n\nexport const eventAppearanceSchema = z.object({\n\tversion: z.literal(1),\n\ttheme: eventThemeSchema,\n\tguestBackground: appearanceMediaSchema,\n\tdisplayBackground: displayMediaSchema,\n\t/** Omitted on save keeps the stored skin (see update-event-appearance). */\n\tpassport: passportSkinSchema.optional(),\n\tphotoWall: z.object({\n\t\tdurationSeconds: z.number().int().min(10).max(40),\n\t\tmaxVisible: z.number().int().min(1).max(16),\n\t\tmotion: z.enum([\"gentle\", \"lively\", \"roaming\"]),\n\t\tshowQrCode: z.boolean(),\n\t\tqrCodeLabel: z\n\t\t\t.string()\n\t\t\t.trim()\n\t\t\t.max(80, \"QR code text must be 80 characters or fewer\")\n\t\t\t.transform((value) => value || \"Scan to share\")\n\t\t\t.default(\"Scan to share\"),\n\t\tshowEventName: z.boolean(),\n\t\tscreen: photoWallScreenSchema.nullable().default(null),\n\t\tsubmission: photoWallSubmissionSettingsSchema.default(\n\t\t\tDEFAULT_PHOTO_WALL_SUBMISSION_SETTINGS,\n\t\t),\n\t}),\n});\n\nexport type EventAppearance = z.output<typeof eventAppearanceSchema>;\nexport type EventTheme = z.output<typeof eventThemeSchema>;\nexport type PassportSkinSettings = z.output<typeof passportSkinSchema>;\nexport type PassportSkinInput = z.input<typeof passportSkinSchema>;\n\nexport const DEFAULT_PASSPORT_SKIN: PassportSkinSettings = {\n\theroImage: null,\n\tlogo: null,\n\tcolors: { graphic: null, dark: null },\n\temphasis: \"accent\",\n};\n\nexport const DEFAULT_EVENT_APPEARANCE: EventAppearance = {\n\tversion: 1,\n\ttheme: {\n\t\taccentColor: \"#f84404\",\n\t\tbackgroundColor: \"#f6f7f9\",\n\t\ttextColor: \"#20242a\",\n\t\tfontFamily: \"SYSTEM\",\n\t},\n\tguestBackground: { type: \"none\", key: null },\n\tdisplayBackground: { type: \"none\", key: null },\n\tphotoWall: {\n\t\tdurationSeconds: 18,\n\t\tmaxVisible: 4,\n\t\tmotion: \"gentle\",\n\t\tshowQrCode: true,\n\t\tqrCodeLabel: \"Scan to share\",\n\t\tshowEventName: true,\n\t\tscreen: null,\n\t\tsubmission: DEFAULT_PHOTO_WALL_SUBMISSION_SETTINGS,\n\t},\n};\n", "import { readFile, writeFile } from \"node:fs/promises\";\nimport { basename } from \"node:path\";\nimport { readSpreadsheetTable } from \"@go-labs/event-tech-utils/lib/spreadsheet-table\";\nimport { staffRedemptionExportSchema } from \"@go-labs/event-tech-validators/staff-redemption/staff-redemption-input.schema\";\nimport {\n\tguessStaffRedemptionRosterMapping,\n\tmapStaffRedemptionRosterTable,\n\ttype StaffRedemptionRosterColumnMapping,\n} from \"@go-labs/event-tech-validators/staff-redemption/staff-redemption-roster.schema\";\nimport { api, type RouterOutputs } from \"@go-labs-sg/event-tech/api-client\";\nimport {\n\tassertOnlyFlags,\n\tassertPositionalCount,\n\tassertStateChangeTarget,\n\tgetOptionalFlag,\n\tgetRequiredFlag,\n\ttype ParsedArguments,\n} from \"@go-labs-sg/event-tech/arguments\";\nimport {\n\ttype CliRuntime,\n\tCliUsageError,\n\twriteSuccess,\n} from \"@go-labs-sg/event-tech/runtime\";\n\ntype ExportRow =\n\tRouterOutputs[\"event\"][\"staffRedemption\"][\"getStaffRedemptionExportData\"][\"rows\"][number];\n\ntype OptionalRosterColumn = Exclude<\n\tkeyof StaffRedemptionRosterColumnMapping,\n\t\"employeeId\"\n>;\n\n/** Optional roster columns, each with the flag that overrides the header guess. */\nconst optionalRosterColumns: readonly [OptionalRosterColumn, string][] = [\n\t[\"name\", \"name-column\"],\n\t[\"siteName\", \"site-column\"],\n\t[\"shift\", \"shift-column\"],\n\t[\"workShift\", \"work-shift-column\"],\n\t[\"allowance\", \"allowance-column\"],\n];\n\nconst rosterImportFlags = [\n\t\"event-id\",\n\t\"file\",\n\t\"sheet\",\n\t\"employee-id-column\",\n\t...optionalRosterColumns.map(([, flag]) => flag),\n\t\"archive-missing\",\n\t\"allow-state-change\",\n\t\"target\",\n] as const;\n\nconst exportFlags = [\n\t\"event-id\",\n\t\"search\",\n\t\"site-id\",\n\t\"session-id\",\n\t\"status\",\n\t\"csv-file\",\n\t\"force\",\n] as const;\n\n/** Finds a header by exact text, ignoring case and surrounding spaces. */\nconst headerIndex = (headers: readonly string[], name: string): number => {\n\tconst wanted = name.trim().toLowerCase();\n\tconst index = headers.findIndex(\n\t\t(header) => header.trim().toLowerCase() === wanted,\n\t);\n\tif (index === -1)\n\t\tthrow new CliUsageError(\n\t\t\t`Column \"${name}\" is not in the file. Headers: ${headers.join(\", \")}.`,\n\t\t);\n\treturn index;\n};\n\n/** Column flags override the header guess; \"none\" clears an optional column. */\nexport const resolveStaffRedemptionRosterMapping = (\n\theaders: readonly string[],\n\tparsed: ParsedArguments,\n): StaffRedemptionRosterColumnMapping => {\n\tconst mapping = guessStaffRedemptionRosterMapping(headers);\n\tconst employeeIdColumn = getOptionalFlag(parsed, \"employee-id-column\");\n\tif (employeeIdColumn !== undefined)\n\t\tmapping.employeeId = headerIndex(headers, employeeIdColumn);\n\tfor (const [key, flag] of optionalRosterColumns) {\n\t\tconst value = getOptionalFlag(parsed, flag);\n\t\tif (value === undefined) continue;\n\t\tmapping[key] =\n\t\t\tvalue.trim().toLowerCase() === \"none\"\n\t\t\t\t? null\n\t\t\t\t: headerIndex(headers, value);\n\t}\n\treturn mapping;\n};\n\nconst readRosterTable = async (\n\tpath: string,\n\tsheetName: string | undefined,\n): Promise<string[][]> => {\n\ttry {\n\t\treturn await readSpreadsheetTable(basename(path), await readFile(path), {\n\t\t\tsheetName,\n\t\t});\n\t} catch (error) {\n\t\tthrow new CliUsageError(\n\t\t\t`Could not read ${path}: ${error instanceof Error ? error.message : \"unknown error\"}`,\n\t\t);\n\t}\n};\n\nconst prepareRosterImport = async (parsed: ParsedArguments) => {\n\tconst eventId = getRequiredFlag(parsed, \"event-id\");\n\tconst path = getRequiredFlag(parsed, \"file\");\n\tconst sheet = getOptionalFlag(parsed, \"sheet\");\n\tassertStateChangeTarget(parsed, eventId);\n\tconst table = await readRosterTable(path, sheet);\n\tconst mapping = resolveStaffRedemptionRosterMapping(table[0] ?? [], parsed);\n\tlet rows: ReturnType<typeof mapStaffRedemptionRosterTable>;\n\ttry {\n\t\trows = mapStaffRedemptionRosterTable(table, mapping);\n\t} catch (error) {\n\t\tthrow new CliUsageError(\n\t\t\t`Could not import ${path}: ${error instanceof Error ? error.message : \"unknown error\"}`,\n\t\t);\n\t}\n\tif (rows.length === 0)\n\t\tthrow new CliUsageError(`${path} has a header but no data rows.`);\n\treturn {\n\t\teventId,\n\t\trows,\n\t\tarchiveMissing: parsed.flags.get(\"archive-missing\") === true,\n\t};\n};\n\nconst exportFilters = (parsed: ParsedArguments, eventId: string) => {\n\tconst checked = staffRedemptionExportSchema.safeParse({\n\t\teventId,\n\t\tsearch: getOptionalFlag(parsed, \"search\"),\n\t\tsiteId: getOptionalFlag(parsed, \"site-id\"),\n\t\tsessionId: getOptionalFlag(parsed, \"session-id\"),\n\t\tstatus: getOptionalFlag(parsed, \"status\"),\n\t});\n\tif (!checked.success) {\n\t\tconst issue = checked.error.issues[0];\n\t\tconst name = String(issue?.path[0] ?? \"filter\");\n\t\tthrow new CliUsageError(\n\t\t\tname === \"status\"\n\t\t\t\t? \"--status must be active, items-pending, voided or all.\"\n\t\t\t\t: `Invalid ${name}: ${issue?.message ?? \"the value is invalid\"}.`,\n\t\t);\n\t}\n\treturn checked.data;\n};\n\n/** Spreadsheet apps run text that starts with one of these as a formula. */\nconst formulaStart = /^[=+\\-@\\t\\r]/;\n\nconst csvCell = (value: string | null | undefined): string => {\n\tconst text = value ?? \"\";\n\tconst safe = formulaStart.test(text) ? `'${text}` : text;\n\treturn /[\",\\r\\n]/.test(safe) ? `\"${safe.replaceAll('\"', '\"\"')}\"` : safe;\n};\n\nconst csvColumns: readonly [string, (row: ExportRow) => string | null][] = [\n\t[\"Created at\", (row) => row.createdAt.toISOString()],\n\t[\"Employee ID\", (row) => row.employeeId],\n\t[\"Name\", (row) => row.name],\n\t[\"Site\", (row) => row.site.name],\n\t[\"Roster site\", (row) => row.rosterSiteName],\n\t[\"Away from roster site\", (row) => (row.awayFromRosterSite ? \"yes\" : \"no\")],\n\t[\"Session\", (row) => row.session.name],\n\t[\n\t\t\"Items\",\n\t\t(row) =>\n\t\t\trow.items\n\t\t\t\t.map((item) => {\n\t\t\t\t\tconst label = `${item.groupName}: ${item.name}`;\n\t\t\t\t\treturn item.quantity === 1 ? label : `${label} x${item.quantity}`;\n\t\t\t\t})\n\t\t\t\t.join(\"; \"),\n\t],\n\t[\"Items recorded\", (row) => (row.itemsPending ? \"no\" : \"yes\")],\n\t[\"Items recorded at\", (row) => row.itemsRecordedAt?.toISOString() ?? null],\n\t[\"Outcome\", (row) => row.draw?.outcome ?? null],\n\t[\"Prize\", (row) => row.draw?.prize?.name ?? null],\n\t[\"Operator kind\", (row) => row.operatorKind],\n\t[\"Voided at\", (row) => row.voidedAt?.toISOString() ?? null],\n\t[\"Void reason\", (row) => row.voidReason],\n\t[\"Draw released at\", (row) => row.draw?.releasedAt?.toISOString() ?? null],\n];\n\n/**\n * CSV for the redemption export: header plus one row per claim, CRLF line\n * ends, quoted per RFC 4180 and with a UTF-8 byte order mark so Excel reads\n * non-Latin names. Text that would run as a spreadsheet formula gets a leading\n * apostrophe.\n */\nexport const staffRedemptionClaimsToCsv = (\n\trows: readonly ExportRow[],\n): string => {\n\tconst lines = [\n\t\tcsvColumns.map(([header]) => csvCell(header)).join(\",\"),\n\t\t...rows.map((row) =>\n\t\t\tcsvColumns.map(([, read]) => csvCell(read(row))).join(\",\"),\n\t\t),\n\t];\n\treturn `${lines.join(\"\\r\\n\")}\\r\\n`;\n};\n\nconst writeCsvFile = async (\n\tpath: string,\n\tcontent: string,\n\tforce: boolean,\n): Promise<void> => {\n\ttry {\n\t\tawait writeFile(path, content, {\n\t\t\tencoding: \"utf8\",\n\t\t\tflag: force ? \"w\" : \"wx\",\n\t\t});\n\t} catch (error) {\n\t\tconst code =\n\t\t\terror instanceof Error && \"code\" in error ? error.code : undefined;\n\t\tif (code === \"EEXIST\")\n\t\t\tthrow new CliUsageError(\n\t\t\t\t`${path} already exists. Choose another --csv-file or pass --force to overwrite it.`,\n\t\t\t);\n\t\tthrow new CliUsageError(\n\t\t\t`Could not write ${path}: ${error instanceof Error ? error.message : \"unknown error\"}`,\n\t\t);\n\t}\n};\n\nconst exportClaims = async (input: {\n\tparsed: ParsedArguments;\n\truntime: CliRuntime;\n\tauthenticate: () => Promise<void>;\n}) => {\n\tconst { parsed, runtime } = input;\n\tassertOnlyFlags(parsed, exportFlags);\n\tassertPositionalCount(parsed, 2);\n\tconst eventId = getRequiredFlag(parsed, \"event-id\");\n\tconst filters = exportFilters(parsed, eventId);\n\tconst csvFile = getOptionalFlag(parsed, \"csv-file\");\n\tif (csvFile === undefined && parsed.flags.has(\"force\"))\n\t\tthrow new CliUsageError(\"--force only applies with --csv-file.\");\n\tawait input.authenticate();\n\tconst { rows } =\n\t\tawait api.event.staffRedemption.getStaffRedemptionExportData.query(filters);\n\tif (csvFile === undefined) {\n\t\twriteSuccess(runtime, { rows });\n\t\treturn;\n\t}\n\tawait writeCsvFile(\n\t\tcsvFile,\n\t\tstaffRedemptionClaimsToCsv(rows),\n\t\tparsed.flags.get(\"force\") === true,\n\t);\n\twriteSuccess(runtime, { file: csvFile, rows: rows.length });\n};\n\nconst importRoster = async (input: {\n\tparsed: ParsedArguments;\n\truntime: CliRuntime;\n\tauthenticate: () => Promise<void>;\n}) => {\n\tconst { parsed, runtime } = input;\n\tassertOnlyFlags(parsed, rosterImportFlags);\n\tassertPositionalCount(parsed, 3);\n\tconst payload = await prepareRosterImport(parsed);\n\tawait input.authenticate();\n\twriteSuccess(\n\t\truntime,\n\t\tawait api.event.staffRedemption.importStaffRedemptionRoster.mutate(payload),\n\t);\n};\n\n/**\n * Hand-written `et staff-redemption` commands. The rest of the group is in the\n * registry (`src/registry/commands.ts`) and never reaches this function.\n */\nexport const runStaffRedemptionCommand = async (input: {\n\tparsed: ParsedArguments;\n\truntime: CliRuntime;\n\tauthenticate: () => Promise<void>;\n}): Promise<void> => {\n\tconst action = input.parsed.positionals.slice(1).join(\" \");\n\tswitch (action) {\n\t\tcase \"roster import\":\n\t\t\tawait importRoster(input);\n\t\t\treturn;\n\t\tcase \"export\":\n\t\t\tawait exportClaims(input);\n\t\t\treturn;\n\t\tdefault:\n\t\t\tthrow new CliUsageError(\n\t\t\t\t\"Unknown staff-redemption command. Run `et commands` for the registry commands and `et --help` for the rest.\",\n\t\t\t);\n\t}\n};\n", "import { stationStaffPasswordSchema } from \"@go-labs/event-tech-validators/event-passport/passport-station-access.schema\";\nimport { z } from \"zod\";\n\nexport const STAFF_REDEMPTION_NAME_MAX = 120;\nexport const STAFF_REDEMPTION_EMPLOYEE_ID_MAX = 64;\nexport const STAFF_REDEMPTION_SHIFT_MAX = 8;\nexport const STAFF_REDEMPTION_ELIGIBLE_SHIFTS_MAX = 20;\nexport const STAFF_REDEMPTION_ALLOWANCE_MAX = 20;\nexport const STAFF_REDEMPTION_QUANTITY_MAX = 100_000;\nexport const STAFF_REDEMPTION_REASON_MAX = 500;\nexport const STAFF_REDEMPTION_ROLLOVER_REASON_MAX = 300;\nexport const STAFF_REDEMPTION_ROLLOVER_LIST_DEFAULT = 20;\nexport const STAFF_REDEMPTION_ROLLOVER_LIST_MAX = 50;\nexport const STAFF_REDEMPTION_PAGE_MAX = 100;\nexport const STAFF_REDEMPTION_CLAIM_ITEMS_MAX = 20;\nexport const STAFF_REDEMPTION_EXPORT_MAX_ROWS = 20_000;\n\n/**\n * Most rows the bounded setup reads return per list (list standardization:\n * bounded editors load `take: max + 1` and report `truncated`). Generous for a\n * real event: a handful of sites and sessions, a short catalogue.\n */\nexport const STAFF_REDEMPTION_LIST_MAX = {\n\tsites: 200,\n\tsessions: 200,\n\tslots: 2_000,\n\titemGroups: 100,\n\titemsPerGroup: 200,\n\tprizes: 200,\n\tprizeStock: 10_000,\n} as const;\n\nexport const STAFF_REDEMPTION_ITEM_RULES = [\n\t\"ONE_FROM_EACH_GROUP\",\n\t\"AT_MOST_ONE_PER_GROUP\",\n\t\"AT_MOST_ONE_PER_GROUP_OR_NONE\",\n] as const;\nexport const STAFF_REDEMPTION_WRONG_SITE_RULES = [\n\t\"REFUSE\",\n\t\"SERVE_FROM_COUNTER\",\n] as const;\n/**\n * Which session a person may redeem in. OWN_SHIFT (the default when unset):\n * only the session for their roster shift, while it is open. ANY_OPEN_SESSION:\n * whichever session is open now, served from that session's sets (#2387).\n */\nexport const STAFF_REDEMPTION_SESSION_RULES = [\n\t\"OWN_SHIFT\",\n\t\"ANY_OPEN_SESSION\",\n] as const;\n/**\n * The remaining-headcount draw shares a slot's prizes over the people of its\n * own site and shift, which ANY_OPEN_SESSION no longer limits it to, so the\n * two cannot be combined (#2387).\n */\nexport const STAFF_REDEMPTION_SESSION_DRAW_CONFLICT =\n\t\"Any open session needs the fixed win rate draw. The remaining-headcount draw shares a session's prizes over its own shift only.\";\nexport const STAFF_REDEMPTION_DRAW_POLICIES = [\n\t\"REMAINING_HEADCOUNT\",\n\t\"FIXED_RATE\",\n] as const;\n/**\n * The counter's order of steps. FOOD_THEN_DRAW (the default when unset): pick\n * items, Redeem, then the wheel. DRAW_THEN_FOOD: Spin first (the claim, set and\n * draw are recorded with no items), then record the items on that claim.\n */\nexport const STAFF_REDEMPTION_COUNTER_ORDERS = [\n\t\"FOOD_THEN_DRAW\",\n\t\"DRAW_THEN_FOOD\",\n] as const;\nexport type StaffRedemptionCounterOrder =\n\t(typeof STAFF_REDEMPTION_COUNTER_ORDERS)[number];\nexport const STAFF_REDEMPTION_DEFAULT_COUNTER_ORDER: StaffRedemptionCounterOrder =\n\t\"FOOD_THEN_DRAW\";\n\n/** Entities with an archive and unarchive action. */\nexport const STAFF_REDEMPTION_ARCHIVABLE = [\n\t\"site\",\n\t\"session\",\n\t\"itemGroup\",\n\t\"item\",\n\t\"prize\",\n\t\"rosterEntry\",\n] as const;\n\n/** Why a counter lookup or redemption cannot go ahead. */\nexport const STAFF_REDEMPTION_REFUSAL_CODES = [\n\t\"NOT_ON_ROSTER\",\n\t\"ARCHIVED\",\n\t\"NOT_ELIGIBLE_SHIFT\",\n\t\"NO_SESSION_FOR_SHIFT\",\n\t\"SESSION_NOT_OPEN\",\n\t\"SESSION_CLOSED\",\n\t\"NO_OPEN_SESSION\",\n\t\"NO_SLOT_AT_ROSTER_SITE\",\n\t\"WRONG_SITE\",\n\t\"NO_SLOT_AT_SITE\",\n\t\"ALREADY_REDEEMED\",\n\t\"NO_SETS_LEFT\",\n\t\"SETUP_INCOMPLETE\",\n] as const;\nexport type StaffRedemptionRefusalCode =\n\t(typeof STAFF_REDEMPTION_REFUSAL_CODES)[number];\n\n/** What the setup readiness checklist can report as missing. */\nexport const STAFF_REDEMPTION_READINESS_CODES = [\n\t\"POLICIES_MISSING\",\n\t\"NO_SITES\",\n\t\"SITE_WITHOUT_PASSWORD\",\n\t\"NO_SESSIONS\",\n\t\"NO_SLOTS\",\n\t\"SLOT_WITHOUT_SETS\",\n\t\"NO_ITEM_GROUPS\",\n\t\"GROUP_WITHOUT_ITEMS\",\n\t\"NO_PRIZES\",\n\t\"NO_PRIZE_STOCK\",\n\t\"ROSTER_EMPTY\",\n\t\"EVENT_NOT_ONGOING\",\n] as const;\nexport type StaffRedemptionReadinessCode =\n\t(typeof STAFF_REDEMPTION_READINESS_CODES)[number];\n\nconst idSchema = z.string().min(1).max(64);\nconst nameSchema = z.string().trim().min(1).max(STAFF_REDEMPTION_NAME_MAX);\nconst orderSchema = z.number().int().min(0).max(10_000);\nconst quantitySchema = z\n\t.number()\n\t.int()\n\t.min(0)\n\t.max(STAFF_REDEMPTION_QUANTITY_MAX);\nconst reasonSchema = z.string().trim().min(1).max(STAFF_REDEMPTION_REASON_MAX);\n\n/** Uppercase shift letter or code, as on the roster (\"C\"). */\nexport const staffRedemptionShiftSchema = z\n\t.string()\n\t.trim()\n\t.min(1)\n\t.max(STAFF_REDEMPTION_SHIFT_MAX)\n\t.transform((value) => value.toUpperCase())\n\t.refine((value) => /^[A-Z0-9]+$/.test(value), {\n\t\tmessage: \"Use letters and digits only.\",\n\t});\n\nexport const staffRedemptionEmployeeIdSchema = z\n\t.string()\n\t.trim()\n\t.min(1)\n\t.max(STAFF_REDEMPTION_EMPLOYEE_ID_MAX);\n\n/** Generated by the counter for each Redeem tap and reused on retry. */\nexport const staffRedemptionClientRequestIdSchema = z.uuid();\n\nexport const staffRedemptionEventIdSchema = z\n\t.object({ eventId: idSchema })\n\t.strict();\n\nexport const staffRedemptionSiteIdSchema = staffRedemptionEventIdSchema\n\t.extend({ siteId: idSchema })\n\t.strict();\n\n// ---------------------------------------------------------------- settings\n\nexport const updateStaffRedemptionSettingsSchema = staffRedemptionEventIdSchema\n\t.extend({\n\t\teligibleShifts: z\n\t\t\t.array(staffRedemptionShiftSchema)\n\t\t\t.min(1)\n\t\t\t.max(STAFF_REDEMPTION_ELIGIBLE_SHIFTS_MAX)\n\t\t\t.optional(),\n\t\titemRule: z.enum(STAFF_REDEMPTION_ITEM_RULES).optional(),\n\t\twrongSite: z.enum(STAFF_REDEMPTION_WRONG_SITE_RULES).optional(),\n\t\tsessionRule: z.enum(STAFF_REDEMPTION_SESSION_RULES).optional(),\n\t\tdrawPolicy: z.enum(STAFF_REDEMPTION_DRAW_POLICIES).optional(),\n\t\tfixedWinRatePercent: z.number().min(0).max(100).optional(),\n\t\tcounterOrder: z.enum(STAFF_REDEMPTION_COUNTER_ORDERS).optional(),\n\t\t/** Allows changing policies after the first redemption; recorded in the activity log. */\n\t\toverrideReason: reasonSchema.optional(),\n\t})\n\t.strict();\n\n// ---------------------------------------------------------------- sites\n\nexport const upsertStaffRedemptionSiteSchema = staffRedemptionEventIdSchema\n\t.extend({\n\t\tsiteId: idSchema.optional(),\n\t\tname: nameSchema,\n\t\torder: orderSchema.optional(),\n\t})\n\t.strict();\n\nexport const setStaffRedemptionCrewPasswordSchema = staffRedemptionSiteIdSchema\n\t.extend({ password: stationStaffPasswordSchema })\n\t.strict();\n\nexport const signInToStaffRedemptionCrewSchema = staffRedemptionSiteIdSchema\n\t.extend({ password: z.string().min(1).max(128) })\n\t.strict();\n\n// ---------------------------------------------------------------- sessions and slots\n\nexport const upsertStaffRedemptionSessionSchema = staffRedemptionEventIdSchema\n\t.extend({\n\t\tsessionId: idSchema.optional(),\n\t\tname: nameSchema,\n\t\tshift: staffRedemptionShiftSchema,\n\t\t/** Optional; null or omitted opens the session whenever the event is open. */\n\t\tstartsAt: z.coerce.date().nullable().default(null),\n\t\t/** Optional; null or omitted keeps it open until the event closes. */\n\t\tendsAt: z.coerce.date().nullable().default(null),\n\t})\n\t.strict()\n\t.refine(\n\t\t(input) =>\n\t\t\tinput.startsAt === null ||\n\t\t\tinput.endsAt === null ||\n\t\t\tinput.endsAt > input.startsAt,\n\t\t{\n\t\t\tmessage: \"The session must end after it starts.\",\n\t\t\tpath: [\"endsAt\"],\n\t\t},\n\t);\n\nexport const setStaffRedemptionSlotSchema = staffRedemptionEventIdSchema\n\t.extend({\n\t\tsessionId: idSchema,\n\t\tsiteId: idSchema,\n\t\tsetQuantity: quantitySchema,\n\t})\n\t.strict();\n\nconst rolloverSessionsShape = {\n\tfromSessionId: idSchema.describe(\n\t\t\"Session whose leftover sets and prizes move out (id from setup get). Must belong to this event and not be archived.\",\n\t),\n\ttoSessionId: idSchema.describe(\n\t\t\"Session that receives them (id from setup get). Must differ from fromSessionId, belong to this event and not be archived.\",\n\t),\n};\n\nconst rolloverReasonSchema = (description: string) =>\n\tz\n\t\t.string()\n\t\t.trim()\n\t\t.min(1)\n\t\t.max(STAFF_REDEMPTION_ROLLOVER_REASON_MAX)\n\t\t.describe(description);\n\nexport const staffRedemptionRolloverPreviewSchema = staffRedemptionEventIdSchema\n\t.extend(rolloverSessionsShape)\n\t.strict();\n\nexport const rolloverStaffRedemptionStockSchema = staffRedemptionEventIdSchema\n\t.extend({\n\t\t...rolloverSessionsShape,\n\t\tsets: z\n\t\t\t.boolean()\n\t\t\t.default(true)\n\t\t\t.describe(\n\t\t\t\t\"Move the leftover sets (set quantity minus active, not voided, redemptions) of each site. Defaults to true.\",\n\t\t\t),\n\t\tprizes: z\n\t\t\t.boolean()\n\t\t\t.default(true)\n\t\t\t.describe(\n\t\t\t\t\"Move the leftover prizes (stock minus prizes drawn and not released) of each site. Defaults to true.\",\n\t\t\t),\n\t\treason: rolloverReasonSchema(\n\t\t\t\"Why the leftovers move (1 to 300 characters). Recorded in the activity log.\",\n\t\t),\n\t})\n\t.strict()\n\t.refine((input) => input.sets || input.prizes, {\n\t\tmessage: \"Choose sets, prizes or both.\",\n\t\tpath: [\"sets\"],\n\t});\n\nexport const staffRedemptionRolloversSchema = staffRedemptionEventIdSchema\n\t.extend({\n\t\tlimit: z\n\t\t\t.number()\n\t\t\t.int()\n\t\t\t.min(1)\n\t\t\t.max(STAFF_REDEMPTION_ROLLOVER_LIST_MAX)\n\t\t\t.default(STAFF_REDEMPTION_ROLLOVER_LIST_DEFAULT)\n\t\t\t.describe(\n\t\t\t\t\"How many rollovers to return, newest first (1 to 50). Defaults to 20.\",\n\t\t\t),\n\t})\n\t.strict();\n\nexport const undoStaffRedemptionRolloverSchema = staffRedemptionEventIdSchema\n\t.extend({\n\t\trolloverId: idSchema.describe(\n\t\t\t\"Id of the rollover to undo (id from rollover list). Must belong to this event and not be undone already.\",\n\t\t),\n\t\treason: rolloverReasonSchema(\n\t\t\t\"Why the rollover is undone (1 to 300 characters). Recorded in the activity log.\",\n\t\t),\n\t})\n\t.strict();\n\n// ---------------------------------------------------------------- catalogue and prizes\n\nexport const upsertStaffRedemptionItemGroupSchema = staffRedemptionEventIdSchema\n\t.extend({\n\t\tgroupId: idSchema.optional(),\n\t\tname: nameSchema,\n\t\torder: orderSchema.optional(),\n\t})\n\t.strict();\n\nexport const upsertStaffRedemptionItemSchema = staffRedemptionEventIdSchema\n\t.extend({\n\t\titemId: idSchema.optional(),\n\t\tgroupId: idSchema,\n\t\tname: nameSchema,\n\t\torder: orderSchema.optional(),\n\t})\n\t.strict();\n\nexport const upsertStaffRedemptionPrizeSchema = staffRedemptionEventIdSchema\n\t.extend({\n\t\tprizeId: idSchema.optional(),\n\t\tname: nameSchema,\n\t\torder: orderSchema.optional(),\n\t})\n\t.strict();\n\nexport const setStaffRedemptionPrizeStockSchema = staffRedemptionEventIdSchema\n\t.extend({\n\t\tslotId: idSchema,\n\t\tprizeId: idSchema,\n\t\tquantity: quantitySchema,\n\t\treason: reasonSchema.optional(),\n\t})\n\t.strict();\n\nexport const setStaffRedemptionArchivedSchema = staffRedemptionEventIdSchema\n\t.extend({\n\t\tentity: z.enum(STAFF_REDEMPTION_ARCHIVABLE),\n\t\tid: idSchema,\n\t\tarchived: z.boolean(),\n\t})\n\t.strict();\n\n// ---------------------------------------------------------------- roster\n\nexport const upsertStaffRedemptionRosterEntrySchema =\n\tstaffRedemptionEventIdSchema\n\t\t.extend({\n\t\t\temployeeId: staffRedemptionEmployeeIdSchema,\n\t\t\tname: z.string().trim().max(STAFF_REDEMPTION_NAME_MAX).nullable(),\n\t\t\tsiteName: z.string().trim().max(STAFF_REDEMPTION_NAME_MAX).nullable(),\n\t\t\tshift: staffRedemptionShiftSchema.nullable(),\n\t\t\tworkShift: z.string().trim().max(STAFF_REDEMPTION_NAME_MAX).nullable(),\n\t\t\tallowance: z\n\t\t\t\t.number()\n\t\t\t\t.int()\n\t\t\t\t.min(0)\n\t\t\t\t.max(STAFF_REDEMPTION_ALLOWANCE_MAX)\n\t\t\t\t.optional(),\n\t\t})\n\t\t.strict();\n\nconst rosterFiltersShape = {\n\tsearch: z.string().trim().max(200).optional(),\n\tsiteId: idSchema.optional(),\n\tshift: staffRedemptionShiftSchema.optional(),\n\tarchived: z.enum([\"active\", \"archived\", \"all\"]).default(\"active\"),\n\tcollected: z.enum([\"any\", \"collected\", \"not-collected\"]).default(\"any\"),\n};\n\nexport const staffRedemptionRosterListSchema = staffRedemptionEventIdSchema\n\t.extend({\n\t\t...rosterFiltersShape,\n\t\tlimit: z.number().int().min(1).max(STAFF_REDEMPTION_PAGE_MAX).default(25),\n\t\tcursor: z.string().min(1).max(8192).nullish(),\n\t\t// tRPC infinite queries always send the fetch direction; this list only pages forward.\n\t\tdirection: z.literal(\"forward\").optional(),\n\t})\n\t.strict();\n\nexport const staffRedemptionRosterCountsSchema = staffRedemptionEventIdSchema\n\t.extend(rosterFiltersShape)\n\t.strict();\n\n// ---------------------------------------------------------------- counter\n\n/** A counter request: the site is fixed for crew sessions and named by staff. */\nexport const staffRedemptionCounterSchema = staffRedemptionSiteIdSchema;\n\nexport const lookupStaffRedemptionSchema = staffRedemptionSiteIdSchema\n\t.extend({ employeeId: staffRedemptionEmployeeIdSchema })\n\t.strict();\n\nconst claimItemIdsSchema = z\n\t.array(idSchema)\n\t.max(STAFF_REDEMPTION_CLAIM_ITEMS_MAX)\n\t.refine((ids) => new Set(ids).size === ids.length, {\n\t\tmessage: \"Pick each item once.\",\n\t});\n\n/** Under DRAW_THEN_FOOD, `itemIds` must be empty: the items are recorded on the claim after the draw. */\nexport const redeemStaffRedemptionSchema = staffRedemptionSiteIdSchema\n\t.extend({\n\t\temployeeId: staffRedemptionEmployeeIdSchema,\n\t\tclientRequestId: staffRedemptionClientRequestIdSchema,\n\t\titemIds: claimItemIdsSchema,\n\t})\n\t.strict();\n\n/**\n * Records the items of a draw-first claim whose items are still pending. A\n * counter at the claim's serving site (crew session for that site, or staff\n * with `event.operate`) may record them. Sending the same items again returns\n * the stored claim; different items once recorded are a CONFLICT.\n */\nexport const recordStaffRedemptionClaimItemsSchema = staffRedemptionSiteIdSchema\n\t.extend({\n\t\tclaimId: idSchema,\n\t\titemIds: claimItemIdsSchema,\n\t})\n\t.strict();\n\n/** \"mine\": claims made by this device (crew) or by me (staff). \"site\": every claim at the site. */\nexport const STAFF_REDEMPTION_COUNTER_CLAIM_SCOPES = [\"mine\", \"site\"] as const;\nexport type StaffRedemptionCounterClaimScope =\n\t(typeof STAFF_REDEMPTION_COUNTER_CLAIM_SCOPES)[number];\n\nexport const staffRedemptionCounterClaimsSchema = staffRedemptionSiteIdSchema\n\t.extend({\n\t\tlimit: z.number().int().min(1).max(50).default(20),\n\t\tscope: z.enum(STAFF_REDEMPTION_COUNTER_CLAIM_SCOPES).default(\"mine\"),\n\t\tstatus: z.enum([\"all\", \"items-pending\"]).default(\"all\"),\n\t})\n\t.strict();\n\n// ---------------------------------------------------------------- claims (managers)\n\n/**\n * \"items-pending\": active draw-first claims whose items are not recorded yet\n * (a subset of \"active\").\n */\nexport const STAFF_REDEMPTION_CLAIM_STATUSES = [\n\t\"active\",\n\t\"items-pending\",\n\t\"voided\",\n\t\"all\",\n] as const;\nexport type StaffRedemptionClaimStatus =\n\t(typeof STAFF_REDEMPTION_CLAIM_STATUSES)[number];\n\nconst claimFiltersShape = {\n\tsearch: z.string().trim().max(200).optional(),\n\tsiteId: idSchema.optional(),\n\tsessionId: idSchema.optional(),\n\tstatus: z.enum(STAFF_REDEMPTION_CLAIM_STATUSES).default(\"all\"),\n};\n\nexport const staffRedemptionClaimListSchema = staffRedemptionEventIdSchema\n\t.extend({\n\t\t...claimFiltersShape,\n\t\tlimit: z.number().int().min(1).max(STAFF_REDEMPTION_PAGE_MAX).default(25),\n\t\tcursor: z.string().min(1).max(8192).nullish(),\n\t\tdirection: z.literal(\"forward\").optional(),\n\t})\n\t.strict();\n\nexport const staffRedemptionClaimCountsSchema = staffRedemptionEventIdSchema\n\t.extend(claimFiltersShape)\n\t.strict();\n\nexport const voidStaffRedemptionClaimSchema = staffRedemptionEventIdSchema\n\t.extend({ claimId: idSchema, reason: reasonSchema })\n\t.strict();\n\n/**\n * `allowWhileClaimActive` is the explicit manager/CLI override: without it a\n * draw that an active (not voided) redemption still shows cannot be released.\n * The web app never sends it.\n */\nexport const releaseStaffRedemptionDrawSchema = staffRedemptionEventIdSchema\n\t.extend({\n\t\tdrawId: idSchema,\n\t\treason: reasonSchema,\n\t\tallowWhileClaimActive: z\n\t\t\t.boolean()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t\"Override: release the draw even though an active (not voided) redemption still shows it, for a redemption that stays recorded (for example a paper entry with no spin). Omit to refuse while any active redemption uses the draw.\",\n\t\t\t),\n\t})\n\t.strict();\n\nexport const staffRedemptionExportSchema = staffRedemptionEventIdSchema\n\t.extend(claimFiltersShape)\n\t.strict();\n", "import { normalizePassportRosterKey } from \"@go-labs/event-tech-validators/event-passport/passport-roster.schema\";\nimport { z } from \"zod\";\nimport {\n\tSTAFF_REDEMPTION_ALLOWANCE_MAX,\n\tSTAFF_REDEMPTION_EMPLOYEE_ID_MAX,\n\tSTAFF_REDEMPTION_NAME_MAX,\n\tSTAFF_REDEMPTION_SHIFT_MAX,\n\tstaffRedemptionEventIdSchema,\n} from \"./staff-redemption-input.schema\";\n\nexport const STAFF_REDEMPTION_ROSTER_IMPORT_MAX = 20_000;\n\n/**\n * Matching key for an Employee ID or site name: case-insensitive, ignoring\n * whitespace, punctuation and accents (the #2254 Staff ID rule).\n */\nexport const normalizeStaffRedemptionKey = normalizePassportRosterKey;\n\n/** One mapped spreadsheet row. `row` is the 1-based row number in the file. */\nexport const staffRedemptionRosterImportRowSchema = z\n\t.object({\n\t\trow: z.number().int().min(1),\n\t\temployeeId: z.string().max(1000),\n\t\tname: z.string().max(1000).nullable(),\n\t\tsiteName: z.string().max(1000).nullable(),\n\t\tshift: z.string().max(1000).nullable(),\n\t\tworkShift: z.string().max(1000).nullable(),\n\t\t/** Raw cell text; blank means 1. */\n\t\tallowance: z.string().max(1000).nullable(),\n\t})\n\t.strict();\nexport type StaffRedemptionRosterImportRow = z.infer<\n\ttypeof staffRedemptionRosterImportRowSchema\n>;\n\nexport const importStaffRedemptionRosterSchema = staffRedemptionEventIdSchema\n\t.extend({\n\t\trows: z\n\t\t\t.array(staffRedemptionRosterImportRowSchema)\n\t\t\t.min(1)\n\t\t\t.max(\n\t\t\t\tSTAFF_REDEMPTION_ROSTER_IMPORT_MAX,\n\t\t\t\t`A roster can have at most ${STAFF_REDEMPTION_ROSTER_IMPORT_MAX} rows.`,\n\t\t\t),\n\t\t/** Archive active entries whose Employee ID is not in this file. */\n\t\tarchiveMissing: z.boolean().default(false),\n\t})\n\t.strict();\n\nexport const STAFF_REDEMPTION_ROSTER_REJECT_REASONS = [\n\t\"MISSING_EMPLOYEE_ID\",\n\t\"DUPLICATE_EMPLOYEE_ID\",\n\t\"TOO_LONG\",\n\t\"BAD_SHIFT\",\n\t\"BAD_ALLOWANCE\",\n] as const;\nexport type StaffRedemptionRosterRejectReason =\n\t(typeof STAFF_REDEMPTION_ROSTER_REJECT_REASONS)[number];\n\nexport interface StaffRedemptionRosterRejectedRow {\n\trow: number;\n\temployeeId: string;\n\treason: StaffRedemptionRosterRejectReason;\n}\n\nexport interface PreparedStaffRedemptionRosterEntry {\n\trow: number;\n\temployeeId: string;\n\temployeeIdKey: string;\n\tname: string | null;\n\tsiteName: string | null;\n\t/** `normalizeStaffRedemptionKey(siteName)`, for matching a site. */\n\tsiteNameKey: string | null;\n\tshift: string | null;\n\tworkShift: string | null;\n\tallowance: number;\n}\n\nconst blankToNull = (value: string | null) => {\n\tconst trimmed = value?.trim() ?? \"\";\n\treturn trimmed === \"\" ? null : trimmed;\n};\n\nconst rejectReason = (\n\trow: StaffRedemptionRosterImportRow,\n): StaffRedemptionRosterRejectReason | null => {\n\tconst employeeId = row.employeeId.trim();\n\tif (!employeeId || !normalizeStaffRedemptionKey(employeeId))\n\t\treturn \"MISSING_EMPLOYEE_ID\";\n\tif (\n\t\temployeeId.length > STAFF_REDEMPTION_EMPLOYEE_ID_MAX ||\n\t\t(row.name?.trim().length ?? 0) > STAFF_REDEMPTION_NAME_MAX ||\n\t\t(row.siteName?.trim().length ?? 0) > STAFF_REDEMPTION_NAME_MAX ||\n\t\t(row.workShift?.trim().length ?? 0) > STAFF_REDEMPTION_NAME_MAX\n\t)\n\t\treturn \"TOO_LONG\";\n\tconst shift = blankToNull(row.shift);\n\tif (\n\t\tshift !== null &&\n\t\t(shift.length > STAFF_REDEMPTION_SHIFT_MAX || !/^[A-Za-z0-9]+$/.test(shift))\n\t)\n\t\treturn \"BAD_SHIFT\";\n\tconst allowance = blankToNull(row.allowance);\n\tif (allowance !== null) {\n\t\tconst parsed = Number(allowance);\n\t\tif (\n\t\t\t!Number.isInteger(parsed) ||\n\t\t\tparsed < 0 ||\n\t\t\tparsed > STAFF_REDEMPTION_ALLOWANCE_MAX\n\t\t)\n\t\t\treturn \"BAD_ALLOWANCE\";\n\t}\n\treturn null;\n};\n\n/**\n * Validates mapped rows: the first occurrence of an Employee ID wins and later\n * ones are rejected as duplicates. Pure, so the web, the CLI and the server\n * report the same rejected rows.\n */\nexport const prepareStaffRedemptionRosterImport = (\n\trows: readonly StaffRedemptionRosterImportRow[],\n) => {\n\tconst entries: PreparedStaffRedemptionRosterEntry[] = [];\n\tconst rejected: StaffRedemptionRosterRejectedRow[] = [];\n\tconst seen = new Set<string>();\n\tfor (const row of rows) {\n\t\tconst reason = rejectReason(row);\n\t\tif (reason) {\n\t\t\trejected.push({\n\t\t\t\trow: row.row,\n\t\t\t\temployeeId: row.employeeId.trim(),\n\t\t\t\treason,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst employeeId = row.employeeId.trim();\n\t\tconst employeeIdKey = normalizeStaffRedemptionKey(employeeId);\n\t\tif (seen.has(employeeIdKey)) {\n\t\t\trejected.push({\n\t\t\t\trow: row.row,\n\t\t\t\temployeeId,\n\t\t\t\treason: \"DUPLICATE_EMPLOYEE_ID\",\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(employeeIdKey);\n\t\tconst siteName = blankToNull(row.siteName);\n\t\tconst allowance = blankToNull(row.allowance);\n\t\tentries.push({\n\t\t\trow: row.row,\n\t\t\temployeeId,\n\t\t\temployeeIdKey,\n\t\t\tname: blankToNull(row.name),\n\t\t\tsiteName,\n\t\t\tsiteNameKey: siteName ? normalizeStaffRedemptionKey(siteName) : null,\n\t\t\tshift: blankToNull(row.shift)?.toUpperCase() ?? null,\n\t\t\tworkShift: blankToNull(row.workShift),\n\t\t\tallowance: allowance === null ? 1 : Number(allowance),\n\t\t});\n\t}\n\treturn { entries, rejected };\n};\n\n/** Zero-based column indexes in the file. Null skips an optional column. */\nexport interface StaffRedemptionRosterColumnMapping {\n\temployeeId: number;\n\tname: number | null;\n\tsiteName: number | null;\n\tshift: number | null;\n\tworkShift: number | null;\n\tallowance: number | null;\n}\n\nconst HEADER_PATTERNS: Record<\n\tkeyof StaffRedemptionRosterColumnMapping,\n\tRegExp\n> = {\n\temployeeId: /^(employee|staff|worker)\\s*(id|no|number)$|^(emp|staff)\\s*id$/i,\n\tname: /^(worker|name|full\\s*name|employee\\s*name|staff\\s*name)$/i,\n\tsiteName: /^(site|location|fab)$/i,\n\tshift: /^shift$/i,\n\tworkShift: /^work\\s*shift$/i,\n\tallowance: /^(allowance|sets|entitlement|balance)$/i,\n};\n\n/** Guesses columns from the header row. Employee ID falls back to column 0. */\nexport const guessStaffRedemptionRosterMapping = (\n\theader: readonly string[],\n): StaffRedemptionRosterColumnMapping => {\n\tconst find = (key: keyof StaffRedemptionRosterColumnMapping) => {\n\t\tconst index = header.findIndex((cell) =>\n\t\t\tHEADER_PATTERNS[key].test(cell.trim()),\n\t\t);\n\t\treturn index === -1 ? null : index;\n\t};\n\treturn {\n\t\temployeeId: find(\"employeeId\") ?? 0,\n\t\tname: find(\"name\"),\n\t\tsiteName: find(\"siteName\"),\n\t\tshift: find(\"shift\"),\n\t\tworkShift: find(\"workShift\"),\n\t\tallowance: find(\"allowance\"),\n\t};\n};\n\n/**\n * Turns a parsed table (header first) into import rows, skipping fully blank\n * lines. Row numbers are 1-based file rows, so the header is row 1.\n */\nexport const mapStaffRedemptionRosterTable = (\n\ttable: readonly (readonly string[])[],\n\tmapping: StaffRedemptionRosterColumnMapping,\n): StaffRedemptionRosterImportRow[] => {\n\tconst cell = (line: readonly string[], index: number | null) =>\n\t\tindex === null ? null : (line[index] ?? \"\");\n\tconst rows: StaffRedemptionRosterImportRow[] = [];\n\ttable.slice(1).forEach((line, offset) => {\n\t\tif (line.every((value) => !value?.trim())) return;\n\t\trows.push({\n\t\t\trow: offset + 2,\n\t\t\temployeeId: line[mapping.employeeId] ?? \"\",\n\t\t\tname: cell(line, mapping.name),\n\t\t\tsiteName: cell(line, mapping.siteName),\n\t\t\tshift: cell(line, mapping.shift),\n\t\t\tworkShift: cell(line, mapping.workShift),\n\t\t\tallowance: cell(line, mapping.allowance),\n\t\t});\n\t});\n\tif (rows.length > STAFF_REDEMPTION_ROSTER_IMPORT_MAX)\n\t\tthrow new Error(\n\t\t\t`A roster can have at most ${STAFF_REDEMPTION_ROSTER_IMPORT_MAX} rows.`,\n\t\t);\n\treturn rows;\n};\n", "import { api } from \"@go-labs-sg/event-tech/api-client\";\nimport {\n\tassertOnlyFlags,\n\tgetOptionalFlag,\n\ttype ParsedArguments,\n\treadInlineOrFile,\n} from \"@go-labs-sg/event-tech/arguments\";\nimport commandManifest from \"@go-labs-sg/event-tech/registry/command-manifest.json\";\nimport {\n\ttype CliRuntime,\n\tCliUsageError,\n\twriteSuccess,\n} from \"@go-labs-sg/event-tech/runtime\";\n\ninterface ManifestInputSchema {\n\tproperties?: Record<string, unknown>;\n\trequired?: readonly string[];\n}\n\ninterface ManifestEntry {\n\tpath: readonly string[];\n\tprocedure: string;\n\toperation: string;\n\tsummary: string;\n\teffects: readonly string[];\n\ttarget?: string;\n\tdates: readonly string[];\n\tinput: ManifestInputSchema | null;\n}\n\ninterface ProcedureClient {\n\tmutate: (input?: unknown) => Promise<unknown>;\n\tquery: (input?: unknown) => Promise<unknown>;\n}\n\nconst manifest: readonly ManifestEntry[] = commandManifest;\n\nconst registryFlags = [\n\t\"input\",\n\t\"input-file\",\n\t\"allow-state-change\",\n\t\"allow-delete\",\n\t\"allow-email\",\n\t\"target\",\n] as const;\n\nconst isoDateTimePattern = /^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d/;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === \"object\" && value !== null && !Array.isArray(value);\n\nexport const commandName = (entry: ManifestEntry): string =>\n\t`et ${entry.path.join(\" \")}`;\n\nexport const findManifestEntry = (\n\tpositionals: readonly string[],\n): ManifestEntry | undefined =>\n\tmanifest.find(\n\t\t(entry) =>\n\t\t\tentry.path.length === positionals.length &&\n\t\t\tentry.path.every((segment, index) => positionals[index] === segment),\n\t);\n\nexport const listRegistryCommands = () =>\n\tmanifest.map((entry) => ({\n\t\tcommand: commandName(entry),\n\t\tsummary: entry.summary,\n\t\teffects: entry.effects,\n\t}));\n\nconst coerceDateAt = (\n\tvalue: unknown,\n\tsegments: readonly string[],\n\tlabel: string,\n): unknown => {\n\tconst [head, ...rest] = segments;\n\tif (head === undefined) {\n\t\tif (typeof value !== \"string\") return value;\n\t\tconst parsed = new Date(value);\n\t\tif (!isoDateTimePattern.test(value) || Number.isNaN(parsed.getTime())) {\n\t\t\tthrow new CliUsageError(\n\t\t\t\t`${label} must be an ISO 8601 date-time such as 2026-11-20T18:00:00+08:00.`,\n\t\t\t);\n\t\t}\n\t\treturn parsed;\n\t}\n\tconst isArray = head.endsWith(\"[]\");\n\tconst key = isArray ? head.slice(0, -2) : head;\n\tconst apply = (child: unknown) =>\n\t\tisArray\n\t\t\t? Array.isArray(child)\n\t\t\t\t? child.map((item) => coerceDateAt(item, rest, label))\n\t\t\t\t: child\n\t\t\t: coerceDateAt(child, rest, label);\n\tif (key === \"\") return apply(value);\n\tif (!isRecord(value) || !(key in value)) return value;\n\treturn { ...value, [key]: apply(value[key]) };\n};\n\n/** Converts ISO strings at the procedure's Date fields; SuperJSON sends real Dates. */\nexport const coerceDates = (\n\tinput: unknown,\n\tdatePaths: readonly string[],\n): unknown =>\n\tdatePaths.reduce(\n\t\t(current, path) =>\n\t\t\tcoerceDateAt(\n\t\t\t\tcurrent,\n\t\t\t\tpath === \"\" ? [] : path.split(\".\"),\n\t\t\t\tpath || \"input\",\n\t\t\t),\n\t\tinput,\n\t);\n\nconst readInput = async (\n\tparsed: ParsedArguments,\n\tentry: ManifestEntry,\n): Promise<unknown> => {\n\tconst provided = parsed.flags.has(\"input\") || parsed.flags.has(\"input-file\");\n\tif (!entry.input) {\n\t\tif (provided) {\n\t\t\tthrow new CliUsageError(`${commandName(entry)} does not take --input.`);\n\t\t}\n\t\treturn undefined;\n\t}\n\tif (!provided) {\n\t\tif ((entry.input.required ?? []).length > 0) {\n\t\t\tthrow new CliUsageError(\n\t\t\t\t`${commandName(entry)} requires --input or --input-file with ${entry.input.required?.join(\", \")}. Run it with --help for the schema.`,\n\t\t\t);\n\t\t}\n\t\treturn {};\n\t}\n\tconst raw = await readInlineOrFile(parsed, \"input\", \"input-file\");\n\tlet value: unknown;\n\ttry {\n\t\tvalue = JSON.parse(raw);\n\t} catch {\n\t\tthrow new CliUsageError(\"--input must be valid JSON.\");\n\t}\n\tif (!isRecord(value)) {\n\t\tthrow new CliUsageError(\"--input must be a JSON object.\");\n\t}\n\treturn coerceDates(value, entry.dates);\n};\n\nconst targetText = (value: unknown): string | undefined => {\n\tif (typeof value === \"string\" || typeof value === \"number\") {\n\t\treturn String(value);\n\t}\n\tif (\n\t\tArray.isArray(value) &&\n\t\tvalue.length > 0 &&\n\t\tvalue.every((item) => typeof item === \"string\")\n\t) {\n\t\treturn value.join(\",\");\n\t}\n\treturn undefined;\n};\n\n/** Writes need every `--allow-<effect>` and `--target` equal to the input's target key. */\nexport const assertConfirmed = (\n\tparsed: ParsedArguments,\n\tentry: ManifestEntry,\n\tinput: unknown,\n): void => {\n\tif (entry.effects.length === 0) return;\n\tconst missing = entry.effects\n\t\t.map((effect) => `allow-${effect}`)\n\t\t.filter((flag) => parsed.flags.get(flag) !== true);\n\tif (missing.length > 0) {\n\t\tthrow new CliUsageError(\n\t\t\t`${commandName(entry)} requires ${missing.map((flag) => `--${flag}`).join(\" \")} as explicit acknowledgement.`,\n\t\t);\n\t}\n\tif (!entry.target) return;\n\tconst expected = targetText(\n\t\tisRecord(input) ? input[entry.target] : undefined,\n\t);\n\tif (expected === undefined) {\n\t\tthrow new CliUsageError(\n\t\t\t`--input must include ${entry.target} so the target can be confirmed.`,\n\t\t);\n\t}\n\tif (getOptionalFlag(parsed, \"target\") !== expected) {\n\t\tthrow new CliUsageError(\n\t\t\t`--target must exactly match input.${entry.target} (${expected}).`,\n\t\t);\n\t}\n};\n\nconst describe = (entry: ManifestEntry) => ({\n\tcommand: commandName(entry),\n\tsummary: entry.summary,\n\tprocedure: entry.procedure,\n\toperation: entry.operation,\n\teffects: entry.effects,\n\tconfirmation:\n\t\tentry.effects.length > 0\n\t\t\t? [\n\t\t\t\t\t...entry.effects.map((effect) => `--allow-${effect}`),\n\t\t\t\t\t...(entry.target\n\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t`--target <input.${entry.target}${entry.target.endsWith(\"s\") ? \" joined with commas\" : \"\"}>`,\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t: []),\n\t\t\t\t]\n\t\t\t: [],\n\tinput: entry.input\n\t\t? \"--input '<json>' or --input-file <path> matching inputSchema\"\n\t\t: \"none\",\n\tdateFields: entry.dates,\n\tinputSchema: entry.input,\n});\n\nconst resolveProcedureClient = (procedure: string): ProcedureClient =>\n\tprocedure\n\t\t.split(\".\")\n\t\t.reduce<unknown>(\n\t\t\t(node, segment) => (node as Record<string, unknown>)[segment],\n\t\t\tapi,\n\t\t) as ProcedureClient;\n\n/** Runs a generic registry command. Returns false when the positionals match none. */\nexport const runRegistryCommand = async (input: {\n\tparsed: ParsedArguments;\n\truntime: CliRuntime;\n\tauthenticate: () => Promise<void>;\n}): Promise<boolean> => {\n\tconst { parsed, runtime, authenticate } = input;\n\tconst entry = findManifestEntry(parsed.positionals);\n\tif (!entry) return false;\n\tif (parsed.flags.has(\"help\")) {\n\t\tassertOnlyFlags(parsed, [\"help\"]);\n\t\twriteSuccess(runtime, describe(entry));\n\t\treturn true;\n\t}\n\tassertOnlyFlags(parsed, registryFlags);\n\tconst procedureInput = await readInput(parsed, entry);\n\tassertConfirmed(parsed, entry, procedureInput);\n\tawait authenticate();\n\tconst client = resolveProcedureClient(entry.procedure);\n\twriteSuccess(\n\t\truntime,\n\t\tentry.operation === \"query\"\n\t\t\t? await client.query(procedureInput)\n\t\t\t: await client.mutate(procedureInput),\n\t);\n\treturn true;\n};\n", "#!/usr/bin/env bun\nimport \"@go-labs-sg/event-tech/load-env\";\nimport { assertBunRuntime } from \"@go-labs/cli-auth/client\";\nimport { runCli } from \"@go-labs-sg/event-tech/cli\";\n\nexport { runCli } from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EAAA,SACCQ,QAAO;AACf,WAAA,WAAW,SAASA,MAAK,GAClBA,kBAAiB,gBAAgB,IAAI;EAAA;AAAA,GAvBxB,QAAA;A0C9yBlB,YAAA,SACH,iBAAiB,GACjB,QAAQ,WAAW,MAAM,OAAO,QAAQ,KAAK,MAAM,CAAC,CAAC;",
6
+ "names": ["__name", "isObject", "err", "object", "keys", "n", "resolve", "reject", "error", "i", "base64", "array", "transform", "path", "node", "errorCode", "date", "file", "data", "serialize", "config", "xhr", "aborted", "row", "value", "_a", "initializer", "own", "proto", "issue", "parseAsync", "version", "result", "checks", "checkResult", "canary", "hostname", "memo", "r", "isObject2", "results", "left", "right", "output", "cached", "merge", "json", "id", "schema", "members", "required", "union", "issues", "_parse", "_parseAsync", "_encode", "_decode", "_encodeAsync", "_decodeAsync", "failure", "directoryStat", "payload", "observable", "settle", "o", "t", "e", "TRPCClientError", "WsConnection", "unknown", "open", "text", "cell", "flag", "email"]
7
+ }